diff --git a/data/miniconda3/lib/python3.13/__phello__/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/__phello__/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71061cccd5ce3b62e49c514223eb0692945454c9 Binary files /dev/null and b/data/miniconda3/lib/python3.13/__phello__/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/__phello__/__pycache__/spam.cpython-313.pyc b/data/miniconda3/lib/python3.13/__phello__/__pycache__/spam.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..345e067d39843e2e64193b0fda44cb8978b7b6a6 Binary files /dev/null and b/data/miniconda3/lib/python3.13/__phello__/__pycache__/spam.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/ctypes/macholib/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/ctypes/macholib/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad8174221cb621705ad5dc76af4cfde1ba6a7980 Binary files /dev/null and b/data/miniconda3/lib/python3.13/ctypes/macholib/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/ctypes/macholib/__pycache__/dyld.cpython-313.pyc b/data/miniconda3/lib/python3.13/ctypes/macholib/__pycache__/dyld.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..217920296bb979dcfe1d72d52af35baeec5f00af Binary files /dev/null and b/data/miniconda3/lib/python3.13/ctypes/macholib/__pycache__/dyld.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/ctypes/macholib/__pycache__/dylib.cpython-313.pyc b/data/miniconda3/lib/python3.13/ctypes/macholib/__pycache__/dylib.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a8026684f0b092e9d2b4f1a9368a1e29b230f5fd Binary files /dev/null and b/data/miniconda3/lib/python3.13/ctypes/macholib/__pycache__/dylib.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/email/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/email/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..731f8bc5445cb209bdeb4ad8fcc6606e9771d77f Binary files /dev/null and b/data/miniconda3/lib/python3.13/email/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/email/__pycache__/_encoded_words.cpython-313.pyc b/data/miniconda3/lib/python3.13/email/__pycache__/_encoded_words.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b3141c237f7fd7ccd2f8e2d780fa470683e3fa18 Binary files /dev/null and b/data/miniconda3/lib/python3.13/email/__pycache__/_encoded_words.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/email/__pycache__/_parseaddr.cpython-313.pyc b/data/miniconda3/lib/python3.13/email/__pycache__/_parseaddr.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..14851171d3dd9065296f9731d9c99227cf9e324d Binary files /dev/null and b/data/miniconda3/lib/python3.13/email/__pycache__/_parseaddr.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/email/__pycache__/_policybase.cpython-313.pyc b/data/miniconda3/lib/python3.13/email/__pycache__/_policybase.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c54fabf333fe4f86766a6fa8c51546a0e90bc584 Binary files /dev/null and b/data/miniconda3/lib/python3.13/email/__pycache__/_policybase.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/email/__pycache__/base64mime.cpython-313.pyc b/data/miniconda3/lib/python3.13/email/__pycache__/base64mime.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..952920a1988f464b0abbbaa90d5b296f3508f546 Binary files /dev/null and b/data/miniconda3/lib/python3.13/email/__pycache__/base64mime.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/email/__pycache__/charset.cpython-313.pyc b/data/miniconda3/lib/python3.13/email/__pycache__/charset.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bcd2460ce6a2ca6d267eee621079dd7a20f1517a Binary files /dev/null and b/data/miniconda3/lib/python3.13/email/__pycache__/charset.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/email/__pycache__/contentmanager.cpython-313.pyc b/data/miniconda3/lib/python3.13/email/__pycache__/contentmanager.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a617f47da221a7c8213fae5911a9bda3fba789a8 Binary files /dev/null and b/data/miniconda3/lib/python3.13/email/__pycache__/contentmanager.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/email/__pycache__/encoders.cpython-313.pyc b/data/miniconda3/lib/python3.13/email/__pycache__/encoders.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3602d9a005f69af0e4bc809eae60699143c5de10 Binary files /dev/null and b/data/miniconda3/lib/python3.13/email/__pycache__/encoders.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/email/__pycache__/errors.cpython-313.pyc b/data/miniconda3/lib/python3.13/email/__pycache__/errors.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8809436c57bd9669dd8efa0159053c045f71db71 Binary files /dev/null and b/data/miniconda3/lib/python3.13/email/__pycache__/errors.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/email/__pycache__/feedparser.cpython-313.pyc b/data/miniconda3/lib/python3.13/email/__pycache__/feedparser.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..50c16f749366b9b5b440e0f95a54ed7f97156888 Binary files /dev/null and b/data/miniconda3/lib/python3.13/email/__pycache__/feedparser.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/email/__pycache__/generator.cpython-313.pyc b/data/miniconda3/lib/python3.13/email/__pycache__/generator.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78fe451e85ec51bdb26304bbd7d018e68f7ac316 Binary files /dev/null and b/data/miniconda3/lib/python3.13/email/__pycache__/generator.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/email/__pycache__/header.cpython-313.pyc b/data/miniconda3/lib/python3.13/email/__pycache__/header.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..21db6a1ac7554a2688580c5d603392778ffa70cf Binary files /dev/null and b/data/miniconda3/lib/python3.13/email/__pycache__/header.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/email/__pycache__/headerregistry.cpython-313.pyc b/data/miniconda3/lib/python3.13/email/__pycache__/headerregistry.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b97dd25d446dcc4ff98847a9d1b1f857e0e3ba7f Binary files /dev/null and b/data/miniconda3/lib/python3.13/email/__pycache__/headerregistry.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/email/__pycache__/iterators.cpython-313.pyc b/data/miniconda3/lib/python3.13/email/__pycache__/iterators.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..59a067d932f41544baf2b0a5bccb09fc5300fb86 Binary files /dev/null and b/data/miniconda3/lib/python3.13/email/__pycache__/iterators.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/email/__pycache__/message.cpython-313.pyc b/data/miniconda3/lib/python3.13/email/__pycache__/message.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf57ccc9a01d5cfb7b43c7b497d46282c50139ee Binary files /dev/null and b/data/miniconda3/lib/python3.13/email/__pycache__/message.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/email/__pycache__/parser.cpython-313.pyc b/data/miniconda3/lib/python3.13/email/__pycache__/parser.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee87718d3e318f96e0d36e4856647a5bb4291f37 Binary files /dev/null and b/data/miniconda3/lib/python3.13/email/__pycache__/parser.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/email/__pycache__/policy.cpython-313.pyc b/data/miniconda3/lib/python3.13/email/__pycache__/policy.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f6c269da2f0ee41bc85e51d229594add85721499 Binary files /dev/null and b/data/miniconda3/lib/python3.13/email/__pycache__/policy.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/email/__pycache__/quoprimime.cpython-313.pyc b/data/miniconda3/lib/python3.13/email/__pycache__/quoprimime.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..47e4ca0cca3207ff00ce93a74aecc89a636efacc Binary files /dev/null and b/data/miniconda3/lib/python3.13/email/__pycache__/quoprimime.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/email/__pycache__/utils.cpython-313.pyc b/data/miniconda3/lib/python3.13/email/__pycache__/utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..35ee667c85e79f53bebb6058fc5f1a763e5fd414 Binary files /dev/null and b/data/miniconda3/lib/python3.13/email/__pycache__/utils.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/email/mime/__init__.py b/data/miniconda3/lib/python3.13/email/mime/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/lib/python3.13/email/mime/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/email/mime/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..47fa12f21616102642442721d76338c5647bc45e Binary files /dev/null and b/data/miniconda3/lib/python3.13/email/mime/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/email/mime/__pycache__/application.cpython-313.pyc b/data/miniconda3/lib/python3.13/email/mime/__pycache__/application.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d9ffd5625ce7630c7f8a27a38a718ad236e2ff4 Binary files /dev/null and b/data/miniconda3/lib/python3.13/email/mime/__pycache__/application.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/email/mime/__pycache__/audio.cpython-313.pyc b/data/miniconda3/lib/python3.13/email/mime/__pycache__/audio.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d0038647d881283085529e61b387979a74799e5 Binary files /dev/null and b/data/miniconda3/lib/python3.13/email/mime/__pycache__/audio.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/email/mime/__pycache__/base.cpython-313.pyc b/data/miniconda3/lib/python3.13/email/mime/__pycache__/base.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..56ee58247a8f154c1c1c2a0d0d08091e9d3b1020 Binary files /dev/null and b/data/miniconda3/lib/python3.13/email/mime/__pycache__/base.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/email/mime/__pycache__/image.cpython-313.pyc b/data/miniconda3/lib/python3.13/email/mime/__pycache__/image.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf465a3a130dbc22299ddc511662acc02ccd1802 Binary files /dev/null and b/data/miniconda3/lib/python3.13/email/mime/__pycache__/image.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/email/mime/__pycache__/message.cpython-313.pyc b/data/miniconda3/lib/python3.13/email/mime/__pycache__/message.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2eea4d3b452485f6fff2c164989c34b2e1dd1912 Binary files /dev/null and b/data/miniconda3/lib/python3.13/email/mime/__pycache__/message.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/email/mime/__pycache__/multipart.cpython-313.pyc b/data/miniconda3/lib/python3.13/email/mime/__pycache__/multipart.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e39f9cae200b26d3be518fced07dfc1e12585eb Binary files /dev/null and b/data/miniconda3/lib/python3.13/email/mime/__pycache__/multipart.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/email/mime/__pycache__/nonmultipart.cpython-313.pyc b/data/miniconda3/lib/python3.13/email/mime/__pycache__/nonmultipart.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49875c56dcfca70933b0e25149c1c2aa11fcd3ef Binary files /dev/null and b/data/miniconda3/lib/python3.13/email/mime/__pycache__/nonmultipart.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/email/mime/__pycache__/text.cpython-313.pyc b/data/miniconda3/lib/python3.13/email/mime/__pycache__/text.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac87653cf556f2d6200f994847e822d8a2a8c2af Binary files /dev/null and b/data/miniconda3/lib/python3.13/email/mime/__pycache__/text.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/email/mime/application.py b/data/miniconda3/lib/python3.13/email/mime/application.py new file mode 100644 index 0000000000000000000000000000000000000000..f67cbad3f03407618de8f7ae1b2a86fc913e62f8 --- /dev/null +++ b/data/miniconda3/lib/python3.13/email/mime/application.py @@ -0,0 +1,37 @@ +# Copyright (C) 2001-2006 Python Software Foundation +# Author: Keith Dart +# Contact: email-sig@python.org + +"""Class representing application/* type MIME documents.""" + +__all__ = ["MIMEApplication"] + +from email import encoders +from email.mime.nonmultipart import MIMENonMultipart + + +class MIMEApplication(MIMENonMultipart): + """Class for generating application/* MIME documents.""" + + def __init__(self, _data, _subtype='octet-stream', + _encoder=encoders.encode_base64, *, policy=None, **_params): + """Create an application/* type MIME document. + + _data contains the bytes for the raw application data. + + _subtype is the MIME content type subtype, defaulting to + 'octet-stream'. + + _encoder is a function which will perform the actual encoding for + transport of the application data, defaulting to base64 encoding. + + Any additional keyword arguments are passed to the base class + constructor, which turns them into parameters on the Content-Type + header. + """ + if _subtype is None: + raise TypeError('Invalid application MIME subtype') + MIMENonMultipart.__init__(self, 'application', _subtype, policy=policy, + **_params) + self.set_payload(_data) + _encoder(self) diff --git a/data/miniconda3/lib/python3.13/email/mime/audio.py b/data/miniconda3/lib/python3.13/email/mime/audio.py new file mode 100644 index 0000000000000000000000000000000000000000..aa0c4905cbb2b4d8dfb7529057e2bca8424de569 --- /dev/null +++ b/data/miniconda3/lib/python3.13/email/mime/audio.py @@ -0,0 +1,97 @@ +# Copyright (C) 2001-2007 Python Software Foundation +# Author: Anthony Baxter +# Contact: email-sig@python.org + +"""Class representing audio/* type MIME documents.""" + +__all__ = ['MIMEAudio'] + +from email import encoders +from email.mime.nonmultipart import MIMENonMultipart + + +class MIMEAudio(MIMENonMultipart): + """Class for generating audio/* MIME documents.""" + + def __init__(self, _audiodata, _subtype=None, + _encoder=encoders.encode_base64, *, policy=None, **_params): + """Create an audio/* type MIME document. + + _audiodata contains the bytes for the raw audio data. If this data + can be decoded as au, wav, aiff, or aifc, then the + subtype will be automatically included in the Content-Type header. + Otherwise, you can specify the specific audio subtype via the + _subtype parameter. If _subtype is not given, and no subtype can be + guessed, a TypeError is raised. + + _encoder is a function which will perform the actual encoding for + transport of the image data. It takes one argument, which is this + Image instance. It should use get_payload() and set_payload() to + change the payload to the encoded form. It should also add any + Content-Transfer-Encoding or other headers to the message as + necessary. The default encoding is Base64. + + Any additional keyword arguments are passed to the base class + constructor, which turns them into parameters on the Content-Type + header. + """ + if _subtype is None: + _subtype = _what(_audiodata) + if _subtype is None: + raise TypeError('Could not find audio MIME subtype') + MIMENonMultipart.__init__(self, 'audio', _subtype, policy=policy, + **_params) + self.set_payload(_audiodata) + _encoder(self) + + +_rules = [] + + +# Originally from the sndhdr module. +# +# There are others in sndhdr that don't have MIME types. :( +# Additional ones to be added to sndhdr? midi, mp3, realaudio, wma?? +def _what(data): + # Try to identify a sound file type. + # + # sndhdr.what() had a pretty cruddy interface, unfortunately. This is why + # we re-do it here. It would be easier to reverse engineer the Unix 'file' + # command and use the standard 'magic' file, as shipped with a modern Unix. + for testfn in _rules: + if res := testfn(data): + return res + else: + return None + + +def rule(rulefunc): + _rules.append(rulefunc) + return rulefunc + + +@rule +def _aiff(h): + if not h.startswith(b'FORM'): + return None + if h[8:12] in {b'AIFC', b'AIFF'}: + return 'x-aiff' + else: + return None + + +@rule +def _au(h): + if h.startswith(b'.snd'): + return 'basic' + else: + return None + + +@rule +def _wav(h): + # 'RIFF' 'WAVE' 'fmt ' + if not h.startswith(b'RIFF') or h[8:12] != b'WAVE' or h[12:16] != b'fmt ': + return None + else: + return "x-wav" diff --git a/data/miniconda3/lib/python3.13/email/mime/base.py b/data/miniconda3/lib/python3.13/email/mime/base.py new file mode 100644 index 0000000000000000000000000000000000000000..f601f621cec3933d1668cbe22bb10b9c94daf55e --- /dev/null +++ b/data/miniconda3/lib/python3.13/email/mime/base.py @@ -0,0 +1,29 @@ +# Copyright (C) 2001-2006 Python Software Foundation +# Author: Barry Warsaw +# Contact: email-sig@python.org + +"""Base class for MIME specializations.""" + +__all__ = ['MIMEBase'] + +import email.policy + +from email import message + + +class MIMEBase(message.Message): + """Base class for MIME specializations.""" + + def __init__(self, _maintype, _subtype, *, policy=None, **_params): + """This constructor adds a Content-Type: and a MIME-Version: header. + + The Content-Type: header is taken from the _maintype and _subtype + arguments. Additional parameters for this header are taken from the + keyword arguments. + """ + if policy is None: + policy = email.policy.compat32 + message.Message.__init__(self, policy=policy) + ctype = '%s/%s' % (_maintype, _subtype) + self.add_header('Content-Type', ctype, **_params) + self['MIME-Version'] = '1.0' diff --git a/data/miniconda3/lib/python3.13/email/mime/image.py b/data/miniconda3/lib/python3.13/email/mime/image.py new file mode 100644 index 0000000000000000000000000000000000000000..4b7f2f9cbad425222a3f56f56511e9920149a2d6 --- /dev/null +++ b/data/miniconda3/lib/python3.13/email/mime/image.py @@ -0,0 +1,152 @@ +# Copyright (C) 2001-2006 Python Software Foundation +# Author: Barry Warsaw +# Contact: email-sig@python.org + +"""Class representing image/* type MIME documents.""" + +__all__ = ['MIMEImage'] + +from email import encoders +from email.mime.nonmultipart import MIMENonMultipart + + +class MIMEImage(MIMENonMultipart): + """Class for generating image/* type MIME documents.""" + + def __init__(self, _imagedata, _subtype=None, + _encoder=encoders.encode_base64, *, policy=None, **_params): + """Create an image/* type MIME document. + + _imagedata contains the bytes for the raw image data. If the data + type can be detected (jpeg, png, gif, tiff, rgb, pbm, pgm, ppm, + rast, xbm, bmp, webp, and exr attempted), then the subtype will be + automatically included in the Content-Type header. Otherwise, you can + specify the specific image subtype via the _subtype parameter. + + _encoder is a function which will perform the actual encoding for + transport of the image data. It takes one argument, which is this + Image instance. It should use get_payload() and set_payload() to + change the payload to the encoded form. It should also add any + Content-Transfer-Encoding or other headers to the message as + necessary. The default encoding is Base64. + + Any additional keyword arguments are passed to the base class + constructor, which turns them into parameters on the Content-Type + header. + """ + _subtype = _what(_imagedata) if _subtype is None else _subtype + if _subtype is None: + raise TypeError('Could not guess image MIME subtype') + MIMENonMultipart.__init__(self, 'image', _subtype, policy=policy, + **_params) + self.set_payload(_imagedata) + _encoder(self) + + +_rules = [] + + +# Originally from the imghdr module. +def _what(data): + for rule in _rules: + if res := rule(data): + return res + else: + return None + + +def rule(rulefunc): + _rules.append(rulefunc) + return rulefunc + + +@rule +def _jpeg(h): + """JPEG data with JFIF or Exif markers; and raw JPEG""" + if h[6:10] in (b'JFIF', b'Exif'): + return 'jpeg' + elif h[:4] == b'\xff\xd8\xff\xdb': + return 'jpeg' + + +@rule +def _png(h): + if h.startswith(b'\211PNG\r\n\032\n'): + return 'png' + + +@rule +def _gif(h): + """GIF ('87 and '89 variants)""" + if h[:6] in (b'GIF87a', b'GIF89a'): + return 'gif' + + +@rule +def _tiff(h): + """TIFF (can be in Motorola or Intel byte order)""" + if h[:2] in (b'MM', b'II'): + return 'tiff' + + +@rule +def _rgb(h): + """SGI image library""" + if h.startswith(b'\001\332'): + return 'rgb' + + +@rule +def _pbm(h): + """PBM (portable bitmap)""" + if len(h) >= 3 and \ + h[0] == ord(b'P') and h[1] in b'14' and h[2] in b' \t\n\r': + return 'pbm' + + +@rule +def _pgm(h): + """PGM (portable graymap)""" + if len(h) >= 3 and \ + h[0] == ord(b'P') and h[1] in b'25' and h[2] in b' \t\n\r': + return 'pgm' + + +@rule +def _ppm(h): + """PPM (portable pixmap)""" + if len(h) >= 3 and \ + h[0] == ord(b'P') and h[1] in b'36' and h[2] in b' \t\n\r': + return 'ppm' + + +@rule +def _rast(h): + """Sun raster file""" + if h.startswith(b'\x59\xA6\x6A\x95'): + return 'rast' + + +@rule +def _xbm(h): + """X bitmap (X10 or X11)""" + if h.startswith(b'#define '): + return 'xbm' + + +@rule +def _bmp(h): + if h.startswith(b'BM'): + return 'bmp' + + +@rule +def _webp(h): + if h.startswith(b'RIFF') and h[8:12] == b'WEBP': + return 'webp' + + +@rule +def _exr(h): + if h.startswith(b'\x76\x2f\x31\x01'): + return 'exr' diff --git a/data/miniconda3/lib/python3.13/email/mime/message.py b/data/miniconda3/lib/python3.13/email/mime/message.py new file mode 100644 index 0000000000000000000000000000000000000000..61836b5a7861fca712c57dc70d5b32e597dc16bf --- /dev/null +++ b/data/miniconda3/lib/python3.13/email/mime/message.py @@ -0,0 +1,33 @@ +# Copyright (C) 2001-2006 Python Software Foundation +# Author: Barry Warsaw +# Contact: email-sig@python.org + +"""Class representing message/* MIME documents.""" + +__all__ = ['MIMEMessage'] + +from email import message +from email.mime.nonmultipart import MIMENonMultipart + + +class MIMEMessage(MIMENonMultipart): + """Class representing message/* MIME documents.""" + + def __init__(self, _msg, _subtype='rfc822', *, policy=None): + """Create a message/* type MIME document. + + _msg is a message object and must be an instance of Message, or a + derived class of Message, otherwise a TypeError is raised. + + Optional _subtype defines the subtype of the contained message. The + default is "rfc822" (this is defined by the MIME standard, even though + the term "rfc822" is technically outdated by RFC 2822). + """ + MIMENonMultipart.__init__(self, 'message', _subtype, policy=policy) + if not isinstance(_msg, message.Message): + raise TypeError('Argument is not an instance of Message') + # It's convenient to use this base class method. We need to do it + # this way or we'll get an exception + message.Message.attach(self, _msg) + # And be sure our default type is set correctly + self.set_default_type('message/rfc822') diff --git a/data/miniconda3/lib/python3.13/email/mime/multipart.py b/data/miniconda3/lib/python3.13/email/mime/multipart.py new file mode 100644 index 0000000000000000000000000000000000000000..94d81c771a474eb27e4e5aa1575a0d198014d439 --- /dev/null +++ b/data/miniconda3/lib/python3.13/email/mime/multipart.py @@ -0,0 +1,47 @@ +# Copyright (C) 2002-2006 Python Software Foundation +# Author: Barry Warsaw +# Contact: email-sig@python.org + +"""Base class for MIME multipart/* type messages.""" + +__all__ = ['MIMEMultipart'] + +from email.mime.base import MIMEBase + + +class MIMEMultipart(MIMEBase): + """Base class for MIME multipart/* type messages.""" + + def __init__(self, _subtype='mixed', boundary=None, _subparts=None, + *, policy=None, + **_params): + """Creates a multipart/* type message. + + By default, creates a multipart/mixed message, with proper + Content-Type and MIME-Version headers. + + _subtype is the subtype of the multipart content type, defaulting to + `mixed'. + + boundary is the multipart boundary string. By default it is + calculated as needed. + + _subparts is a sequence of initial subparts for the payload. It + must be an iterable object, such as a list. You can always + attach new subparts to the message by using the attach() method. + + Additional parameters for the Content-Type header are taken from the + keyword arguments (or passed into the _params argument). + """ + MIMEBase.__init__(self, 'multipart', _subtype, policy=policy, **_params) + + # Initialise _payload to an empty list as the Message superclass's + # implementation of is_multipart assumes that _payload is a list for + # multipart messages. + self._payload = [] + + if _subparts: + for p in _subparts: + self.attach(p) + if boundary: + self.set_boundary(boundary) diff --git a/data/miniconda3/lib/python3.13/email/mime/nonmultipart.py b/data/miniconda3/lib/python3.13/email/mime/nonmultipart.py new file mode 100644 index 0000000000000000000000000000000000000000..a41386eb148c0c835b789526bb343b01efab4709 --- /dev/null +++ b/data/miniconda3/lib/python3.13/email/mime/nonmultipart.py @@ -0,0 +1,21 @@ +# Copyright (C) 2002-2006 Python Software Foundation +# Author: Barry Warsaw +# Contact: email-sig@python.org + +"""Base class for MIME type messages that are not multipart.""" + +__all__ = ['MIMENonMultipart'] + +from email import errors +from email.mime.base import MIMEBase + + +class MIMENonMultipart(MIMEBase): + """Base class for MIME non-multipart type messages.""" + + def attach(self, payload): + # The public API prohibits attaching multiple subparts to MIMEBase + # derived subtypes since none of them are, by definition, of content + # type multipart/* + raise errors.MultipartConversionError( + 'Cannot attach additional subparts to non-multipart/*') diff --git a/data/miniconda3/lib/python3.13/email/mime/text.py b/data/miniconda3/lib/python3.13/email/mime/text.py new file mode 100644 index 0000000000000000000000000000000000000000..7672b78913860091329fae6e786b83d0ed68b87d --- /dev/null +++ b/data/miniconda3/lib/python3.13/email/mime/text.py @@ -0,0 +1,40 @@ +# Copyright (C) 2001-2006 Python Software Foundation +# Author: Barry Warsaw +# Contact: email-sig@python.org + +"""Class representing text/* type MIME documents.""" + +__all__ = ['MIMEText'] + +from email.mime.nonmultipart import MIMENonMultipart + + +class MIMEText(MIMENonMultipart): + """Class for generating text/* type MIME documents.""" + + def __init__(self, _text, _subtype='plain', _charset=None, *, policy=None): + """Create a text/* type MIME document. + + _text is the string for this message object. + + _subtype is the MIME sub content type, defaulting to "plain". + + _charset is the character set parameter added to the Content-Type + header. This defaults to "us-ascii". Note that as a side-effect, the + Content-Transfer-Encoding header will also be set. + """ + + # If no _charset was specified, check to see if there are non-ascii + # characters present. If not, use 'us-ascii', otherwise use utf-8. + # XXX: This can be removed once #7304 is fixed. + if _charset is None: + try: + _text.encode('us-ascii') + _charset = 'us-ascii' + except UnicodeEncodeError: + _charset = 'utf-8' + + MIMENonMultipart.__init__(self, 'text', _subtype, policy=policy, + charset=str(_charset)) + + self.set_payload(_text, _charset) diff --git a/data/miniconda3/lib/python3.13/ensurepip/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/ensurepip/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f89595fb0d595b4f74d315e9d8fabe1fadbed5b Binary files /dev/null and b/data/miniconda3/lib/python3.13/ensurepip/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/ensurepip/__pycache__/__main__.cpython-313.pyc b/data/miniconda3/lib/python3.13/ensurepip/__pycache__/__main__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e5b038dd1c38255bebc27e895820a4b4f1820ad Binary files /dev/null and b/data/miniconda3/lib/python3.13/ensurepip/__pycache__/__main__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/ensurepip/__pycache__/_uninstall.cpython-313.pyc b/data/miniconda3/lib/python3.13/ensurepip/__pycache__/_uninstall.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c32055c0888b8a7c17e9b5408e57c8c617fc2d41 Binary files /dev/null and b/data/miniconda3/lib/python3.13/ensurepip/__pycache__/_uninstall.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/Icons/README.txt b/data/miniconda3/lib/python3.13/idlelib/Icons/README.txt new file mode 100644 index 0000000000000000000000000000000000000000..e245bc0b26e121eb19df5eb9f8464e12dcf6ebde --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/Icons/README.txt @@ -0,0 +1,51 @@ +IDLE-PYTHON LOGOS + +These are sent to tk on Windows, *NIX, and non-Aqua macOS +in pyshell following "# set application icon". + + +2006?: Andrew Clover made variously sized python icons for win23. +https://www.doxdesk.com/software/py/pyicons.html + +2006: 16, 32, and 48 bit .png versions were copied to CPython +as Python application icons, maybe in PC/icons/py.ico. +https://github.com/python/cpython/issues/43372 + +2014: They were copied (perhaps a bit revised) to idlelib/Icons. +https://github.com/python/cpython/issues/64605 +.gif versions were also added. + +2020: Add Clover's 256-bit image. +https://github.com/python/cpython/issues/82620 +Other fixups were done. + +The idle.ico file used for Windows was created with ImageMagick: + $ convert idle_16.png idle_32.png idle_48.png idle_256.png idle.ico +** This needs redoing whenever files are changed. +?? Do Start, Desktop, and Taskbar use idlelib/Icons files? + +Issue added Windows Store PC/icons/idlex44.png and .../idlex150.png. +https://github.com/python/cpython/pull/22817 +?? Should these be updated with major changes? + +2022: Optimize .png images in CPython repository with external program. +https://github.com/python/cpython/pull/21348 +idle.ico (and idlex##) were not updated. + +The idlexx.gif files are only needed for *nix running tcl/tk 8.5. +As of 2022, this was known true for 1 'major' Linux distribution. +(Same would be true for any non-Aqua macOS with 8.5, but now none?) +Can be deleted when we require 8.6 or it is known always used. + +Future: Derivatives of Python logo should be submitted for approval. +PSF Trademark Working Group / Committee psf-trademarks@python.org +https://www.python.org/community/logos/ # Original files +https://www.python.org/psf/trademarks-faq/ +https://www.python.org/psf/trademarks/ # Usage. + + +OTHER GIFS: These are used by browsers using idlelib.tree. +At least some will not be used when tree is replaced by ttk.Treeview. + + +Edited 2024 August 26 by TJR. diff --git a/data/miniconda3/lib/python3.13/idlelib/Icons/idle.ico b/data/miniconda3/lib/python3.13/idlelib/Icons/idle.ico new file mode 100644 index 0000000000000000000000000000000000000000..2aa9a8300d9e29670ecbe585f5ab21579dece9c2 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/Icons/idle.ico differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b97dde2b0929410f1065596d4fdeb513d7586ef8 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/__main__.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/__main__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4abd767b12dfa106257001d05a018bd5399b77dc Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/__main__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/autocomplete.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/autocomplete.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4ba916b2c9a2c8bef76fedbb1ecf10586a32c74 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/autocomplete.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/autocomplete_w.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/autocomplete_w.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e0cba0ee3c8caaa42775ed8edc11ed6c264277ff Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/autocomplete_w.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/autoexpand.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/autoexpand.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f2b1213a062bebdcc94847e287f1650fa9d916b7 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/autoexpand.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/browser.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/browser.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f9cd9f73db70925791da6cc6eaf32730d309992 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/browser.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/calltip.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/calltip.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..77fb893ca20982b56a444e135aea43e18f615f08 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/calltip.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/calltip_w.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/calltip_w.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b50832e9493b3d719d42ac194ac3d6e07f3729b6 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/calltip_w.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/codecontext.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/codecontext.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a454227be46838b5c0b68ad0ab1e19e19f6028f Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/codecontext.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/colorizer.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/colorizer.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..72dc2fb38119f87e641efbd27d14ba21b2e41c5c Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/colorizer.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/config.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/config.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fab6ec4fd03d5036b3b37d6e1e3102c9348fa7e1 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/config.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/config_key.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/config_key.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..140bdee3fbabd5036467ec1e76e0440743af6ebb Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/config_key.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/debugger.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/debugger.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..17701433913b67258b01761b371388396f4418ba Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/debugger.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/debugger_r.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/debugger_r.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b6c9425ad54de6fbb6131751265906e5e95da7e Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/debugger_r.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/debugobj.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/debugobj.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf1ece882303536b4b0341767f8d0c715f3b4ed3 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/debugobj.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/debugobj_r.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/debugobj_r.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d64c6fb32e68e31a17f0020e112b080e99d56d95 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/debugobj_r.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/delegator.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/delegator.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..987f95687cd6838c97dc9af068d7b3bbce0f87a9 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/delegator.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/dynoption.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/dynoption.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..14915d88774fd1d78e6400b87d351143d7680155 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/dynoption.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/editor.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/editor.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..369d76fb955f4956e382f8ea27c9b25f7eca9a67 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/editor.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/filelist.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/filelist.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1aacd07becffd5c55742759b49fa49d9dedd4abb Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/filelist.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/format.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/format.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8be2b1cfa66956e47ac574a063a2572d46697c4c Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/format.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/grep.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/grep.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de642ad1aa9d5e01446cdbaaf4bc40288e033669 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/grep.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/help.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/help.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec9d8e02eb5eff7eb5bff496a2e453ec0c666413 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/help.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/help_about.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/help_about.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8c3588c1f7f1ed0f7091e9bed8b93a858fa3e15 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/help_about.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/history.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/history.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f15ffd9b2ef046719f1d774a8cee58724545d3b Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/history.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/hyperparser.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/hyperparser.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a678e2ffd496a2393d854b1914092095ca88cab2 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/hyperparser.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/idle.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/idle.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..116e0b043efbffa92af0273d08aac0d5e4fc7716 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/idle.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/iomenu.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/iomenu.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..21eea86e5748dc282bbb36de441d470e35c47710 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/iomenu.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/macosx.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/macosx.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..89732f0ac8cb5bf1c6748ae7282f92bc4bc082cb Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/macosx.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/mainmenu.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/mainmenu.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..39b8127861ff93d50c97b5ea5f17782a8528630b Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/mainmenu.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/multicall.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/multicall.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22e9fe2fe9ae827f2c72463e5797a25a687aee40 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/multicall.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/outwin.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/outwin.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a23a8296e6c91cb62404e03235d59c2a01f66304 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/outwin.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/parenmatch.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/parenmatch.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..39d5d5bccdfe1bd6b51e7c4d37d2c48fcc3f8ddd Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/parenmatch.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/pathbrowser.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/pathbrowser.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d2cee12bfeb31df0b8d12ff90c93efa37a82c9e2 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/pathbrowser.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/percolator.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/percolator.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..19a5770d70942c7f53f1d65f9432890d85419482 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/percolator.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/pyparse.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/pyparse.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f39c08c78a741f73253fd1d50ab1a7bbd295f473 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/pyparse.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/pyshell.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/pyshell.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f9f207d060e110d40295d14c7eb1d10ce91ad29e Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/pyshell.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/query.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/query.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f92aed5ba1f9fe237d8ecf71b7a65aedf0d625cf Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/query.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/redirector.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/redirector.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c8e68331856c362831ded7471a25ede2887c52e4 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/redirector.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/replace.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/replace.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a7435d7f44084c78c1a4dda42556476d24d5151f Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/replace.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/rpc.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/rpc.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a9afb3510dc149ae99bdab88fef6116302b7fe5e Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/rpc.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/run.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/run.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc0ef55aa0b424ad7e3bd37f8dd5dc853fe6a618 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/run.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/runscript.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/runscript.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..53e744a88f96f5d974c9bc6038468005ec4c57c7 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/runscript.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/scrolledlist.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/scrolledlist.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d9a537d19dfbe215db9df8401820836195ec037 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/scrolledlist.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/search.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/search.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..93f84f52ef660c172341484033baaa4123dd6c68 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/search.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/searchbase.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/searchbase.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ceebdde04820b1b66bb357dae8c93beb0b110ba3 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/searchbase.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/searchengine.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/searchengine.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ec5890010a601614cd7f52a46a40b977f4d22b5 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/searchengine.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/sidebar.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/sidebar.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..deb98f6fa9c104b2bc113aa2dda13883001f3b53 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/sidebar.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/squeezer.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/squeezer.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e33be66c6015a576b02a453acb7c85ed5887cdfe Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/squeezer.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/stackviewer.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/stackviewer.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e043c62fad0a2b1f060a09a5ab3bc3a4116741fb Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/stackviewer.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/statusbar.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/statusbar.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2bf2abce63af2a40c64e92e02018e9e39e282ba9 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/statusbar.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/textview.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/textview.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2db4cd06fa63bfa83b610a8dcb8b582761c76fa4 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/textview.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/tooltip.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/tooltip.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e21ce0d7f8981a949be9d08af335e4799f85391 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/tooltip.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/tree.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/tree.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..374956e08fb39031cef05fb4891957b7ec0cc0fe Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/tree.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/undo.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/undo.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a9b78732ebcac80a88d6ea95266de7c27d009f46 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/undo.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/util.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/util.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f2f0b7d2cb2265fc205b4f6256d8550e5390a5fd Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/util.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/window.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/window.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6cbfc04f01e03f8a9e75f31385d5e9dbdba92d01 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/window.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/zoomheight.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/zoomheight.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..42a3ef5549178fd74fe2bac4014b39230496fb60 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/zoomheight.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/__pycache__/zzdummy.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/__pycache__/zzdummy.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..55c5aa41e7eeaaf030c4d550b1dcdf3aaabf8b88 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/__pycache__/zzdummy.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/README.txt b/data/miniconda3/lib/python3.13/idlelib/idle_test/README.txt new file mode 100644 index 0000000000000000000000000000000000000000..cacd06db873d039baa144a95fa45914565ca6197 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/README.txt @@ -0,0 +1,241 @@ +README FOR IDLE TESTS IN IDLELIB.IDLE_TEST + +0. Quick Start + +Automated unit tests were added in 3.3 for Python 3.x. +To run the tests from a command line: + +python -m test.test_idle + +Human-mediated tests were added later in 3.4. + +python -m idlelib.idle_test.htest + + +1. Test Files + +The idle directory, idlelib, has over 60 xyz.py files. The idle_test +subdirectory contains test_xyz.py for each implementation file xyz.py. +To add a test for abc.py, open idle_test/template.py and immediately +Save As test_abc.py. Insert 'abc' on the first line, and replace +'zzdummy' with 'abc. + +Remove the imports of requires and tkinter if not needed. Otherwise, +add to the tkinter imports as needed. + +Add a prefix to 'Test' for the initial test class. The template class +contains code needed or possibly needed for gui tests. See the next +section if doing gui tests. If not, and not needed for further classes, +this code can be removed. + +Add the following at the end of abc.py. If an htest was added first, +insert the import and main lines before the htest lines. + +if __name__ == "__main__": + from unittest import main + main('idlelib.idle_test.test_abc', verbosity=2, exit=False) + +The ', exit=False' is only needed if an htest follows. + + + +2. GUI Tests + +When run as part of the Python test suite, Idle GUI tests need to run +test.support.requires('gui'). A test is a GUI test if it creates a +tkinter.Tk root or master object either directly or indirectly by +instantiating a tkinter or idle class. GUI tests cannot run in test +processes that either have no graphical environment available or are not +allowed to use it. + +To guard a module consisting entirely of GUI tests, start with + +from test.support import requires +requires('gui') + +To guard a test class, put "requires('gui')" in its setUpClass function. +The template.py file does this. + +To avoid interfering with other GUI tests, all GUI objects must be +destroyed and deleted by the end of the test. The Tk root created in a +setUpX function should be destroyed in the corresponding tearDownX and +the module or class attribute deleted. Others widgets should descend +from the single root and the attributes deleted BEFORE root is +destroyed. See https://bugs.python.org/issue20567. + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = tk.Tk() + cls.text = tk.Text(root) + + @classmethod + def tearDownClass(cls): + del cls.text + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + +The update_idletasks call is sometimes needed to prevent the following +warning either when running a test alone or as part of the test suite +(#27196). It should not hurt if not needed. + + can't invoke "event" command: application has been destroyed + ... + "ttk::ThemeChanged" + +If a test creates instance 'e' of EditorWindow, call 'e._close()' before +or as the first part of teardown. The effect of omitting this depends +on the later shutdown. Then enable the after_cancel loop in the +template. This prevents messages like the following. + +bgerror failed to handle background error. + Original error: invalid command name "106096696timer_event" + Error in bgerror: can't invoke "tk" command: application has been destroyed + +Requires('gui') causes the test(s) it guards to be skipped if any of +these conditions are met: + + - The tests are being run by regrtest.py, and it was started without + enabling the "gui" resource with the "-u" command line option. + + - The tests are being run on Windows by a service that is not allowed + to interact with the graphical environment. + + - The tests are being run on Linux and X Windows is not available. + + - The tests are being run on Mac OSX in a process that cannot make a + window manager connection. + + - tkinter.Tk cannot be successfully instantiated for some reason. + + - test.support.use_resources has been set by something other than + regrtest.py and does not contain "gui". + +Tests of non-GUI operations should avoid creating tk widgets. Incidental +uses of tk variables and messageboxes can be replaced by the mock +classes in idle_test/mock_tk.py. The mock text handles some uses of the +tk Text widget. + + +3. Running Unit Tests + +Assume that xyz.py and test_xyz.py both end with a unittest.main() call. +Running either from an Idle editor runs all tests in the test_xyz file +with the version of Python running Idle. Test output appears in the +Shell window. The 'verbosity=2' option lists all test methods in the +file, which is appropriate when developing tests. The 'exit=False' +option is needed in xyx.py files when an htest follows. + +The following command lines also run all test methods, including +GUI tests, in test_xyz.py. (Both '-m idlelib' and '-m idlelib.idle' +start Idle and so cannot run tests.) + +python -m idlelib.xyz +python -m idlelib.idle_test.test_xyz + +The following runs all idle_test/test_*.py tests interactively. + +>>> import unittest +>>> unittest.main('idlelib.idle_test', verbosity=2) + +The following run all Idle tests at a command line. Option '-v' is the +same as 'verbosity=2'. + +python -m unittest -v idlelib.idle_test +python -m test -v -ugui test_idle +python -m test.test_idle + +IDLE tests are 'discovered' by idlelib.idle_test.__init__.load_tests +when this is imported into test.test_idle. Normally, neither file +should be changed when working on individual test modules. The third +command runs unittest indirectly through regrtest. The same happens when +the entire test suite is run with 'python -m test'. So that command must +work for buildbots to stay green. IDLE tests must not disturb the +environment in a way that makes other tests fail (GH-62281). + +To test subsets of modules, see idlelib.idle_test.__init__. This +can be used to find refleaks or possible sources of "Theme changed" +tcl messages (GH-71383). + +To run an individual Testcase or test method, extend the dotted name +given to unittest on the command line or use the test -m option. The +latter allows use of other regrtest options. When using the latter, +all components of the pattern must be present, but any can be replaced +by '*'. + +python -m unittest -v idlelib.idle_test.test_xyz.Test_case.test_meth +python -m test -m idlelib.idle_test.text_xyz.Test_case.test_meth test_idle + +The test suite can be run in an IDLE user process from Shell. +>>> import test.autotest # Issue 25588, 2017/10/13, 3.6.4, 3.7.0a2. +There are currently failures not usually present, and this does not +work when run from the editor. + + +4. Human-mediated Tests + +Human-mediated tests are widget tests that cannot be automated but need +human verification. They are contained in idlelib/idle_test/htest.py, +which has instructions. (Some modules need an auxiliary function, +identified with "# htest # on the header line.) The set is about +complete, though some tests need improvement. To run all htests, run the +htest file from an editor or from the command line with: + +python -m idlelib.idle_test.htest + + +5. Test Coverage + +Install the coverage package into your Python 3.6 site-packages +directory. (Its exact location depends on the OS). +> python3 -m pip install coverage +(On Windows, replace 'python3 with 'py -3.6' or perhaps just 'python'.) + +The problem with running coverage with repository python is that +coverage uses absolute imports for its submodules, hence it needs to be +in a directory in sys.path. One solution: copy the package to the +directory containing the cpython repository. Call it 'dev'. Then run +coverage either directly or from a script in that directory so that +'dev' is prepended to sys.path. + +Either edit or add dev/.coveragerc so it looks something like this. +--- +# .coveragerc sets coverage options. +[run] +branch = True + +[report] +# Regexes for lines to exclude from consideration +exclude_lines = + # Don't complain if non-runnable code isn't run: + if 0: + if __name__ == .__main__.: + + .*# htest # + if not _utest: + if _htest: +--- +The additions for IDLE are 'branch = True', to test coverage both ways, +and the last three exclude lines, to exclude things peculiar to IDLE +that are not executed during tests. + +A script like the following cover.bat (for Windows) is very handy. +--- +@echo off +rem Usage: cover filename [test_ suffix] # proper case required by coverage +rem filename without .py, 2nd parameter if test is not test_filename +setlocal +set py=f:\dev\3x\pcbuild\win32\python_d.exe +set src=idlelib.%1 +if "%2" EQU "" set tst=f:/dev/3x/Lib/idlelib/idle_test/test_%1.py +if "%2" NEQ "" set tst=f:/dev/ex/Lib/idlelib/idle_test/test_%2.py + +%py% -m coverage run --pylib --source=%src% %tst% +%py% -m coverage report --show-missing +%py% -m coverage html +start htmlcov\3x_Lib_idlelib_%1_py.html +rem Above opens new report; htmlcov\index.html displays report index +--- +The second parameter was added for tests of module x not named test_x. +(There were several before modules were renamed, now only one is left.) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__init__.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8eed2699c4121119eec4e38d7b19e6a360404f70 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/__init__.py @@ -0,0 +1,23 @@ +"""idlelib.idle_test implements test.test_idle, which tests the IDLE +application as part of the stdlib test suite. +Run IDLE tests alone with "python -m test.test_idle (-v)". + +This package and its contained modules are subject to change and +any direct use is at your own risk. +""" +from os.path import dirname + +# test_idle imports load_tests for test discovery (default all). +# To run subsets of idlelib module tests, insert '[]' after '_'. +# Example: insert '[ac]' for modules beginning with 'a' or 'c'. +# Additional .discover/.addTest pairs with separate inserts work. +# Example: pairs with 'c' and 'g' test c* files and grep. + +def load_tests(loader, standard_tests, pattern): + this_dir = dirname(__file__) + top_dir = dirname(dirname(this_dir)) + module_tests = loader.discover(start_dir=this_dir, + pattern='test_*.py', # Insert here. + top_level_dir=top_dir) + standard_tests.addTests(module_tests) + return standard_tests diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5069ad6b84939a7ff3b4862894ad3469132aeb11 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/htest.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/htest.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4c6bb282669892071c6b05284d549d7513026d1 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/htest.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/mock_idle.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/mock_idle.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d254df7399e41db1a62fe545e6f5cc7545977589 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/mock_idle.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/mock_tk.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/mock_tk.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..559ac89523d8450d1a8d54fe688d181c03bc5e76 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/mock_tk.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/template.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/template.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..305b4a60f603cd52b2111085aec5f7d0475dd755 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/template.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_autocomplete.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_autocomplete.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0bb7157c5970efa75f6355d57cb9b70965e589fe Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_autocomplete.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_autocomplete_w.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_autocomplete_w.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d80cd870beb17ad43c631732b57cac0397ac568 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_autocomplete_w.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_autoexpand.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_autoexpand.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..420e66c409273e635cf2eb5131a15164a68b9585 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_autoexpand.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_browser.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_browser.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f645de1c0d30662cf3b40cabf23b8c0fb56fa03 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_browser.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_calltip.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_calltip.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2266ee0a854cb14edc3d80589478c4873e18681e Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_calltip.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_calltip_w.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_calltip_w.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9f5a6872528627a804990e50fd8c131f2f3bbbac Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_calltip_w.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_codecontext.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_codecontext.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..897332a704585f29ec59511264ee7cf29a91b569 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_codecontext.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_colorizer.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_colorizer.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cc90df7a39b1d16c9d10c6185000a33a454eaec3 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_colorizer.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_config.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_config.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d66805d8c0979aaaffffa4cfc106efdffd5a8d7b Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_config.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_config_key.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_config_key.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0bf1b5c32876483ac1b5acfd7804c661cdc69257 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_config_key.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_configdialog.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_configdialog.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c3b05eba59fd891110eb1d6d7729ae0f896095c3 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_configdialog.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_debugger.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_debugger.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4577059f29f980006d605acdd4d6fe4c3632700b Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_debugger.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_debugger_r.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_debugger_r.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dcd7c434a56986bd30db6d22d68caa4ad80f9b93 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_debugger_r.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_debugobj.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_debugobj.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..06644b9458e6293ba25bebed8dede033b61a78e1 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_debugobj.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_debugobj_r.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_debugobj_r.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2bbb0dd5799f22c2c5b52b7363901d9a103ab357 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_debugobj_r.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_delegator.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_delegator.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..83b24ee64c0dce63666567f543aa7c4d6d966134 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_delegator.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_editmenu.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_editmenu.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0cbd664de474ec67c2e3261cd7743c3f508cc501 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_editmenu.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_editor.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_editor.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..879818425b130a26d66770c03c6628fc117fb36a Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_editor.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_filelist.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_filelist.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..74296d12c71bf05986a6e99847be6137d8ae302d Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_filelist.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_format.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_format.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4c169ac571236e410da90767e2c8a47e0e978b4e Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_format.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_grep.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_grep.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..374009121a8316967957273f9ba34a27d083f9cf Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_grep.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_help.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_help.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..11f984f85b06d2ae64262cbe2f8f4fd71ddc5606 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_help.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_help_about.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_help_about.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..80b486a04289ff0d0a76fc38902fa1db0b92d129 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_help_about.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_history.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_history.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8cfc3a2cee31a327a4314ed4d7bb6878898025ee Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_history.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_hyperparser.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_hyperparser.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f7f989a4556485ad13fa39a6855eef96ef1d630 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_hyperparser.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_iomenu.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_iomenu.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..05e77483b74c852f66401b91ccee9111a0dad747 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_iomenu.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_macosx.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_macosx.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9462458eb627b598cedf4df91ad82bc43afeea1e Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_macosx.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_mainmenu.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_mainmenu.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b2979bb302e26849831fc30130a47532ce415ba6 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_mainmenu.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_multicall.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_multicall.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f66bf3b8bbe5ee2d91269432d12c605b36d59264 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_multicall.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_outwin.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_outwin.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d9e7fdd8e0a371d8c6ee729d01fa77e29ba24ae Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_outwin.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_parenmatch.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_parenmatch.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5732fcbcefe94beb577973ad5602b1f8db25f972 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_parenmatch.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_pathbrowser.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_pathbrowser.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..40a4a100776c2b35a5f65ae7cae5f2985c071052 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_pathbrowser.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_percolator.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_percolator.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..050ca765b6d296fc65fa7e840074598b52b635d7 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_percolator.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_pyparse.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_pyparse.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..368e04227df5c5514c9c2ccea787c3c94cabb841 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_pyparse.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_pyshell.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_pyshell.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e59392d7c328fd8d6b41eb020d9c13e4a3a6ff4b Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_pyshell.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_query.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_query.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b6df392ce9ae41a3d5386ea1c072e9c8045b28c7 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_query.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_redirector.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_redirector.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..045fcfd71517ce16355e89e0142e328c088f894e Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_redirector.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_replace.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_replace.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1258bdecc7904d8b48b3ecd4c181198f941f2113 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_replace.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_rpc.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_rpc.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fcfb16ac34935e136366372d4324598fffe04db0 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_rpc.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_run.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_run.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad06225c71838cce94c04abc75f7bef105c56a06 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_run.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_runscript.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_runscript.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bd5b9f294900e57ea053af15a970ca0db9ff665a Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_runscript.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_scrolledlist.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_scrolledlist.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..13cf38976c8252ca0125d986dd36d566016443d6 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_scrolledlist.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_search.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_search.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a923789344eba6be983aa22520056c478cdac3e Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_search.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_searchbase.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_searchbase.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c3ba772a8e409ef6eef71f8aebb5b261daaced5 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_searchbase.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_searchengine.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_searchengine.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dc41ab75225658f0c94ecb8983dbafd46413443e Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_searchengine.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_sidebar.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_sidebar.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c8e128a655eff566150994fb57fb6de20043f1b7 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_sidebar.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_squeezer.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_squeezer.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fbda7ea3c2a6452a40d4874b73becb80e196b24c Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_squeezer.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_stackviewer.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_stackviewer.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a7904ef87f21af145c4c60c3ba960e56bda8d55 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_stackviewer.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_statusbar.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_statusbar.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4858002da90612709c55f8414b7432a4d091c972 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_statusbar.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_text.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_text.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..705f983f8ddeb0f6e43c137c98f201a991bb9748 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_text.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_textview.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_textview.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..02ae74679702d508c472fbd44eb234ba899af766 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_textview.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_tooltip.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_tooltip.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..23228343b7211885ac57852401d676f1d6665a4b Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_tooltip.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_tree.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_tree.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..03702942c59626c934d9331c637a5e97e3189bdd Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_tree.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_undo.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_undo.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2079794e231144346b5046bab9c9f922076b481c Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_undo.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_util.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_util.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e00fda7c204662a216767f485557f28b98b27d9 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_util.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_warning.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_warning.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2be5ded4595a9f75e9539b277526e6da3ee6e701 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_warning.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_window.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_window.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2220c990acaa9627d8df7edd84286832d1c401b3 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_window.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_zoomheight.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_zoomheight.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4702c107ea3b78cde101d7710dd26ef43365c20c Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_zoomheight.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_zzdummy.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_zzdummy.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f43a1ac5bbca1b2e0bdc87a7193d2909bb2e7915 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/test_zzdummy.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/tkinter_testing_utils.cpython-313.pyc b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/tkinter_testing_utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6daf1bff2c6ad1dca9e834014bee85a958553c05 Binary files /dev/null and b/data/miniconda3/lib/python3.13/idlelib/idle_test/__pycache__/tkinter_testing_utils.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/example_noext b/data/miniconda3/lib/python3.13/idlelib/idle_test/example_noext new file mode 100644 index 0000000000000000000000000000000000000000..7d2510e30bc0ae41fde1a2e2fa30cdbb55318893 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/example_noext @@ -0,0 +1,4 @@ +#!usr/bin/env python + +def example_function(some_argument): + pass diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/example_stub.pyi b/data/miniconda3/lib/python3.13/idlelib/idle_test/example_stub.pyi new file mode 100644 index 0000000000000000000000000000000000000000..abcdbc17529974ca9892cb0b70f30425160bb279 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/example_stub.pyi @@ -0,0 +1,4 @@ +# An example file to test recognition of a .pyi file as Python source code. + +class Example: + def method(self, argument1: str, argument2: list[int]) -> None: ... diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/htest.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/htest.py new file mode 100644 index 0000000000000000000000000000000000000000..b63ff9ec2877b96ef225d7f8a4073a19b294cd94 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/htest.py @@ -0,0 +1,442 @@ +"""Run human tests of Idle's window, dialog, and popup widgets. + +run(*tests) Create a master Tk() htest window. Within that, run each +callable in tests after finding the matching test spec in this file. If +tests is empty, run an htest for each spec dict in this file after +finding the matching callable in the module named in the spec. Close +the master window to end testing. + +In a tested module, let X be a global name bound to a callable (class or +function) whose .__name__ attribute is also X (the usual situation). The +first parameter of X must be 'parent' or 'master'. When called, the +first argument will be the root window. X must create a child +Toplevel(parent/master) (or subclass thereof). The Toplevel may be a +test widget or dialog, in which case the callable is the corresponding +class. Or the Toplevel may contain the widget to be tested or set up a +context in which a test widget is invoked. In this latter case, the +callable is a wrapper function that sets up the Toplevel and other +objects. Wrapper function names, such as _editor_window', should start +with '_' and be lowercase. + + +End the module with + +if __name__ == '__main__': + + from idlelib.idle_test.htest import run + run(callable) # There could be multiple comma-separated callables. + +To have wrapper functions ignored by coverage reports, tag the def +header like so: "def _wrapper(parent): # htest #". Use the same tag +for htest lines in widget code. Make sure that the 'if __name__' line +matches the above. Then have make sure that .coveragerc includes the +following: + +[report] +exclude_lines = + .*# htest # + if __name__ == .__main__.: + +(The "." instead of "'" is intentional and necessary.) + + +To run any X, this file must contain a matching instance of the +following template, with X.__name__ prepended to '_spec'. +When all tests are run, the prefix is use to get X. + +callable_spec = { + 'file': '', + 'kwds': {'title': ''}, + 'msg': "" + } + +file (no .py): run() imports file.py. +kwds: augmented with {'parent':root} and passed to X as **kwds. +title: an example kwd; some widgets need this, delete line if not. +msg: master window hints about testing the widget. + + +TODO test these modules and classes: + autocomplete_w.AutoCompleteWindow + debugger.Debugger + outwin.OutputWindow (indirectly being tested with grep test) + pyshell.PyShellEditorWindow +""" + +import idlelib.pyshell # Set Windows DPI awareness before Tk(). +from importlib import import_module +import textwrap +import tkinter as tk +from tkinter.ttk import Scrollbar +tk.NoDefaultRoot() + +AboutDialog_spec = { + 'file': 'help_about', + 'kwds': {'title': 'help_about test', + '_htest': True, + }, + 'msg': "Click on URL to open in default browser.\n" + "Verify x.y.z versions and test each button, including Close.\n " + } + +# TODO implement ^\; adding '' to function does not work. +_calltip_window_spec = { + 'file': 'calltip_w', + 'kwds': {}, + 'msg': "Typing '(' should display a calltip.\n" + "Typing ') should hide the calltip.\n" + "So should moving cursor out of argument area.\n" + "Force-open-calltip does not work here.\n" + } + +_color_delegator_spec = { + 'file': 'colorizer', + 'kwds': {}, + 'msg': "The text is sample Python code.\n" + "Ensure components like comments, keywords, builtins,\n" + "string, definitions, and break are correctly colored.\n" + "The default color scheme is in idlelib/config-highlight.def" + } + +ConfigDialog_spec = { + 'file': 'configdialog', + 'kwds': {'title': 'ConfigDialogTest', + '_htest': True,}, + 'msg': "IDLE preferences dialog.\n" + "In the 'Fonts/Tabs' tab, changing font face, should update the " + "font face of the text in the area below it.\nIn the " + "'Highlighting' tab, try different color schemes. Clicking " + "items in the sample program should update the choices above it." + "\nIn the 'Keys', 'General' and 'Extensions' tabs, test settings " + "of interest." + "\n[Ok] to close the dialog.[Apply] to apply the settings and " + "and [Cancel] to revert all changes.\nRe-run the test to ensure " + "changes made have persisted." + } + +CustomRun_spec = { + 'file': 'query', + 'kwds': {'title': 'Customize query.py Run', + '_htest': True}, + 'msg': "Enter with or [OK]. Print valid entry to Shell\n" + "Arguments are parsed into a list\n" + "Mode is currently restart True or False\n" + "Close dialog with valid entry, , [Cancel], [X]" + } + +_debug_object_browser_spec = { + 'file': 'debugobj', + 'kwds': {}, + 'msg': "Double click on items up to the lowest level.\n" + "Attributes of the objects and related information " + "will be displayed side-by-side at each level." + } + +# TODO Improve message +_dyn_option_menu_spec = { + 'file': 'dynoption', + 'kwds': {}, + 'msg': "Select one of the many options in the 'old option set'.\n" + "Click the button to change the option set.\n" + "Select one of the many options in the 'new option set'." + } + +# TODO edit wrapper +_editor_window_spec = { + 'file': 'editor', + 'kwds': {}, + 'msg': "Test editor functions of interest.\n" + "Best to close editor first." + } + +GetKeysWindow_spec = { + 'file': 'config_key', + 'kwds': {'title': 'Test keybindings', + 'action': 'find-again', + 'current_key_sequences': [['', '', '']], + '_htest': True, + }, + 'msg': "Test for different key modifier sequences.\n" + " is invalid.\n" + "No modifier key is invalid.\n" + "Shift key with [a-z],[0-9], function key, move key, tab, space " + "is invalid.\nNo validity checking if advanced key binding " + "entry is used." + } + +_grep_dialog_spec = { + 'file': 'grep', + 'kwds': {}, + 'msg': "Click the 'Show GrepDialog' button.\n" + "Test the various 'Find-in-files' functions.\n" + "The results should be displayed in a new '*Output*' window.\n" + "'Right-click'->'Go to file/line' in the search results\n " + "should open that file in a new EditorWindow." + } + +HelpSource_spec = { + 'file': 'query', + 'kwds': {'title': 'Help name and source', + 'menuitem': 'test', + 'filepath': __file__, + 'used_names': {'abc'}, + '_htest': True}, + 'msg': "Enter menu item name and help file path\n" + "'', > than 30 chars, and 'abc' are invalid menu item names.\n" + "'' and file does not exist are invalid path items.\n" + "Any url ('www...', 'http...') is accepted.\n" + "Test Browse with and without path, as cannot unittest.\n" + "[Ok] or prints valid entry to shell\n" + ", [Cancel], or [X] prints None to shell" + } + +_io_binding_spec = { + 'file': 'iomenu', + 'kwds': {}, + 'msg': "Test the following bindings.\n" + " to open file from dialog.\n" + "Edit the file.\n" + " to print the file.\n" + " to save the file.\n" + " to save-as another file.\n" + " to save-copy-as another file.\n" + "Check that changes were saved by opening the file elsewhere." + } + +_multi_call_spec = { + 'file': 'multicall', + 'kwds': {}, + 'msg': "The following should trigger a print to console or IDLE Shell.\n" + "Entering and leaving the text area, key entry, ,\n" + ", , , \n" + ", and focusing elsewhere." + } + +_module_browser_spec = { + 'file': 'browser', + 'kwds': {}, + 'msg': textwrap.dedent(""" + "Inspect names of module, class(with superclass if applicable), + "methods and functions. Toggle nested items. Double clicking + "on items prints a traceback for an exception that is ignored.""") + } + +_multistatus_bar_spec = { + 'file': 'statusbar', + 'kwds': {}, + 'msg': "Ensure presence of multi-status bar below text area.\n" + "Click 'Update Status' to change the status text" + } + +PathBrowser_spec = { + 'file': 'pathbrowser', + 'kwds': {'_htest': True}, + 'msg': "Test for correct display of all paths in sys.path.\n" + "Toggle nested items out to the lowest level.\n" + "Double clicking on an item prints a traceback\n" + "for an exception that is ignored." + } + +_percolator_spec = { + 'file': 'percolator', + 'kwds': {}, + 'msg': "There are two tracers which can be toggled using a checkbox.\n" + "Toggling a tracer 'on' by checking it should print tracer " + "output to the console or to the IDLE shell.\n" + "If both the tracers are 'on', the output from the tracer which " + "was switched 'on' later, should be printed first\n" + "Test for actions like text entry, and removal." + } + +Query_spec = { + 'file': 'query', + 'kwds': {'title': 'Query', + 'message': 'Enter something', + 'text0': 'Go', + '_htest': True}, + 'msg': "Enter with or [Ok]. Print valid entry to Shell\n" + "Blank line, after stripping, is ignored\n" + "Close dialog with valid entry, , [Cancel], [X]" + } + + +_replace_dialog_spec = { + 'file': 'replace', + 'kwds': {}, + 'msg': "Click the 'Replace' button.\n" + "Test various replace options in the 'Replace dialog'.\n" + "Click [Close] or [X] to close the 'Replace Dialog'." + } + +_scrolled_list_spec = { + 'file': 'scrolledlist', + 'kwds': {}, + 'msg': "You should see a scrollable list of items\n" + "Selecting (clicking) or double clicking an item " + "prints the name to the console or Idle shell.\n" + "Right clicking an item will display a popup." + } + +_search_dialog_spec = { + 'file': 'search', + 'kwds': {}, + 'msg': "Click the 'Search' button.\n" + "Test various search options in the 'Search dialog'.\n" + "Click [Close] or [X] to close the 'Search Dialog'." + } + +_searchbase_spec = { + 'file': 'searchbase', + 'kwds': {}, + 'msg': "Check the appearance of the base search dialog\n" + "Its only action is to close." + } + +show_idlehelp_spec = { + 'file': 'help', + 'kwds': {}, + 'msg': "If the help text displays, this works.\n" + "Text is selectable. Window is scrollable." + } + +_sidebar_number_scrolling_spec = { + 'file': 'sidebar', + 'kwds': {}, + 'msg': textwrap.dedent("""\ + 1. Click on the line numbers and drag down below the edge of the + window, moving the mouse a bit and then leaving it there for a + while. The text and line numbers should gradually scroll down, + with the selection updated continuously. + + 2. With the lines still selected, click on a line number above + or below the selected lines. Only the line whose number was + clicked should be selected. + + 3. Repeat step #1, dragging to above the window. The text and + line numbers should gradually scroll up, with the selection + updated continuously. + + 4. Repeat step #2, clicking a line number below the selection."""), + } + +_stackbrowser_spec = { + 'file': 'stackviewer', + 'kwds': {}, + 'msg': "A stacktrace for a NameError exception.\n" + "Should have NameError and 1 traceback line." + } + +_tooltip_spec = { + 'file': 'tooltip', + 'kwds': {}, + 'msg': "Place mouse cursor over both the buttons\n" + "A tooltip should appear with some text." + } + +_tree_widget_spec = { + 'file': 'tree', + 'kwds': {}, + 'msg': "The canvas is scrollable.\n" + "Click on folders up to the lowest level." + } + +_undo_delegator_spec = { + 'file': 'undo', + 'kwds': {}, + 'msg': "Click [Undo] to undo any action.\n" + "Click [Redo] to redo any action.\n" + "Click [Dump] to dump the current state " + "by printing to the console or the IDLE shell.\n" + } + +ViewWindow_spec = { + 'file': 'textview', + 'kwds': {'title': 'Test textview', + 'contents': 'The quick brown fox jumps over the lazy dog.\n'*35, + '_htest': True}, + 'msg': "Test for read-only property of text.\n" + "Select text, scroll window, close" + } + +_widget_redirector_spec = { + 'file': 'redirector', + 'kwds': {}, + 'msg': "Every text insert should be printed to the console " + "or the IDLE shell." + } + +def run(*tests): + "Run callables in tests." + root = tk.Tk() + root.title('IDLE htest') + root.resizable(0, 0) + + # A scrollable Label-like constant width text widget. + frameLabel = tk.Frame(root, padx=10) + frameLabel.pack() + text = tk.Text(frameLabel, wrap='word') + text.configure(bg=root.cget('bg'), relief='flat', height=4, width=70) + scrollbar = Scrollbar(frameLabel, command=text.yview) + text.config(yscrollcommand=scrollbar.set) + scrollbar.pack(side='right', fill='y', expand=False) + text.pack(side='left', fill='both', expand=True) + + test_list = [] # Make list of (spec, callable) tuples. + if tests: + for test in tests: + test_spec = globals()[test.__name__ + '_spec'] + test_spec['name'] = test.__name__ + test_list.append((test_spec, test)) + else: + for key, dic in globals().items(): + if key.endswith('_spec'): + test_name = key[:-5] + test_spec = dic + test_spec['name'] = test_name + mod = import_module('idlelib.' + test_spec['file']) + test = getattr(mod, test_name) + test_list.append((test_spec, test)) + test_list.reverse() # So can pop in proper order in next_test. + + test_name = tk.StringVar(root) + callable_object = None + test_kwds = None + + def next_test(): + nonlocal test_name, callable_object, test_kwds + if len(test_list) == 1: + next_button.pack_forget() + test_spec, callable_object = test_list.pop() + test_kwds = test_spec['kwds'] + test_name.set('Test ' + test_spec['name']) + + text['state'] = 'normal' # Enable text replacement. + text.delete('1.0', 'end') + text.insert("1.0", test_spec['msg']) + text['state'] = 'disabled' # Restore read-only property. + + def run_test(_=None): + widget = callable_object(root, **test_kwds) + try: + print(widget.result) # Only true for query classes(?). + except AttributeError: + pass + + def close(_=None): + root.destroy() + + button = tk.Button(root, textvariable=test_name, + default='active', command=run_test) + next_button = tk.Button(root, text="Next", command=next_test) + button.pack() + next_button.pack() + next_button.focus_set() + root.bind('', run_test) + root.bind('', close) + + next_test() + root.mainloop() + + +if __name__ == '__main__': + run() diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/mock_idle.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/mock_idle.py new file mode 100644 index 0000000000000000000000000000000000000000..71fa480ce4d05c1d4bcb32fb1cf2d10f8695a2e5 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/mock_idle.py @@ -0,0 +1,61 @@ +'''Mock classes that imitate idlelib modules or classes. + +Attributes and methods will be added as needed for tests. +''' + +from idlelib.idle_test.mock_tk import Text + +class Func: + '''Record call, capture args, return/raise result set by test. + + When mock function is called, set or use attributes: + self.called - increment call number even if no args, kwds passed. + self.args - capture positional arguments. + self.kwds - capture keyword arguments. + self.result - return or raise value set in __init__. + self.return_self - return self instead, to mock query class return. + + Most common use will probably be to mock instance methods. + Given class instance, can set and delete as instance attribute. + Mock_tk.Var and Mbox_func are special variants of this. + ''' + def __init__(self, result=None, return_self=False): + self.called = 0 + self.result = result + self.return_self = return_self + self.args = None + self.kwds = None + def __call__(self, *args, **kwds): + self.called += 1 + self.args = args + self.kwds = kwds + if isinstance(self.result, BaseException): + raise self.result + elif self.return_self: + return self + else: + return self.result + + +class Editor: + '''Minimally imitate editor.EditorWindow class. + ''' + def __init__(self, flist=None, filename=None, key=None, root=None, + text=None): # Allow real Text with mock Editor. + self.text = text or Text() + self.undo = UndoDelegator() + + def get_selection_indices(self): + first = self.text.index('1.0') + last = self.text.index('end') + return first, last + + +class UndoDelegator: + '''Minimally imitate undo.UndoDelegator class. + ''' + # A real undo block is only needed for user interaction. + def undo_block_start(*args): + pass + def undo_block_stop(*args): + pass diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/mock_tk.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/mock_tk.py new file mode 100644 index 0000000000000000000000000000000000000000..8304734b847a835e5ad17227a66a0ff3b21eeaf7 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/mock_tk.py @@ -0,0 +1,307 @@ +"""Classes that replace tkinter gui objects used by an object being tested. + +A gui object is anything with a master or parent parameter, which is +typically required in spite of what the doc strings say. +""" +import re +from _tkinter import TclError + + +class Event: + '''Minimal mock with attributes for testing event handlers. + + This is not a gui object, but is used as an argument for callbacks + that access attributes of the event passed. If a callback ignores + the event, other than the fact that is happened, pass 'event'. + + Keyboard, mouse, window, and other sources generate Event instances. + Event instances have the following attributes: serial (number of + event), time (of event), type (of event as number), widget (in which + event occurred), and x,y (position of mouse). There are other + attributes for specific events, such as keycode for key events. + tkinter.Event.__doc__ has more but is still not complete. + ''' + def __init__(self, **kwds): + "Create event with attributes needed for test" + self.__dict__.update(kwds) + + +class Var: + "Use for String/Int/BooleanVar: incomplete" + def __init__(self, master=None, value=None, name=None): + self.master = master + self.value = value + self.name = name + def set(self, value): + self.value = value + def get(self): + return self.value + + +class Mbox_func: + """Generic mock for messagebox functions, which all have the same signature. + + Instead of displaying a message box, the mock's call method saves the + arguments as instance attributes, which test functions can then examine. + The test can set the result returned to ask function + """ + def __init__(self, result=None): + self.result = result # Return None for all show funcs + def __call__(self, title, message, *args, **kwds): + # Save all args for possible examination by tester + self.title = title + self.message = message + self.args = args + self.kwds = kwds + return self.result # Set by tester for ask functions + + +class Mbox: + """Mock for tkinter.messagebox with an Mbox_func for each function. + + Example usage in test_module.py for testing functions in module.py: + --- +from idlelib.idle_test.mock_tk import Mbox +import module + +orig_mbox = module.messagebox +showerror = Mbox.showerror # example, for attribute access in test methods + +class Test(unittest.TestCase): + + @classmethod + def setUpClass(cls): + module.messagebox = Mbox + + @classmethod + def tearDownClass(cls): + module.messagebox = orig_mbox + --- + For 'ask' functions, set func.result return value before calling the method + that uses the message function. When messagebox functions are the + only GUI calls in a method, this replacement makes the method GUI-free, + """ + askokcancel = Mbox_func() # True or False + askquestion = Mbox_func() # 'yes' or 'no' + askretrycancel = Mbox_func() # True or False + askyesno = Mbox_func() # True or False + askyesnocancel = Mbox_func() # True, False, or None + showerror = Mbox_func() # None + showinfo = Mbox_func() # None + showwarning = Mbox_func() # None + + +class Text: + """A semi-functional non-gui replacement for tkinter.Text text editors. + + The mock's data model is that a text is a list of \n-terminated lines. + The mock adds an empty string at the beginning of the list so that the + index of actual lines start at 1, as with Tk. The methods never see this. + Tk initializes files with a terminal \n that cannot be deleted. It is + invisible in the sense that one cannot move the cursor beyond it. + + This class is only tested (and valid) with strings of ascii chars. + For testing, we are not concerned with Tk Text's treatment of, + for instance, 0-width characters or character + accent. + """ + def __init__(self, master=None, cnf={}, **kw): + '''Initialize mock, non-gui, text-only Text widget. + + At present, all args are ignored. Almost all affect visual behavior. + There are just a few Text-only options that affect text behavior. + ''' + self.data = ['', '\n'] + + def index(self, index): + "Return string version of index decoded according to current text." + return "%s.%s" % self._decode(index, endflag=1) + + def _decode(self, index, endflag=0): + """Return a (line, char) tuple of int indexes into self.data. + + This implements .index without converting the result back to a string. + The result is constrained by the number of lines and linelengths of + self.data. For many indexes, the result is initially (1, 0). + + The input index may have any of several possible forms: + * line.char float: converted to 'line.char' string; + * 'line.char' string, where line and char are decimal integers; + * 'line.char lineend', where lineend='lineend' (and char is ignored); + * 'line.end', where end='end' (same as above); + * 'insert', the positions before terminal \n; + * 'end', whose meaning depends on the endflag passed to ._endex. + * 'sel.first' or 'sel.last', where sel is a tag -- not implemented. + """ + if isinstance(index, (float, bytes)): + index = str(index) + try: + index=index.lower() + except AttributeError: + raise TclError('bad text index "%s"' % index) from None + + lastline = len(self.data) - 1 # same as number of text lines + if index == 'insert': + return lastline, len(self.data[lastline]) - 1 + elif index == 'end': + return self._endex(endflag) + + line, char = index.split('.') + line = int(line) + + # Out of bounds line becomes first or last ('end') index + if line < 1: + return 1, 0 + elif line > lastline: + return self._endex(endflag) + + linelength = len(self.data[line]) -1 # position before/at \n + if char.endswith(' lineend') or char == 'end': + return line, linelength + # Tk requires that ignored chars before ' lineend' be valid int + if m := re.fullmatch(r'end-(\d*)c', char, re.A): # Used by hyperparser. + return line, linelength - int(m.group(1)) + + # Out of bounds char becomes first or last index of line + char = int(char) + if char < 0: + char = 0 + elif char > linelength: + char = linelength + return line, char + + def _endex(self, endflag): + '''Return position for 'end' or line overflow corresponding to endflag. + + -1: position before terminal \n; for .insert(), .delete + 0: position after terminal \n; for .get, .delete index 1 + 1: same viewed as beginning of non-existent next line (for .index) + ''' + n = len(self.data) + if endflag == 1: + return n, 0 + else: + n -= 1 + return n, len(self.data[n]) + endflag + + def insert(self, index, chars): + "Insert chars before the character at index." + + if not chars: # ''.splitlines() is [], not [''] + return + chars = chars.splitlines(True) + if chars[-1][-1] == '\n': + chars.append('') + line, char = self._decode(index, -1) + before = self.data[line][:char] + after = self.data[line][char:] + self.data[line] = before + chars[0] + self.data[line+1:line+1] = chars[1:] + self.data[line+len(chars)-1] += after + + def get(self, index1, index2=None): + "Return slice from index1 to index2 (default is 'index1+1')." + + startline, startchar = self._decode(index1) + if index2 is None: + endline, endchar = startline, startchar+1 + else: + endline, endchar = self._decode(index2) + + if startline == endline: + return self.data[startline][startchar:endchar] + else: + lines = [self.data[startline][startchar:]] + for i in range(startline+1, endline): + lines.append(self.data[i]) + lines.append(self.data[endline][:endchar]) + return ''.join(lines) + + def delete(self, index1, index2=None): + '''Delete slice from index1 to index2 (default is 'index1+1'). + + Adjust default index2 ('index+1) for line ends. + Do not delete the terminal \n at the very end of self.data ([-1][-1]). + ''' + startline, startchar = self._decode(index1, -1) + if index2 is None: + if startchar < len(self.data[startline])-1: + # not deleting \n + endline, endchar = startline, startchar+1 + elif startline < len(self.data) - 1: + # deleting non-terminal \n, convert 'index1+1 to start of next line + endline, endchar = startline+1, 0 + else: + # do not delete terminal \n if index1 == 'insert' + return + else: + endline, endchar = self._decode(index2, -1) + # restricting end position to insert position excludes terminal \n + + if startline == endline and startchar < endchar: + self.data[startline] = self.data[startline][:startchar] + \ + self.data[startline][endchar:] + elif startline < endline: + self.data[startline] = self.data[startline][:startchar] + \ + self.data[endline][endchar:] + startline += 1 + for i in range(startline, endline+1): + del self.data[startline] + + def compare(self, index1, op, index2): + line1, char1 = self._decode(index1) + line2, char2 = self._decode(index2) + if op == '<': + return line1 < line2 or line1 == line2 and char1 < char2 + elif op == '<=': + return line1 < line2 or line1 == line2 and char1 <= char2 + elif op == '>': + return line1 > line2 or line1 == line2 and char1 > char2 + elif op == '>=': + return line1 > line2 or line1 == line2 and char1 >= char2 + elif op == '==': + return line1 == line2 and char1 == char2 + elif op == '!=': + return line1 != line2 or char1 != char2 + else: + raise TclError('''bad comparison operator "%s": ''' + '''must be <, <=, ==, >=, >, or !=''' % op) + + # The following Text methods normally do something and return None. + # Whether doing nothing is sufficient for a test will depend on the test. + + def mark_set(self, name, index): + "Set mark *name* before the character at index." + pass + + def mark_unset(self, *markNames): + "Delete all marks in markNames." + + def tag_remove(self, tagName, index1, index2=None): + "Remove tag tagName from all characters between index1 and index2." + pass + + # The following Text methods affect the graphics screen and return None. + # Doing nothing should always be sufficient for tests. + + def scan_dragto(self, x, y): + "Adjust the view of the text according to scan_mark" + + def scan_mark(self, x, y): + "Remember the current X, Y coordinates." + + def see(self, index): + "Scroll screen to make the character at INDEX is visible." + pass + + # The following is a Misc method inherited by Text. + # It should properly go in a Misc mock, but is included here for now. + + def bind(sequence=None, func=None, add=None): + "Bind to this widget at event sequence a call to function func." + pass + + +class Entry: + "Mock for tkinter.Entry." + def focus_set(self): + pass diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/template.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/template.py new file mode 100644 index 0000000000000000000000000000000000000000..725a55b9c47230c32c63b3e6cd036f0319173046 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/template.py @@ -0,0 +1,30 @@ +"Test , coverage %." + +from idlelib import zzdummy +import unittest +from test.support import requires +from tkinter import Tk + + +class Test(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + + @classmethod + def tearDownClass(cls): + cls.root.update_idletasks() +## for id in cls.root.tk.call('after', 'info'): +## cls.root.after_cancel(id) # Need for EditorWindow. + cls.root.destroy() + del cls.root + + def test_init(self): + self.assertTrue(True) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_autocomplete.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_autocomplete.py new file mode 100644 index 0000000000000000000000000000000000000000..a811363c18d04e5770ec7071e08f0273dd04f0bf --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_autocomplete.py @@ -0,0 +1,305 @@ +"Test autocomplete, coverage 93%." + +import unittest +from unittest.mock import Mock, patch +from test.support import requires +from tkinter import Tk, Text +import os +import __main__ + +import idlelib.autocomplete as ac +import idlelib.autocomplete_w as acw +from idlelib.idle_test.mock_idle import Func +from idlelib.idle_test.mock_tk import Event + + +class DummyEditwin: + def __init__(self, root, text): + self.root = root + self.text = text + self.indentwidth = 8 + self.tabwidth = 8 + self.prompt_last_line = '>>>' # Currently not used by autocomplete. + + +class AutoCompleteTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.text = Text(cls.root) + cls.editor = DummyEditwin(cls.root, cls.text) + + @classmethod + def tearDownClass(cls): + del cls.editor, cls.text + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def setUp(self): + self.text.delete('1.0', 'end') + self.autocomplete = ac.AutoComplete(self.editor) + + def test_init(self): + self.assertEqual(self.autocomplete.editwin, self.editor) + self.assertEqual(self.autocomplete.text, self.text) + + def test_make_autocomplete_window(self): + testwin = self.autocomplete._make_autocomplete_window() + self.assertIsInstance(testwin, acw.AutoCompleteWindow) + + def test_remove_autocomplete_window(self): + acp = self.autocomplete + acp.autocompletewindow = m = Mock() + acp._remove_autocomplete_window() + m.hide_window.assert_called_once() + self.assertIsNone(acp.autocompletewindow) + + def test_force_open_completions_event(self): + # Call _open_completions and break. + acp = self.autocomplete + open_c = Func() + acp.open_completions = open_c + self.assertEqual(acp.force_open_completions_event('event'), 'break') + self.assertEqual(open_c.args[0], ac.FORCE) + + def test_autocomplete_event(self): + Equal = self.assertEqual + acp = self.autocomplete + + # Result of autocomplete event: If modified tab, None. + ev = Event(mc_state=True) + self.assertIsNone(acp.autocomplete_event(ev)) + del ev.mc_state + + # If tab after whitespace, None. + self.text.insert('1.0', ' """Docstring.\n ') + self.assertIsNone(acp.autocomplete_event(ev)) + self.text.delete('1.0', 'end') + + # If active autocomplete window, complete() and 'break'. + self.text.insert('1.0', 're.') + acp.autocompletewindow = mock = Mock() + mock.is_active = Mock(return_value=True) + Equal(acp.autocomplete_event(ev), 'break') + mock.complete.assert_called_once() + acp.autocompletewindow = None + + # If no active autocomplete window, open_completions(), None/break. + open_c = Func(result=False) + acp.open_completions = open_c + Equal(acp.autocomplete_event(ev), None) + Equal(open_c.args[0], ac.TAB) + open_c.result = True + Equal(acp.autocomplete_event(ev), 'break') + Equal(open_c.args[0], ac.TAB) + + def test_try_open_completions_event(self): + Equal = self.assertEqual + text = self.text + acp = self.autocomplete + trycompletions = acp.try_open_completions_event + after = Func(result='after1') + acp.text.after = after + + # If no text or trigger, after not called. + trycompletions() + Equal(after.called, 0) + text.insert('1.0', 're') + trycompletions() + Equal(after.called, 0) + + # Attribute needed, no existing callback. + text.insert('insert', ' re.') + acp._delayed_completion_id = None + trycompletions() + Equal(acp._delayed_completion_index, text.index('insert')) + Equal(after.args, + (acp.popupwait, acp._delayed_open_completions, ac.TRY_A)) + cb1 = acp._delayed_completion_id + Equal(cb1, 'after1') + + # File needed, existing callback cancelled. + text.insert('insert', ' "./Lib/') + after.result = 'after2' + cancel = Func() + acp.text.after_cancel = cancel + trycompletions() + Equal(acp._delayed_completion_index, text.index('insert')) + Equal(cancel.args, (cb1,)) + Equal(after.args, + (acp.popupwait, acp._delayed_open_completions, ac.TRY_F)) + Equal(acp._delayed_completion_id, 'after2') + + def test_delayed_open_completions(self): + Equal = self.assertEqual + acp = self.autocomplete + open_c = Func() + acp.open_completions = open_c + self.text.insert('1.0', '"dict.') + + # Set autocomplete._delayed_completion_id to None. + # Text index changed, don't call open_completions. + acp._delayed_completion_id = 'after' + acp._delayed_completion_index = self.text.index('insert+1c') + acp._delayed_open_completions('dummy') + self.assertIsNone(acp._delayed_completion_id) + Equal(open_c.called, 0) + + # Text index unchanged, call open_completions. + acp._delayed_completion_index = self.text.index('insert') + acp._delayed_open_completions((1, 2, 3, ac.FILES)) + self.assertEqual(open_c.args[0], (1, 2, 3, ac.FILES)) + + def test_oc_cancel_comment(self): + none = self.assertIsNone + acp = self.autocomplete + + # Comment is in neither code or string. + acp._delayed_completion_id = 'after' + after = Func(result='after') + acp.text.after_cancel = after + self.text.insert(1.0, '# comment') + none(acp.open_completions(ac.TAB)) # From 'else' after 'elif'. + none(acp._delayed_completion_id) + + def test_oc_no_list(self): + acp = self.autocomplete + fetch = Func(result=([],[])) + acp.fetch_completions = fetch + self.text.insert('1.0', 'object') + self.assertIsNone(acp.open_completions(ac.TAB)) + self.text.insert('insert', '.') + self.assertIsNone(acp.open_completions(ac.TAB)) + self.assertEqual(fetch.called, 2) + + + def test_open_completions_none(self): + # Test other two None returns. + none = self.assertIsNone + acp = self.autocomplete + + # No object for attributes or need call not allowed. + self.text.insert(1.0, '.') + none(acp.open_completions(ac.TAB)) + self.text.insert('insert', ' int().') + none(acp.open_completions(ac.TAB)) + + # Blank or quote trigger 'if complete ...'. + self.text.delete(1.0, 'end') + self.assertFalse(acp.open_completions(ac.TAB)) + self.text.insert('1.0', '"') + self.assertFalse(acp.open_completions(ac.TAB)) + self.text.delete('1.0', 'end') + + class dummy_acw: + __init__ = Func() + show_window = Func(result=False) + hide_window = Func() + + def test_open_completions(self): + # Test completions of files and attributes. + acp = self.autocomplete + fetch = Func(result=(['tem'],['tem', '_tem'])) + acp.fetch_completions = fetch + def make_acw(): return self.dummy_acw() + acp._make_autocomplete_window = make_acw + + self.text.insert('1.0', 'int.') + acp.open_completions(ac.TAB) + self.assertIsInstance(acp.autocompletewindow, self.dummy_acw) + self.text.delete('1.0', 'end') + + # Test files. + self.text.insert('1.0', '"t') + self.assertTrue(acp.open_completions(ac.TAB)) + self.text.delete('1.0', 'end') + + def test_completion_kwds(self): + self.assertIn('and', ac.completion_kwds) + self.assertIn('case', ac.completion_kwds) + self.assertNotIn('None', ac.completion_kwds) + + def test_fetch_completions(self): + # Test that fetch_completions returns 2 lists: + # For attribute completion, a large list containing all variables, and + # a small list containing non-private variables. + # For file completion, a large list containing all files in the path, + # and a small list containing files that do not start with '.'. + acp = self.autocomplete + small, large = acp.fetch_completions( + '', ac.ATTRS) + if hasattr(__main__, '__file__') and __main__.__file__ != ac.__file__: + self.assertNotIn('AutoComplete', small) # See issue 36405. + + # Test attributes + s, b = acp.fetch_completions('', ac.ATTRS) + self.assertLess(len(small), len(large)) + self.assertTrue(all(filter(lambda x: x.startswith('_'), s))) + self.assertTrue(any(filter(lambda x: x.startswith('_'), b))) + + # Test smalll should respect to __all__. + with patch.dict('__main__.__dict__', {'__all__': ['a', 'b']}): + s, b = acp.fetch_completions('', ac.ATTRS) + self.assertEqual(s, ['a', 'b']) + self.assertIn('__name__', b) # From __main__.__dict__. + self.assertIn('sum', b) # From __main__.__builtins__.__dict__. + self.assertIn('nonlocal', b) # From keyword.kwlist. + pos = b.index('False') # Test False not included twice. + self.assertNotEqual(b[pos+1], 'False') + + # Test attributes with name entity. + mock = Mock() + mock._private = Mock() + with patch.dict('__main__.__dict__', {'foo': mock}): + s, b = acp.fetch_completions('foo', ac.ATTRS) + self.assertNotIn('_private', s) + self.assertIn('_private', b) + self.assertEqual(s, [i for i in sorted(dir(mock)) if i[:1] != '_']) + self.assertEqual(b, sorted(dir(mock))) + + # Test files + def _listdir(path): + # This will be patch and used in fetch_completions. + if path == '.': + return ['foo', 'bar', '.hidden'] + return ['monty', 'python', '.hidden'] + + with patch.object(os, 'listdir', _listdir): + s, b = acp.fetch_completions('', ac.FILES) + self.assertEqual(s, ['bar', 'foo']) + self.assertEqual(b, ['.hidden', 'bar', 'foo']) + + s, b = acp.fetch_completions('~', ac.FILES) + self.assertEqual(s, ['monty', 'python']) + self.assertEqual(b, ['.hidden', 'monty', 'python']) + + def test_get_entity(self): + # Test that a name is in the namespace of sys.modules and + # __main__.__dict__. + acp = self.autocomplete + Equal = self.assertEqual + + Equal(acp.get_entity('int'), int) + + # Test name from sys.modules. + mock = Mock() + with patch.dict('sys.modules', {'tempfile': mock}): + Equal(acp.get_entity('tempfile'), mock) + + # Test name from __main__.__dict__. + di = {'foo': 10, 'bar': 20} + with patch.dict('__main__.__dict__', {'d': di}): + Equal(acp.get_entity('d'), di) + + # Test name not in namespace. + with patch.dict('__main__.__dict__', {}): + with self.assertRaises(NameError): + acp.get_entity('not_exist') + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_autocomplete_w.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_autocomplete_w.py new file mode 100644 index 0000000000000000000000000000000000000000..a59a375c90fd807e1d3219cde60b3f2612d24fac --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_autocomplete_w.py @@ -0,0 +1,32 @@ +"Test autocomplete_w, coverage 11%." + +import unittest +from test.support import requires +from tkinter import Tk, Text + +import idlelib.autocomplete_w as acw + + +class AutoCompleteWindowTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.text = Text(cls.root) + cls.acw = acw.AutoCompleteWindow(cls.text, tags=None) + + @classmethod + def tearDownClass(cls): + del cls.text, cls.acw + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def test_init(self): + self.assertEqual(self.acw.widget, self.text) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_autoexpand.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_autoexpand.py new file mode 100644 index 0000000000000000000000000000000000000000..e734a8be714a2adc3ea1a6fca6957cac2815309e --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_autoexpand.py @@ -0,0 +1,155 @@ +"Test autoexpand, coverage 100%." + +from idlelib.autoexpand import AutoExpand +import unittest +from test.support import requires +from tkinter import Text, Tk + + +class DummyEditwin: + # AutoExpand.__init__ only needs .text + def __init__(self, text): + self.text = text + +class AutoExpandTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.tk = Tk() + cls.text = Text(cls.tk) + cls.auto_expand = AutoExpand(DummyEditwin(cls.text)) + cls.auto_expand.bell = lambda: None + +# If mock_tk.Text._decode understood indexes 'insert' with suffixed 'linestart', +# 'wordstart', and 'lineend', used by autoexpand, we could use the following +# to run these test on non-gui machines (but check bell). +## try: +## requires('gui') +## #raise ResourceDenied() # Uncomment to test mock. +## except ResourceDenied: +## from idlelib.idle_test.mock_tk import Text +## cls.text = Text() +## cls.text.bell = lambda: None +## else: +## from tkinter import Tk, Text +## cls.tk = Tk() +## cls.text = Text(cls.tk) + + @classmethod + def tearDownClass(cls): + del cls.text, cls.auto_expand + if hasattr(cls, 'tk'): + cls.tk.destroy() + del cls.tk + + def tearDown(self): + self.text.delete('1.0', 'end') + + def test_get_prevword(self): + text = self.text + previous = self.auto_expand.getprevword + equal = self.assertEqual + + equal(previous(), '') + + text.insert('insert', 't') + equal(previous(), 't') + + text.insert('insert', 'his') + equal(previous(), 'this') + + text.insert('insert', ' ') + equal(previous(), '') + + text.insert('insert', 'is') + equal(previous(), 'is') + + text.insert('insert', '\nsample\nstring') + equal(previous(), 'string') + + text.delete('3.0', 'insert') + equal(previous(), '') + + text.delete('1.0', 'end') + equal(previous(), '') + + def test_before_only(self): + previous = self.auto_expand.getprevword + expand = self.auto_expand.expand_word_event + equal = self.assertEqual + + self.text.insert('insert', 'ab ac bx ad ab a') + equal(self.auto_expand.getwords(), ['ab', 'ad', 'ac', 'a']) + expand('event') + equal(previous(), 'ab') + expand('event') + equal(previous(), 'ad') + expand('event') + equal(previous(), 'ac') + expand('event') + equal(previous(), 'a') + + def test_after_only(self): + # Also add punctuation 'noise' that should be ignored. + text = self.text + previous = self.auto_expand.getprevword + expand = self.auto_expand.expand_word_event + equal = self.assertEqual + + text.insert('insert', 'a, [ab] ac: () bx"" cd ac= ad ya') + text.mark_set('insert', '1.1') + equal(self.auto_expand.getwords(), ['ab', 'ac', 'ad', 'a']) + expand('event') + equal(previous(), 'ab') + expand('event') + equal(previous(), 'ac') + expand('event') + equal(previous(), 'ad') + expand('event') + equal(previous(), 'a') + + def test_both_before_after(self): + text = self.text + previous = self.auto_expand.getprevword + expand = self.auto_expand.expand_word_event + equal = self.assertEqual + + text.insert('insert', 'ab xy yz\n') + text.insert('insert', 'a ac by ac') + + text.mark_set('insert', '2.1') + equal(self.auto_expand.getwords(), ['ab', 'ac', 'a']) + expand('event') + equal(previous(), 'ab') + expand('event') + equal(previous(), 'ac') + expand('event') + equal(previous(), 'a') + + def test_other_expand_cases(self): + text = self.text + expand = self.auto_expand.expand_word_event + equal = self.assertEqual + + # no expansion candidate found + equal(self.auto_expand.getwords(), []) + equal(expand('event'), 'break') + + text.insert('insert', 'bx cy dz a') + equal(self.auto_expand.getwords(), []) + + # reset state by successfully expanding once + # move cursor to another position and expand again + text.insert('insert', 'ac xy a ac ad a') + text.mark_set('insert', '1.7') + expand('event') + initial_state = self.auto_expand.state + text.mark_set('insert', '1.end') + expand('event') + new_state = self.auto_expand.state + self.assertNotEqual(initial_state, new_state) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_browser.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_browser.py new file mode 100644 index 0000000000000000000000000000000000000000..6cfea3888cd6a9064be1b9b5f5c13febdc701b96 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_browser.py @@ -0,0 +1,257 @@ +"Test browser, coverage 90%." + +from idlelib import browser +from test.support import requires +import unittest +from unittest import mock +from idlelib.idle_test.mock_idle import Func +from idlelib.util import py_extensions + +from collections import deque +import os.path +import pyclbr +from tkinter import Tk + +from idlelib.tree import TreeNode + + +class ModuleBrowserTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.mb = browser.ModuleBrowser(cls.root, __file__, _utest=True) + + @classmethod + def tearDownClass(cls): + cls.mb.close() + cls.root.update_idletasks() + cls.root.destroy() + del cls.root, cls.mb + + def test_init(self): + mb = self.mb + eq = self.assertEqual + eq(mb.path, __file__) + eq(pyclbr._modules, {}) + self.assertIsInstance(mb.node, TreeNode) + self.assertIsNotNone(browser.file_open) + + def test_settitle(self): + mb = self.mb + self.assertIn(os.path.basename(__file__), mb.top.title()) + self.assertEqual(mb.top.iconname(), 'Module Browser') + + def test_rootnode(self): + mb = self.mb + rn = mb.rootnode() + self.assertIsInstance(rn, browser.ModuleBrowserTreeItem) + + def test_close(self): + mb = self.mb + mb.top.destroy = Func() + mb.node.destroy = Func() + mb.close() + self.assertTrue(mb.top.destroy.called) + self.assertTrue(mb.node.destroy.called) + del mb.top.destroy, mb.node.destroy + + def test_is_browseable_extension(self): + path = "/path/to/file" + for ext in py_extensions: + with self.subTest(ext=ext): + filename = f'{path}{ext}' + actual = browser.is_browseable_extension(filename) + expected = ext not in browser.browseable_extension_blocklist + self.assertEqual(actual, expected) + + +# Nested tree same as in test_pyclbr.py except for supers on C0. C1. +mb = pyclbr +module, fname = 'test', 'test.py' +C0 = mb.Class(module, 'C0', ['base'], fname, 1, end_lineno=9) +F1 = mb._nest_function(C0, 'F1', 3, 5) +C1 = mb._nest_class(C0, 'C1', 6, 9, ['']) +C2 = mb._nest_class(C1, 'C2', 7, 9) +F3 = mb._nest_function(C2, 'F3', 9, 9) +f0 = mb.Function(module, 'f0', fname, 11, end_lineno=15) +f1 = mb._nest_function(f0, 'f1', 12, 14) +f2 = mb._nest_function(f1, 'f2', 13, 13) +c1 = mb._nest_class(f0, 'c1', 15, 15) +mock_pyclbr_tree = {'C0': C0, 'f0': f0} + +# Adjust C0.name, C1.name so tests do not depend on order. +browser.transform_children(mock_pyclbr_tree, 'test') # C0(base) +browser.transform_children(C0.children) # C1() + +# The class below checks that the calls above are correct +# and that duplicate calls have no effect. + + +class TransformChildrenTest(unittest.TestCase): + + def test_transform_module_children(self): + eq = self.assertEqual + transform = browser.transform_children + # Parameter matches tree module. + tcl = list(transform(mock_pyclbr_tree, 'test')) + eq(tcl, [C0, f0]) + eq(tcl[0].name, 'C0(base)') + eq(tcl[1].name, 'f0') + # Check that second call does not change suffix. + tcl = list(transform(mock_pyclbr_tree, 'test')) + eq(tcl[0].name, 'C0(base)') + # Nothing to traverse if parameter name isn't same as tree module. + tcl = list(transform(mock_pyclbr_tree, 'different name')) + eq(tcl, []) + + def test_transform_node_children(self): + eq = self.assertEqual + transform = browser.transform_children + # Class with two children, one name altered. + tcl = list(transform(C0.children)) + eq(tcl, [F1, C1]) + eq(tcl[0].name, 'F1') + eq(tcl[1].name, 'C1()') + tcl = list(transform(C0.children)) + eq(tcl[1].name, 'C1()') + # Function with two children. + eq(list(transform(f0.children)), [f1, c1]) + + +class ModuleBrowserTreeItemTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + cls.mbt = browser.ModuleBrowserTreeItem(fname) + + def test_init(self): + self.assertEqual(self.mbt.file, fname) + + def test_gettext(self): + self.assertEqual(self.mbt.GetText(), fname) + + def test_geticonname(self): + self.assertEqual(self.mbt.GetIconName(), 'python') + + def test_isexpandable(self): + self.assertTrue(self.mbt.IsExpandable()) + + def test_listchildren(self): + save_rex = browser.pyclbr.readmodule_ex + save_tc = browser.transform_children + browser.pyclbr.readmodule_ex = Func(result=mock_pyclbr_tree) + browser.transform_children = Func(result=[f0, C0]) + try: + self.assertEqual(self.mbt.listchildren(), [f0, C0]) + finally: + browser.pyclbr.readmodule_ex = save_rex + browser.transform_children = save_tc + + def test_getsublist(self): + mbt = self.mbt + mbt.listchildren = Func(result=[f0, C0]) + sub0, sub1 = mbt.GetSubList() + del mbt.listchildren + self.assertIsInstance(sub0, browser.ChildBrowserTreeItem) + self.assertIsInstance(sub1, browser.ChildBrowserTreeItem) + self.assertEqual(sub0.name, 'f0') + self.assertEqual(sub1.name, 'C0(base)') + + @mock.patch('idlelib.browser.file_open') + def test_ondoubleclick(self, fopen): + mbt = self.mbt + + with mock.patch('os.path.exists', return_value=False): + mbt.OnDoubleClick() + fopen.assert_not_called() + + with mock.patch('os.path.exists', return_value=True): + mbt.OnDoubleClick() + fopen.assert_called_once_with(fname) + + +class ChildBrowserTreeItemTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + CBT = browser.ChildBrowserTreeItem + cls.cbt_f1 = CBT(f1) + cls.cbt_C1 = CBT(C1) + cls.cbt_F1 = CBT(F1) + + @classmethod + def tearDownClass(cls): + del cls.cbt_C1, cls.cbt_f1, cls.cbt_F1 + + def test_init(self): + eq = self.assertEqual + eq(self.cbt_C1.name, 'C1()') + self.assertFalse(self.cbt_C1.isfunction) + eq(self.cbt_f1.name, 'f1') + self.assertTrue(self.cbt_f1.isfunction) + + def test_gettext(self): + self.assertEqual(self.cbt_C1.GetText(), 'class C1()') + self.assertEqual(self.cbt_f1.GetText(), 'def f1(...)') + + def test_geticonname(self): + self.assertEqual(self.cbt_C1.GetIconName(), 'folder') + self.assertEqual(self.cbt_f1.GetIconName(), 'python') + + def test_isexpandable(self): + self.assertTrue(self.cbt_C1.IsExpandable()) + self.assertTrue(self.cbt_f1.IsExpandable()) + self.assertFalse(self.cbt_F1.IsExpandable()) + + def test_getsublist(self): + eq = self.assertEqual + CBT = browser.ChildBrowserTreeItem + + f1sublist = self.cbt_f1.GetSubList() + self.assertIsInstance(f1sublist[0], CBT) + eq(len(f1sublist), 1) + eq(f1sublist[0].name, 'f2') + + eq(self.cbt_F1.GetSubList(), []) + + @mock.patch('idlelib.browser.file_open') + def test_ondoubleclick(self, fopen): + goto = fopen.return_value.gotoline = mock.Mock() + self.cbt_F1.OnDoubleClick() + fopen.assert_called() + goto.assert_called() + goto.assert_called_with(self.cbt_F1.obj.lineno) + # Failure test would have to raise OSError or AttributeError. + + +class NestedChildrenTest(unittest.TestCase): + "Test that all the nodes in a nested tree are added to the BrowserTree." + + def test_nested(self): + queue = deque() + actual_names = [] + # The tree items are processed in breadth first order. + # Verify that processing each sublist hits every node and + # in the right order. + expected_names = ['f0', 'C0(base)', + 'f1', 'c1', 'F1', 'C1()', + 'f2', 'C2', + 'F3'] + CBT = browser.ChildBrowserTreeItem + queue.extend((CBT(f0), CBT(C0))) + while queue: + cb = queue.popleft() + sublist = cb.GetSubList() + queue.extend(sublist) + self.assertIn(cb.name, cb.GetText()) + self.assertIn(cb.GetIconName(), ('python', 'folder')) + self.assertIs(cb.IsExpandable(), sublist != []) + actual_names.append(cb.name) + self.assertEqual(actual_names, expected_names) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_calltip.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_calltip.py new file mode 100644 index 0000000000000000000000000000000000000000..28c196a42672fcd2b025753341a7aac656926a6a --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_calltip.py @@ -0,0 +1,372 @@ +"Test calltip, coverage 76%" + +from idlelib import calltip +import unittest +from unittest.mock import Mock +import textwrap +import types +import re +from idlelib.idle_test.mock_tk import Text +from test.support import MISSING_C_DOCSTRINGS + + +# Test Class TC is used in multiple get_argspec test methods +class TC: + 'doc' + tip = "(ai=None, *b)" + def __init__(self, ai=None, *b): 'doc' + __init__.tip = "(self, ai=None, *b)" + def t1(self): 'doc' + t1.tip = "(self)" + def t2(self, ai, b=None): 'doc' + t2.tip = "(self, ai, b=None)" + def t3(self, ai, *args): 'doc' + t3.tip = "(self, ai, *args)" + def t4(self, *args): 'doc' + t4.tip = "(self, *args)" + def t5(self, ai, b=None, *args, **kw): 'doc' + t5.tip = "(self, ai, b=None, *args, **kw)" + def t6(no, self): 'doc' + t6.tip = "(no, self)" + def __call__(self, ci): 'doc' + __call__.tip = "(self, ci)" + def nd(self): pass # No doc. + # attaching .tip to wrapped methods does not work + @classmethod + def cm(cls, a): 'doc' + @staticmethod + def sm(b): 'doc' + + +tc = TC() +default_tip = calltip._default_callable_argspec +get_spec = calltip.get_argspec + + +class Get_argspecTest(unittest.TestCase): + # The get_spec function must return a string, even if blank. + # Test a variety of objects to be sure that none cause it to raise + # (quite aside from getting as correct an answer as possible). + # The tests of builtins may break if inspect or the docstrings change, + # but a red buildbot is better than a user crash (as has happened). + # For a simple mismatch, change the expected output to the actual. + + @unittest.skipIf(MISSING_C_DOCSTRINGS, + "Signature information for builtins requires docstrings") + def test_builtins(self): + + def tiptest(obj, out): + self.assertEqual(get_spec(obj), out) + + # Python class that inherits builtin methods + class List(list): "List() doc" + + # Simulate builtin with no docstring for default tip test + class SB: __call__ = None + + if List.__doc__ is not None: + tiptest(List, + f'(iterable=(), /)' + f'\n{List.__doc__}') + tiptest(list.__new__, + '(*args, **kwargs)\n' + 'Create and return a new object. ' + 'See help(type) for accurate signature.') + tiptest(list.__init__, + '(self, /, *args, **kwargs)\n' + 'Initialize self. See help(type(self)) for accurate signature.') + append_doc = "\nAppend object to the end of the list." + tiptest(list.append, '(self, object, /)' + append_doc) + tiptest(List.append, '(self, object, /)' + append_doc) + tiptest([].append, '(object, /)' + append_doc) + # The use of 'object' above matches the signature text. + + tiptest(types.MethodType, + '(function, instance, /)\n' + 'Create a bound instance method object.') + tiptest(SB(), default_tip) + + p = re.compile('') + tiptest(re.sub, '''\ +(pattern, repl, string, count=0, flags=0) +Return the string obtained by replacing the leftmost +non-overlapping occurrences of the pattern in string by the +replacement repl. repl can be either a string or a callable; +if a string, backslash escapes in it are processed. If it is +a callable, it's passed the Match object and must return''') + tiptest(p.sub, '''\ +(repl, string, count=0) +Return the string obtained by replacing the leftmost \ +non-overlapping occurrences o...''') + + def test_signature_wrap(self): + if textwrap.TextWrapper.__doc__ is not None: + self.assertEqual(get_spec(textwrap.TextWrapper), '''\ +(width=70, initial_indent='', subsequent_indent='', expand_tabs=True, + replace_whitespace=True, fix_sentence_endings=False, break_long_words=True, + drop_whitespace=True, break_on_hyphens=True, tabsize=8, *, max_lines=None, + placeholder=' [...]') +Object for wrapping/filling text. The public interface consists of +the wrap() and fill() methods; the other methods are just there for +subclasses to override in order to tweak the default behaviour. +If you want to completely replace the main wrapping algorithm, +you\'ll probably have to override _wrap_chunks().''') + + def test_properly_formatted(self): + + def foo(s='a'*100): + pass + + def bar(s='a'*100): + """Hello Guido""" + pass + + def baz(s='a'*100, z='b'*100): + pass + + indent = calltip._INDENT + + sfoo = "(s='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"\ + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" + indent + "aaaaaaaaa"\ + "aaaaaaaaaa')" + sbar = "(s='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"\ + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" + indent + "aaaaaaaaa"\ + "aaaaaaaaaa')\nHello Guido" + sbaz = "(s='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"\ + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" + indent + "aaaaaaaaa"\ + "aaaaaaaaaa', z='bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"\ + "bbbbbbbbbbbbbbbbb\n" + indent + "bbbbbbbbbbbbbbbbbbbbbb"\ + "bbbbbbbbbbbbbbbbbbbbbb')" + + for func,doc in [(foo, sfoo), (bar, sbar), (baz, sbaz)]: + with self.subTest(func=func, doc=doc): + self.assertEqual(get_spec(func), doc) + + def test_docline_truncation(self): + def f(): pass + f.__doc__ = 'a'*300 + self.assertEqual(get_spec(f), f"()\n{'a'*(calltip._MAX_COLS-3) + '...'}") + + @unittest.skipIf(MISSING_C_DOCSTRINGS, + "Signature information for builtins requires docstrings") + def test_multiline_docstring(self): + # Test fewer lines than max. + self.assertEqual(get_spec(range), + "range(stop) -> range object\n" + "range(start, stop[, step]) -> range object") + + # Test max lines + self.assertEqual(get_spec(bytes), '''\ +bytes(iterable_of_ints) -> bytes +bytes(string, encoding[, errors]) -> bytes +bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer +bytes(int) -> bytes object of size given by the parameter initialized with null bytes +bytes() -> empty bytes object''') + + def test_multiline_docstring_2(self): + # Test more than max lines + def f(): pass + f.__doc__ = 'a\n' * 15 + self.assertEqual(get_spec(f), '()' + '\na' * calltip._MAX_LINES) + + def test_functions(self): + def t1(): 'doc' + t1.tip = "()" + def t2(a, b=None): 'doc' + t2.tip = "(a, b=None)" + def t3(a, *args): 'doc' + t3.tip = "(a, *args)" + def t4(*args): 'doc' + t4.tip = "(*args)" + def t5(a, b=None, *args, **kw): 'doc' + t5.tip = "(a, b=None, *args, **kw)" + + doc = '\ndoc' if t1.__doc__ is not None else '' + for func in (t1, t2, t3, t4, t5, TC): + with self.subTest(func=func): + self.assertEqual(get_spec(func), func.tip + doc) + + def test_methods(self): + doc = '\ndoc' if TC.__doc__ is not None else '' + for meth in (TC.t1, TC.t2, TC.t3, TC.t4, TC.t5, TC.t6, TC.__call__): + with self.subTest(meth=meth): + self.assertEqual(get_spec(meth), meth.tip + doc) + self.assertEqual(get_spec(TC.cm), "(a)" + doc) + self.assertEqual(get_spec(TC.sm), "(b)" + doc) + + def test_bound_methods(self): + # test that first parameter is correctly removed from argspec + doc = '\ndoc' if TC.__doc__ is not None else '' + for meth, mtip in ((tc.t1, "()"), (tc.t4, "(*args)"), + (tc.t6, "(self)"), (tc.__call__, '(ci)'), + (tc, '(ci)'), (TC.cm, "(a)"),): + with self.subTest(meth=meth, mtip=mtip): + self.assertEqual(get_spec(meth), mtip + doc) + + def test_starred_parameter(self): + # test that starred first parameter is *not* removed from argspec + class C: + def m1(*args): pass + c = C() + for meth, mtip in ((C.m1, '(*args)'), (c.m1, "(*args)"),): + with self.subTest(meth=meth, mtip=mtip): + self.assertEqual(get_spec(meth), mtip) + + def test_invalid_method_get_spec(self): + class C: + def m2(**kwargs): pass + class Test: + def __call__(*, a): pass + + mtip = calltip._invalid_method + self.assertEqual(get_spec(C().m2), mtip) + self.assertEqual(get_spec(Test()), mtip) + + def test_non_ascii_name(self): + # test that re works to delete a first parameter name that + # includes non-ascii chars, such as various forms of A. + uni = "(A\u0391\u0410\u05d0\u0627\u0905\u1e00\u3042, a)" + assert calltip._first_param.sub('', uni) == '(a)' + + def test_no_docstring(self): + for meth, mtip in ((TC.nd, "(self)"), (tc.nd, "()")): + with self.subTest(meth=meth, mtip=mtip): + self.assertEqual(get_spec(meth), mtip) + + def test_buggy_getattr_class(self): + class NoCall: + def __getattr__(self, name): # Not invoked for class attribute. + raise IndexError # Bug. + class CallA(NoCall): + def __call__(self, ci): # Bug does not matter. + pass + class CallB(NoCall): + def __call__(oui, a, b, c): # Non-standard 'self'. + pass + + for meth, mtip in ((NoCall, default_tip), (CallA, default_tip), + (NoCall(), ''), (CallA(), '(ci)'), + (CallB(), '(a, b, c)')): + with self.subTest(meth=meth, mtip=mtip): + self.assertEqual(get_spec(meth), mtip) + + def test_metaclass_class(self): # Failure case for issue 38689. + class Type(type): # Type() requires 3 type args, returns class. + __class__ = property({}.__getitem__, {}.__setitem__) + class Object(metaclass=Type): + __slots__ = '__class__' + for meth, mtip in ((Type, get_spec(type)), (Object, default_tip), + (Object(), '')): + with self.subTest(meth=meth, mtip=mtip): + self.assertEqual(get_spec(meth), mtip) + + def test_non_callables(self): + for obj in (0, 0.0, '0', b'0', [], {}): + with self.subTest(obj=obj): + self.assertEqual(get_spec(obj), '') + + +class Get_entityTest(unittest.TestCase): + def test_bad_entity(self): + self.assertIsNone(calltip.get_entity('1/0')) + def test_good_entity(self): + self.assertIs(calltip.get_entity('int'), int) + + +# Test the 9 Calltip methods. +# open_calltip is about half the code; the others are fairly trivial. +# The default mocks are what are needed for open_calltip. + +class mock_Shell: + "Return mock sufficient to pass to hyperparser." + def __init__(self, text): + text.tag_prevrange = Mock(return_value=None) + self.text = text + self.prompt_last_line = ">>> " + self.indentwidth = 4 + self.tabwidth = 8 + + +class mock_TipWindow: + def __init__(self): + pass + + def showtip(self, text, parenleft, parenright): + self.args = parenleft, parenright + self.parenline, self.parencol = map(int, parenleft.split('.')) + + +class WrappedCalltip(calltip.Calltip): + def _make_tk_calltip_window(self): + return mock_TipWindow() + + def remove_calltip_window(self, event=None): + if self.active_calltip: # Setup to None. + self.active_calltip = None + self.tips_removed += 1 # Setup to 0. + + def fetch_tip(self, expression): + return 'tip' + + +class CalltipTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + cls.text = Text() + cls.ct = WrappedCalltip(mock_Shell(cls.text)) + + def setUp(self): + self.text.delete('1.0', 'end') # Insert and call + self.ct.active_calltip = None + # Test .active_calltip, +args + self.ct.tips_removed = 0 + + def open_close(self, testfunc): + # Open-close template with testfunc called in between. + opentip = self.ct.open_calltip + self.text.insert(1.0, 'f(') + opentip(False) + self.tip = self.ct.active_calltip + testfunc(self) ### + self.text.insert('insert', ')') + opentip(False) + self.assertIsNone(self.ct.active_calltip, None) + + def test_open_close(self): + def args(self): + self.assertEqual(self.tip.args, ('1.1', '1.end')) + self.open_close(args) + + def test_repeated_force(self): + def force(self): + for char in 'abc': + self.text.insert('insert', 'a') + self.ct.open_calltip(True) + self.ct.open_calltip(True) + self.assertIs(self.ct.active_calltip, self.tip) + self.open_close(force) + + def test_repeated_parens(self): + def parens(self): + for context in "a", "'": + with self.subTest(context=context): + self.text.insert('insert', context) + for char in '(()())': + self.text.insert('insert', char) + self.assertIs(self.ct.active_calltip, self.tip) + self.text.insert('insert', "'") + self.open_close(parens) + + def test_comment_parens(self): + def comment(self): + self.text.insert('insert', "# ") + for char in '(()())': + self.text.insert('insert', char) + self.assertIs(self.ct.active_calltip, self.tip) + self.text.insert('insert', "\n") + self.open_close(comment) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_calltip_w.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_calltip_w.py new file mode 100644 index 0000000000000000000000000000000000000000..a5ec76e15ffdf3ed8c4259dd3c9435ca9e0ec3a4 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_calltip_w.py @@ -0,0 +1,29 @@ +"Test calltip_w, coverage 18%." + +from idlelib import calltip_w +import unittest +from test.support import requires +from tkinter import Tk, Text + + +class CallTipWindowTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.text = Text(cls.root) + cls.calltip = calltip_w.CalltipWindow(cls.text) + + @classmethod + def tearDownClass(cls): + cls.root.update_idletasks() + cls.root.destroy() + del cls.text, cls.root + + def test_init(self): + self.assertEqual(self.calltip.anchor_widget, self.text) + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_codecontext.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_codecontext.py new file mode 100644 index 0000000000000000000000000000000000000000..6969ad73b01a81a7ec896a2c1991905e26e7a564 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_codecontext.py @@ -0,0 +1,455 @@ +"Test codecontext, coverage 100%" + +from idlelib import codecontext +import unittest +import unittest.mock +from test.support import requires +from tkinter import NSEW, Tk, Frame, Text, TclError + +from unittest import mock +import re +from idlelib import config + + +usercfg = codecontext.idleConf.userCfg +testcfg = { + 'main': config.IdleUserConfParser(''), + 'highlight': config.IdleUserConfParser(''), + 'keys': config.IdleUserConfParser(''), + 'extensions': config.IdleUserConfParser(''), +} +code_sample = """\ + +class C1: + # Class comment. + def __init__(self, a, b): + self.a = a + self.b = b + def compare(self): + if a > b: + return a + elif a < b: + return b + else: + return None +""" + + +class DummyEditwin: + def __init__(self, root, frame, text): + self.root = root + self.top = root + self.text_frame = frame + self.text = text + self.label = '' + + def getlineno(self, index): + return int(float(self.text.index(index))) + + def update_menu_label(self, **kwargs): + self.label = kwargs['label'] + + +class CodeContextTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + root = cls.root = Tk() + root.withdraw() + frame = cls.frame = Frame(root) + text = cls.text = Text(frame) + text.insert('1.0', code_sample) + # Need to pack for creation of code context text widget. + frame.pack(side='left', fill='both', expand=1) + text.grid(row=1, column=1, sticky=NSEW) + cls.editor = DummyEditwin(root, frame, text) + codecontext.idleConf.userCfg = testcfg + + @classmethod + def tearDownClass(cls): + codecontext.idleConf.userCfg = usercfg + cls.editor.text.delete('1.0', 'end') + del cls.editor, cls.frame, cls.text + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def setUp(self): + self.text.yview(0) + self.text['font'] = 'TkFixedFont' + self.cc = codecontext.CodeContext(self.editor) + + self.highlight_cfg = {"background": '#abcdef', + "foreground": '#123456'} + orig_idleConf_GetHighlight = codecontext.idleConf.GetHighlight + def mock_idleconf_GetHighlight(theme, element): + if element == 'context': + return self.highlight_cfg + return orig_idleConf_GetHighlight(theme, element) + GetHighlight_patcher = unittest.mock.patch.object( + codecontext.idleConf, 'GetHighlight', mock_idleconf_GetHighlight) + GetHighlight_patcher.start() + self.addCleanup(GetHighlight_patcher.stop) + + self.font_override = 'TkFixedFont' + def mock_idleconf_GetFont(root, configType, section): + return self.font_override + GetFont_patcher = unittest.mock.patch.object( + codecontext.idleConf, 'GetFont', mock_idleconf_GetFont) + GetFont_patcher.start() + self.addCleanup(GetFont_patcher.stop) + + def tearDown(self): + if self.cc.context: + self.cc.context.destroy() + # Explicitly call __del__ to remove scheduled scripts. + self.cc.__del__() + del self.cc.context, self.cc + + def test_init(self): + eq = self.assertEqual + ed = self.editor + cc = self.cc + + eq(cc.editwin, ed) + eq(cc.text, ed.text) + eq(cc.text['font'], ed.text['font']) + self.assertIsNone(cc.context) + eq(cc.info, [(0, -1, '', False)]) + eq(cc.topvisible, 1) + self.assertIsNone(self.cc.t1) + + def test_del(self): + self.cc.__del__() + + def test_del_with_timer(self): + timer = self.cc.t1 = self.text.after(10000, lambda: None) + self.cc.__del__() + with self.assertRaises(TclError) as cm: + self.root.tk.call('after', 'info', timer) + self.assertIn("doesn't exist", str(cm.exception)) + + def test_reload(self): + codecontext.CodeContext.reload() + self.assertEqual(self.cc.context_depth, 15) + + def test_toggle_code_context_event(self): + eq = self.assertEqual + cc = self.cc + toggle = cc.toggle_code_context_event + + # Make sure code context is off. + if cc.context: + toggle() + + # Toggle on. + toggle() + self.assertIsNotNone(cc.context) + eq(cc.context['font'], self.text['font']) + eq(cc.context['fg'], self.highlight_cfg['foreground']) + eq(cc.context['bg'], self.highlight_cfg['background']) + eq(cc.context.get('1.0', 'end-1c'), '') + eq(cc.editwin.label, 'Hide Code Context') + eq(self.root.tk.call('after', 'info', self.cc.t1)[1], 'timer') + + # Toggle off. + toggle() + self.assertIsNone(cc.context) + eq(cc.editwin.label, 'Show Code Context') + self.assertIsNone(self.cc.t1) + + # Scroll down and toggle back on. + line11_context = '\n'.join(x[2] for x in cc.get_context(11)[0]) + cc.text.yview(11) + toggle() + eq(cc.context.get('1.0', 'end-1c'), line11_context) + + # Toggle off and on again. + toggle() + toggle() + eq(cc.context.get('1.0', 'end-1c'), line11_context) + + def test_get_context(self): + eq = self.assertEqual + gc = self.cc.get_context + + # stopline must be greater than 0. + with self.assertRaises(AssertionError): + gc(1, stopline=0) + + eq(gc(3), ([(2, 0, 'class C1:', 'class')], 0)) + + # Don't return comment. + eq(gc(4), ([(2, 0, 'class C1:', 'class')], 0)) + + # Two indentation levels and no comment. + eq(gc(5), ([(2, 0, 'class C1:', 'class'), + (4, 4, ' def __init__(self, a, b):', 'def')], 0)) + + # Only one 'def' is returned, not both at the same indent level. + eq(gc(10), ([(2, 0, 'class C1:', 'class'), + (7, 4, ' def compare(self):', 'def'), + (8, 8, ' if a > b:', 'if')], 0)) + + # With 'elif', also show the 'if' even though it's at the same level. + eq(gc(11), ([(2, 0, 'class C1:', 'class'), + (7, 4, ' def compare(self):', 'def'), + (8, 8, ' if a > b:', 'if'), + (10, 8, ' elif a < b:', 'elif')], 0)) + + # Set stop_line to not go back to first line in source code. + # Return includes stop_line. + eq(gc(11, stopline=2), ([(2, 0, 'class C1:', 'class'), + (7, 4, ' def compare(self):', 'def'), + (8, 8, ' if a > b:', 'if'), + (10, 8, ' elif a < b:', 'elif')], 0)) + eq(gc(11, stopline=3), ([(7, 4, ' def compare(self):', 'def'), + (8, 8, ' if a > b:', 'if'), + (10, 8, ' elif a < b:', 'elif')], 4)) + eq(gc(11, stopline=8), ([(8, 8, ' if a > b:', 'if'), + (10, 8, ' elif a < b:', 'elif')], 8)) + + # Set stop_indent to test indent level to stop at. + eq(gc(11, stopindent=4), ([(7, 4, ' def compare(self):', 'def'), + (8, 8, ' if a > b:', 'if'), + (10, 8, ' elif a < b:', 'elif')], 4)) + # Check that the 'if' is included. + eq(gc(11, stopindent=8), ([(8, 8, ' if a > b:', 'if'), + (10, 8, ' elif a < b:', 'elif')], 8)) + + def test_update_code_context(self): + eq = self.assertEqual + cc = self.cc + # Ensure code context is active. + if not cc.context: + cc.toggle_code_context_event() + + # Invoke update_code_context without scrolling - nothing happens. + self.assertIsNone(cc.update_code_context()) + eq(cc.info, [(0, -1, '', False)]) + eq(cc.topvisible, 1) + + # Scroll down to line 1. + cc.text.yview(1) + cc.update_code_context() + eq(cc.info, [(0, -1, '', False)]) + eq(cc.topvisible, 2) + eq(cc.context.get('1.0', 'end-1c'), '') + + # Scroll down to line 2. + cc.text.yview(2) + cc.update_code_context() + eq(cc.info, [(0, -1, '', False), (2, 0, 'class C1:', 'class')]) + eq(cc.topvisible, 3) + eq(cc.context.get('1.0', 'end-1c'), 'class C1:') + + # Scroll down to line 3. Since it's a comment, nothing changes. + cc.text.yview(3) + cc.update_code_context() + eq(cc.info, [(0, -1, '', False), (2, 0, 'class C1:', 'class')]) + eq(cc.topvisible, 4) + eq(cc.context.get('1.0', 'end-1c'), 'class C1:') + + # Scroll down to line 4. + cc.text.yview(4) + cc.update_code_context() + eq(cc.info, [(0, -1, '', False), + (2, 0, 'class C1:', 'class'), + (4, 4, ' def __init__(self, a, b):', 'def')]) + eq(cc.topvisible, 5) + eq(cc.context.get('1.0', 'end-1c'), 'class C1:\n' + ' def __init__(self, a, b):') + + # Scroll down to line 11. Last 'def' is removed. + cc.text.yview(11) + cc.update_code_context() + eq(cc.info, [(0, -1, '', False), + (2, 0, 'class C1:', 'class'), + (7, 4, ' def compare(self):', 'def'), + (8, 8, ' if a > b:', 'if'), + (10, 8, ' elif a < b:', 'elif')]) + eq(cc.topvisible, 12) + eq(cc.context.get('1.0', 'end-1c'), 'class C1:\n' + ' def compare(self):\n' + ' if a > b:\n' + ' elif a < b:') + + # No scroll. No update, even though context_depth changed. + cc.update_code_context() + cc.context_depth = 1 + eq(cc.info, [(0, -1, '', False), + (2, 0, 'class C1:', 'class'), + (7, 4, ' def compare(self):', 'def'), + (8, 8, ' if a > b:', 'if'), + (10, 8, ' elif a < b:', 'elif')]) + eq(cc.topvisible, 12) + eq(cc.context.get('1.0', 'end-1c'), 'class C1:\n' + ' def compare(self):\n' + ' if a > b:\n' + ' elif a < b:') + + # Scroll up. + cc.text.yview(5) + cc.update_code_context() + eq(cc.info, [(0, -1, '', False), + (2, 0, 'class C1:', 'class'), + (4, 4, ' def __init__(self, a, b):', 'def')]) + eq(cc.topvisible, 6) + # context_depth is 1. + eq(cc.context.get('1.0', 'end-1c'), ' def __init__(self, a, b):') + + def test_jumptoline(self): + eq = self.assertEqual + cc = self.cc + jump = cc.jumptoline + + if not cc.context: + cc.toggle_code_context_event() + + # Empty context. + cc.text.yview('2.0') + cc.update_code_context() + eq(cc.topvisible, 2) + cc.context.mark_set('insert', '1.5') + jump() + eq(cc.topvisible, 1) + + # 4 lines of context showing. + cc.text.yview('12.0') + cc.update_code_context() + eq(cc.topvisible, 12) + cc.context.mark_set('insert', '3.0') + jump() + eq(cc.topvisible, 8) + + # More context lines than limit. + cc.context_depth = 2 + cc.text.yview('12.0') + cc.update_code_context() + eq(cc.topvisible, 12) + cc.context.mark_set('insert', '1.0') + jump() + eq(cc.topvisible, 8) + + # Context selection stops jump. + cc.text.yview('5.0') + cc.update_code_context() + cc.context.tag_add('sel', '1.0', '2.0') + cc.context.mark_set('insert', '1.0') + jump() # Without selection, to line 2. + eq(cc.topvisible, 5) + + @mock.patch.object(codecontext.CodeContext, 'update_code_context') + def test_timer_event(self, mock_update): + # Ensure code context is not active. + if self.cc.context: + self.cc.toggle_code_context_event() + self.cc.timer_event() + mock_update.assert_not_called() + + # Activate code context. + self.cc.toggle_code_context_event() + self.cc.timer_event() + mock_update.assert_called() + + def test_font(self): + eq = self.assertEqual + cc = self.cc + + orig_font = cc.text['font'] + test_font = 'TkTextFont' + self.assertNotEqual(orig_font, test_font) + + # Ensure code context is not active. + if cc.context is not None: + cc.toggle_code_context_event() + + self.font_override = test_font + # Nothing breaks or changes with inactive code context. + cc.update_font() + + # Activate code context, previous font change is immediately effective. + cc.toggle_code_context_event() + eq(cc.context['font'], test_font) + + # Call the font update, change is picked up. + self.font_override = orig_font + cc.update_font() + eq(cc.context['font'], orig_font) + + def test_highlight_colors(self): + eq = self.assertEqual + cc = self.cc + + orig_colors = dict(self.highlight_cfg) + test_colors = {'background': '#222222', 'foreground': '#ffff00'} + + def assert_colors_are_equal(colors): + eq(cc.context['background'], colors['background']) + eq(cc.context['foreground'], colors['foreground']) + + # Ensure code context is not active. + if cc.context: + cc.toggle_code_context_event() + + self.highlight_cfg = test_colors + # Nothing breaks with inactive code context. + cc.update_highlight_colors() + + # Activate code context, previous colors change is immediately effective. + cc.toggle_code_context_event() + assert_colors_are_equal(test_colors) + + # Call colors update with no change to the configured colors. + cc.update_highlight_colors() + assert_colors_are_equal(test_colors) + + # Call the colors update with code context active, change is picked up. + self.highlight_cfg = orig_colors + cc.update_highlight_colors() + assert_colors_are_equal(orig_colors) + + +class HelperFunctionText(unittest.TestCase): + + def test_get_spaces_firstword(self): + get = codecontext.get_spaces_firstword + test_lines = ( + (' first word', (' ', 'first')), + ('\tfirst word', ('\t', 'first')), + (' \u19D4\u19D2: ', (' ', '\u19D4\u19D2')), + ('no spaces', ('', 'no')), + ('', ('', '')), + ('# TEST COMMENT', ('', '')), + (' (continuation)', (' ', '')) + ) + for line, expected_output in test_lines: + self.assertEqual(get(line), expected_output) + + # Send the pattern in the call. + self.assertEqual(get(' (continuation)', + c=re.compile(r'^(\s*)([^\s]*)')), + (' ', '(continuation)')) + + def test_get_line_info(self): + eq = self.assertEqual + gli = codecontext.get_line_info + lines = code_sample.splitlines() + + # Line 1 is not a BLOCKOPENER. + eq(gli(lines[0]), (codecontext.INFINITY, '', False)) + # Line 2 is a BLOCKOPENER without an indent. + eq(gli(lines[1]), (0, 'class C1:', 'class')) + # Line 3 is not a BLOCKOPENER and does not return the indent level. + eq(gli(lines[2]), (codecontext.INFINITY, ' # Class comment.', False)) + # Line 4 is a BLOCKOPENER and is indented. + eq(gli(lines[3]), (4, ' def __init__(self, a, b):', 'def')) + # Line 8 is a different BLOCKOPENER and is indented. + eq(gli(lines[7]), (8, ' if a > b:', 'if')) + # Test tab. + eq(gli('\tif a == b:'), (1, '\tif a == b:', 'if')) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_colorizer.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_colorizer.py new file mode 100644 index 0000000000000000000000000000000000000000..308bc389384d33dc8d4bb473b06dc5b5b127c0b6 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_colorizer.py @@ -0,0 +1,622 @@ +"Test colorizer, coverage 99%." +from idlelib import colorizer +from test.support import requires +import unittest +from unittest import mock +from idlelib.idle_test.tkinter_testing_utils import run_in_tk_mainloop + +from functools import partial +import textwrap +from tkinter import Tk, Text +from idlelib import config +from idlelib.percolator import Percolator + + +usercfg = colorizer.idleConf.userCfg +testcfg = { + 'main': config.IdleUserConfParser(''), + 'highlight': config.IdleUserConfParser(''), + 'keys': config.IdleUserConfParser(''), + 'extensions': config.IdleUserConfParser(''), +} + +source = textwrap.dedent("""\ + if True: int ('1') # keyword, builtin, string, comment + elif False: print(0) # 'string' in comment + else: float(None) # if in comment + if iF + If + IF: 'keyword matching must respect case' + if'': x or'' # valid keyword-string no-space combinations + async def f(): await g() + # Strings should be entirely colored, including quotes. + 'x', '''x''', "x", \"""x\""" + 'abc\\ + def' + '''abc\\ + def''' + # All valid prefixes for unicode and byte strings should be colored. + r'x', u'x', R'x', U'x', f'x', F'x' + fr'x', Fr'x', fR'x', FR'x', rf'x', rF'x', Rf'x', RF'x' + b'x',B'x', br'x',Br'x',bR'x',BR'x', rb'x', rB'x',Rb'x',RB'x' + # Invalid combinations of legal characters should be half colored. + ur'x', ru'x', uf'x', fu'x', UR'x', ufr'x', rfu'x', xf'x', fx'x' + match point: + case (x, 0) as _: + print(f"X={x}") + case [_, [_], "_", + _]: + pass + case _ if ("a" if _ else set()): pass + case _: + raise ValueError("Not a point _") + ''' + case _:''' + "match x:" + """) + + +def setUpModule(): + colorizer.idleConf.userCfg = testcfg + + +def tearDownModule(): + colorizer.idleConf.userCfg = usercfg + + +class FunctionTest(unittest.TestCase): + + def test_any(self): + self.assertEqual(colorizer.any('test', ('a', 'b', 'cd')), + '(?Pa|b|cd)') + + def test_make_pat(self): + # Tested in more detail by testing prog. + self.assertTrue(colorizer.make_pat()) + + def test_prog(self): + prog = colorizer.prog + eq = self.assertEqual + line = 'def f():\n print("hello")\n' + m = prog.search(line) + eq(m.groupdict()['KEYWORD'], 'def') + m = prog.search(line, m.end()) + eq(m.groupdict()['SYNC'], '\n') + m = prog.search(line, m.end()) + eq(m.groupdict()['BUILTIN'], 'print') + m = prog.search(line, m.end()) + eq(m.groupdict()['STRING'], '"hello"') + m = prog.search(line, m.end()) + eq(m.groupdict()['SYNC'], '\n') + + def test_idprog(self): + idprog = colorizer.idprog + m = idprog.match('nospace') + self.assertIsNone(m) + m = idprog.match(' space') + self.assertEqual(m.group(0), ' space') + + +class ColorConfigTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + root = cls.root = Tk() + root.withdraw() + cls.text = Text(root) + + @classmethod + def tearDownClass(cls): + del cls.text + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def test_color_config(self): + text = self.text + eq = self.assertEqual + colorizer.color_config(text) + # Uses IDLE Classic theme as default. + eq(text['background'], '#ffffff') + eq(text['foreground'], '#000000') + eq(text['selectbackground'], 'gray') + eq(text['selectforeground'], '#000000') + eq(text['insertbackground'], 'black') + eq(text['inactiveselectbackground'], 'gray') + + +class ColorDelegatorInstantiationTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + root = cls.root = Tk() + root.withdraw() + cls.text = Text(root) + + @classmethod + def tearDownClass(cls): + del cls.text + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def setUp(self): + self.color = colorizer.ColorDelegator() + + def tearDown(self): + self.color.close() + self.text.delete('1.0', 'end') + self.color.resetcache() + del self.color + + def test_init(self): + color = self.color + self.assertIsInstance(color, colorizer.ColorDelegator) + + def test_init_state(self): + # init_state() is called during the instantiation of + # ColorDelegator in setUp(). + color = self.color + self.assertIsNone(color.after_id) + self.assertTrue(color.allow_colorizing) + self.assertFalse(color.colorizing) + self.assertFalse(color.stop_colorizing) + + +class ColorDelegatorTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + root = cls.root = Tk() + root.withdraw() + text = cls.text = Text(root) + cls.percolator = Percolator(text) + # Delegator stack = [Delegator(text)] + + @classmethod + def tearDownClass(cls): + cls.percolator.close() + del cls.percolator, cls.text + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def setUp(self): + self.color = colorizer.ColorDelegator() + self.percolator.insertfilter(self.color) + # Calls color.setdelegate(Delegator(text)). + + def tearDown(self): + self.color.close() + self.percolator.removefilter(self.color) + self.text.delete('1.0', 'end') + self.color.resetcache() + del self.color + + def test_setdelegate(self): + # Called in setUp when filter is attached to percolator. + color = self.color + self.assertIsInstance(color.delegate, colorizer.Delegator) + # It is too late to mock notify_range, so test side effect. + self.assertEqual(self.root.tk.call( + 'after', 'info', color.after_id)[1], 'timer') + + def test_LoadTagDefs(self): + highlight = partial(config.idleConf.GetHighlight, theme='IDLE Classic') + for tag, colors in self.color.tagdefs.items(): + with self.subTest(tag=tag): + self.assertIn('background', colors) + self.assertIn('foreground', colors) + if tag not in ('SYNC', 'TODO'): + self.assertEqual(colors, highlight(element=tag.lower())) + + def test_config_colors(self): + text = self.text + highlight = partial(config.idleConf.GetHighlight, theme='IDLE Classic') + for tag in self.color.tagdefs: + for plane in ('background', 'foreground'): + with self.subTest(tag=tag, plane=plane): + if tag in ('SYNC', 'TODO'): + self.assertEqual(text.tag_cget(tag, plane), '') + else: + self.assertEqual(text.tag_cget(tag, plane), + highlight(element=tag.lower())[plane]) + # 'sel' is marked as the highest priority. + self.assertEqual(text.tag_names()[-1], 'sel') + + @mock.patch.object(colorizer.ColorDelegator, 'notify_range') + def test_insert(self, mock_notify): + text = self.text + # Initial text. + text.insert('insert', 'foo') + self.assertEqual(text.get('1.0', 'end'), 'foo\n') + mock_notify.assert_called_with('1.0', '1.0+3c') + # Additional text. + text.insert('insert', 'barbaz') + self.assertEqual(text.get('1.0', 'end'), 'foobarbaz\n') + mock_notify.assert_called_with('1.3', '1.3+6c') + + @mock.patch.object(colorizer.ColorDelegator, 'notify_range') + def test_delete(self, mock_notify): + text = self.text + # Initialize text. + text.insert('insert', 'abcdefghi') + self.assertEqual(text.get('1.0', 'end'), 'abcdefghi\n') + # Delete single character. + text.delete('1.7') + self.assertEqual(text.get('1.0', 'end'), 'abcdefgi\n') + mock_notify.assert_called_with('1.7') + # Delete multiple characters. + text.delete('1.3', '1.6') + self.assertEqual(text.get('1.0', 'end'), 'abcgi\n') + mock_notify.assert_called_with('1.3') + + def test_notify_range(self): + text = self.text + color = self.color + eq = self.assertEqual + + # Colorizing already scheduled. + save_id = color.after_id + eq(self.root.tk.call('after', 'info', save_id)[1], 'timer') + self.assertFalse(color.colorizing) + self.assertFalse(color.stop_colorizing) + self.assertTrue(color.allow_colorizing) + + # Coloring scheduled and colorizing in progress. + color.colorizing = True + color.notify_range('1.0', 'end') + self.assertFalse(color.stop_colorizing) + eq(color.after_id, save_id) + + # No colorizing scheduled and colorizing in progress. + text.after_cancel(save_id) + color.after_id = None + color.notify_range('1.0', '1.0+3c') + self.assertTrue(color.stop_colorizing) + self.assertIsNotNone(color.after_id) + eq(self.root.tk.call('after', 'info', color.after_id)[1], 'timer') + # New event scheduled. + self.assertNotEqual(color.after_id, save_id) + + # No colorizing scheduled and colorizing off. + text.after_cancel(color.after_id) + color.after_id = None + color.allow_colorizing = False + color.notify_range('1.4', '1.4+10c') + # Nothing scheduled when colorizing is off. + self.assertIsNone(color.after_id) + + def test_toggle_colorize_event(self): + color = self.color + eq = self.assertEqual + + # Starts with colorizing allowed and scheduled. + self.assertFalse(color.colorizing) + self.assertFalse(color.stop_colorizing) + self.assertTrue(color.allow_colorizing) + eq(self.root.tk.call('after', 'info', color.after_id)[1], 'timer') + + # Toggle colorizing off. + color.toggle_colorize_event() + self.assertIsNone(color.after_id) + self.assertFalse(color.colorizing) + self.assertFalse(color.stop_colorizing) + self.assertFalse(color.allow_colorizing) + + # Toggle on while colorizing in progress (doesn't add timer). + color.colorizing = True + color.toggle_colorize_event() + self.assertIsNone(color.after_id) + self.assertTrue(color.colorizing) + self.assertFalse(color.stop_colorizing) + self.assertTrue(color.allow_colorizing) + + # Toggle off while colorizing in progress. + color.toggle_colorize_event() + self.assertIsNone(color.after_id) + self.assertTrue(color.colorizing) + self.assertTrue(color.stop_colorizing) + self.assertFalse(color.allow_colorizing) + + # Toggle on while colorizing not in progress. + color.colorizing = False + color.toggle_colorize_event() + eq(self.root.tk.call('after', 'info', color.after_id)[1], 'timer') + self.assertFalse(color.colorizing) + self.assertTrue(color.stop_colorizing) + self.assertTrue(color.allow_colorizing) + + @mock.patch.object(colorizer.ColorDelegator, 'recolorize_main') + def test_recolorize(self, mock_recmain): + text = self.text + color = self.color + eq = self.assertEqual + # Call recolorize manually and not scheduled. + text.after_cancel(color.after_id) + + # No delegate. + save_delegate = color.delegate + color.delegate = None + color.recolorize() + mock_recmain.assert_not_called() + color.delegate = save_delegate + + # Toggle off colorizing. + color.allow_colorizing = False + color.recolorize() + mock_recmain.assert_not_called() + color.allow_colorizing = True + + # Colorizing in progress. + color.colorizing = True + color.recolorize() + mock_recmain.assert_not_called() + color.colorizing = False + + # Colorizing is done, but not completed, so rescheduled. + color.recolorize() + self.assertFalse(color.stop_colorizing) + self.assertFalse(color.colorizing) + mock_recmain.assert_called() + eq(mock_recmain.call_count, 1) + # Rescheduled when TODO tag still exists. + eq(self.root.tk.call('after', 'info', color.after_id)[1], 'timer') + + # No changes to text, so no scheduling added. + text.tag_remove('TODO', '1.0', 'end') + color.recolorize() + self.assertFalse(color.stop_colorizing) + self.assertFalse(color.colorizing) + mock_recmain.assert_called() + eq(mock_recmain.call_count, 2) + self.assertIsNone(color.after_id) + + @mock.patch.object(colorizer.ColorDelegator, 'notify_range') + def test_recolorize_main(self, mock_notify): + text = self.text + color = self.color + eq = self.assertEqual + + text.insert('insert', source) + expected = (('1.0', ('KEYWORD',)), ('1.2', ()), ('1.3', ('KEYWORD',)), + ('1.7', ()), ('1.9', ('BUILTIN',)), ('1.14', ('STRING',)), + ('1.19', ('COMMENT',)), + ('2.1', ('KEYWORD',)), ('2.18', ()), ('2.25', ('COMMENT',)), + ('3.6', ('BUILTIN',)), ('3.12', ('KEYWORD',)), ('3.21', ('COMMENT',)), + ('4.0', ('KEYWORD',)), ('4.3', ()), ('4.6', ()), + ('5.2', ('STRING',)), ('5.8', ('KEYWORD',)), ('5.10', ('STRING',)), + ('6.0', ('KEYWORD',)), ('6.10', ('DEFINITION',)), ('6.11', ()), + ('8.0', ('STRING',)), ('8.4', ()), ('8.5', ('STRING',)), + ('8.12', ()), ('8.14', ('STRING',)), + ('19.0', ('KEYWORD',)), + ('20.4', ('KEYWORD',)), ('20.16', ('KEYWORD',)),# ('20.19', ('KEYWORD',)), + #('22.4', ('KEYWORD',)), ('22.10', ('KEYWORD',)), ('22.14', ('KEYWORD',)), ('22.19', ('STRING',)), + #('23.12', ('KEYWORD',)), + ('24.8', ('KEYWORD',)), + ('25.4', ('KEYWORD',)), ('25.9', ('KEYWORD',)), + ('25.11', ('KEYWORD',)), ('25.15', ('STRING',)), + ('25.19', ('KEYWORD',)), ('25.22', ()), + ('25.24', ('KEYWORD',)), ('25.29', ('BUILTIN',)), ('25.37', ('KEYWORD',)), + ('26.4', ('KEYWORD',)), ('26.9', ('KEYWORD',)),# ('26.11', ('KEYWORD',)), ('26.14', (),), + ('27.25', ('STRING',)), ('27.38', ('STRING',)), + ('29.0', ('STRING',)), + ('30.1', ('STRING',)), + # SYNC at the end of every line. + ('1.55', ('SYNC',)), ('2.50', ('SYNC',)), ('3.34', ('SYNC',)), + ) + + # Nothing marked to do therefore no tags in text. + text.tag_remove('TODO', '1.0', 'end') + color.recolorize_main() + for tag in text.tag_names(): + with self.subTest(tag=tag): + eq(text.tag_ranges(tag), ()) + + # Source marked for processing. + text.tag_add('TODO', '1.0', 'end') + # Check some indexes. + color.recolorize_main() + for index, expected_tags in expected: + with self.subTest(index=index): + eq(text.tag_names(index), expected_tags) + + # Check for some tags for ranges. + eq(text.tag_nextrange('TODO', '1.0'), ()) + eq(text.tag_nextrange('KEYWORD', '1.0'), ('1.0', '1.2')) + eq(text.tag_nextrange('COMMENT', '2.0'), ('2.22', '2.43')) + eq(text.tag_nextrange('SYNC', '2.0'), ('2.43', '3.0')) + eq(text.tag_nextrange('STRING', '2.0'), ('4.17', '4.53')) + eq(text.tag_nextrange('STRING', '8.0'), ('8.0', '8.3')) + eq(text.tag_nextrange('STRING', '8.3'), ('8.5', '8.12')) + eq(text.tag_nextrange('STRING', '8.12'), ('8.14', '8.17')) + eq(text.tag_nextrange('STRING', '8.17'), ('8.19', '8.26')) + eq(text.tag_nextrange('SYNC', '8.0'), ('8.26', '9.0')) + eq(text.tag_nextrange('SYNC', '30.0'), ('30.10', '32.0')) + + def _assert_highlighting(self, source, tag_ranges): + """Check highlighting of a given piece of code. + + This inserts just this code into the Text widget. It will then + check that the resulting highlighting tag ranges exactly match + those described in the given `tag_ranges` dict. + + Note that the irrelevant tags 'sel', 'TODO' and 'SYNC' are + ignored. + """ + text = self.text + + with mock.patch.object(colorizer.ColorDelegator, 'notify_range'): + text.delete('1.0', 'end-1c') + text.insert('insert', source) + text.tag_add('TODO', '1.0', 'end-1c') + self.color.recolorize_main() + + # Make a dict with highlighting tag ranges in the Text widget. + text_tag_ranges = {} + for tag in set(text.tag_names()) - {'sel', 'TODO', 'SYNC'}: + indexes = [rng.string for rng in text.tag_ranges(tag)] + for index_pair in zip(indexes[::2], indexes[1::2]): + text_tag_ranges.setdefault(tag, []).append(index_pair) + + self.assertEqual(text_tag_ranges, tag_ranges) + + with mock.patch.object(colorizer.ColorDelegator, 'notify_range'): + text.delete('1.0', 'end-1c') + + def test_def_statement(self): + # empty def + self._assert_highlighting('def', {'KEYWORD': [('1.0', '1.3')]}) + + # def followed by identifier + self._assert_highlighting('def foo:', {'KEYWORD': [('1.0', '1.3')], + 'DEFINITION': [('1.4', '1.7')]}) + + # def followed by partial identifier + self._assert_highlighting('def fo', {'KEYWORD': [('1.0', '1.3')], + 'DEFINITION': [('1.4', '1.6')]}) + + # def followed by non-keyword + self._assert_highlighting('def ++', {'KEYWORD': [('1.0', '1.3')]}) + + def test_match_soft_keyword(self): + # empty match + self._assert_highlighting('match', {'KEYWORD': [('1.0', '1.5')]}) + + # match followed by partial identifier + self._assert_highlighting('match fo', {'KEYWORD': [('1.0', '1.5')]}) + + # match followed by identifier and colon + self._assert_highlighting('match foo:', {'KEYWORD': [('1.0', '1.5')]}) + + # match followed by keyword + self._assert_highlighting('match and', {'KEYWORD': [('1.6', '1.9')]}) + + # match followed by builtin with keyword prefix + self._assert_highlighting('match int:', {'KEYWORD': [('1.0', '1.5')], + 'BUILTIN': [('1.6', '1.9')]}) + + # match followed by non-text operator + self._assert_highlighting('match^', {}) + self._assert_highlighting('match @', {}) + + # match followed by colon + self._assert_highlighting('match :', {}) + + # match followed by comma + self._assert_highlighting('match\t,', {}) + + # match followed by a lone underscore + self._assert_highlighting('match _:', {'KEYWORD': [('1.0', '1.5')]}) + + def test_case_soft_keyword(self): + # empty case + self._assert_highlighting('case', {'KEYWORD': [('1.0', '1.4')]}) + + # case followed by partial identifier + self._assert_highlighting('case fo', {'KEYWORD': [('1.0', '1.4')]}) + + # case followed by identifier and colon + self._assert_highlighting('case foo:', {'KEYWORD': [('1.0', '1.4')]}) + + # case followed by keyword + self._assert_highlighting('case and', {'KEYWORD': [('1.5', '1.8')]}) + + # case followed by builtin with keyword prefix + self._assert_highlighting('case int:', {'KEYWORD': [('1.0', '1.4')], + 'BUILTIN': [('1.5', '1.8')]}) + + # case followed by non-text operator + self._assert_highlighting('case^', {}) + self._assert_highlighting('case @', {}) + + # case followed by colon + self._assert_highlighting('case :', {}) + + # case followed by comma + self._assert_highlighting('case\t,', {}) + + # case followed by a lone underscore + self._assert_highlighting('case _:', {'KEYWORD': [('1.0', '1.4'), + ('1.5', '1.6')]}) + + def test_long_multiline_string(self): + source = textwrap.dedent('''\ + """a + b + c + d + e""" + ''') + self._assert_highlighting(source, {'STRING': [('1.0', '5.4')]}) + + @run_in_tk_mainloop(delay=50) + def test_incremental_editing(self): + text = self.text + eq = self.assertEqual + + # Simulate typing 'inte'. During this, the highlighting should + # change from normal to keyword to builtin to normal. + text.insert('insert', 'i') + yield + eq(text.tag_nextrange('BUILTIN', '1.0'), ()) + eq(text.tag_nextrange('KEYWORD', '1.0'), ()) + + text.insert('insert', 'n') + yield + eq(text.tag_nextrange('BUILTIN', '1.0'), ()) + eq(text.tag_nextrange('KEYWORD', '1.0'), ('1.0', '1.2')) + + text.insert('insert', 't') + yield + eq(text.tag_nextrange('BUILTIN', '1.0'), ('1.0', '1.3')) + eq(text.tag_nextrange('KEYWORD', '1.0'), ()) + + text.insert('insert', 'e') + yield + eq(text.tag_nextrange('BUILTIN', '1.0'), ()) + eq(text.tag_nextrange('KEYWORD', '1.0'), ()) + + # Simulate deleting three characters from the end of 'inte'. + # During this, the highlighting should change from normal to + # builtin to keyword to normal. + text.delete('insert-1c', 'insert') + yield + eq(text.tag_nextrange('BUILTIN', '1.0'), ('1.0', '1.3')) + eq(text.tag_nextrange('KEYWORD', '1.0'), ()) + + text.delete('insert-1c', 'insert') + yield + eq(text.tag_nextrange('BUILTIN', '1.0'), ()) + eq(text.tag_nextrange('KEYWORD', '1.0'), ('1.0', '1.2')) + + text.delete('insert-1c', 'insert') + yield + eq(text.tag_nextrange('BUILTIN', '1.0'), ()) + eq(text.tag_nextrange('KEYWORD', '1.0'), ()) + + @mock.patch.object(colorizer.ColorDelegator, 'recolorize') + @mock.patch.object(colorizer.ColorDelegator, 'notify_range') + def test_removecolors(self, mock_notify, mock_recolorize): + text = self.text + color = self.color + text.insert('insert', source) + + color.recolorize_main() + # recolorize_main doesn't add these tags. + text.tag_add("ERROR", "1.0") + text.tag_add("TODO", "1.0") + text.tag_add("hit", "1.0") + for tag in color.tagdefs: + with self.subTest(tag=tag): + self.assertNotEqual(text.tag_ranges(tag), ()) + + color.removecolors() + for tag in color.tagdefs: + with self.subTest(tag=tag): + self.assertEqual(text.tag_ranges(tag), ()) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_config.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_config.py new file mode 100644 index 0000000000000000000000000000000000000000..6d75cf7aa67dcce3b9bc49cc54cb4d5fd24cc103 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_config.py @@ -0,0 +1,805 @@ +"""Test config, coverage 93%. +(100% for IdleConfParser, IdleUserConfParser*, ConfigChanges). +* Exception is OSError clause in Save method. +Much of IdleConf is also exercised by ConfigDialog and test_configdialog. +""" +from idlelib import config +import sys +import os +import tempfile +from test.support import captured_stderr, findfile +import unittest +from unittest import mock +import idlelib +from idlelib.idle_test.mock_idle import Func + +# Tests should not depend on fortuitous user configurations. +# They must not affect actual user .cfg files. +# Replace user parsers with empty parsers that cannot be saved +# due to getting '' as the filename when created. + +idleConf = config.idleConf +usercfg = idleConf.userCfg +testcfg = {} +usermain = testcfg['main'] = config.IdleUserConfParser('') +userhigh = testcfg['highlight'] = config.IdleUserConfParser('') +userkeys = testcfg['keys'] = config.IdleUserConfParser('') +userextn = testcfg['extensions'] = config.IdleUserConfParser('') + +def setUpModule(): + idleConf.userCfg = testcfg + idlelib.testing = True + +def tearDownModule(): + idleConf.userCfg = usercfg + idlelib.testing = False + + +class IdleConfParserTest(unittest.TestCase): + """Test that IdleConfParser works""" + + config = """ + [one] + one = false + two = true + three = 10 + + [two] + one = a string + two = true + three = false + """ + + def test_get(self): + parser = config.IdleConfParser('') + parser.read_string(self.config) + eq = self.assertEqual + + # Test with type argument. + self.assertIs(parser.Get('one', 'one', type='bool'), False) + self.assertIs(parser.Get('one', 'two', type='bool'), True) + eq(parser.Get('one', 'three', type='int'), 10) + eq(parser.Get('two', 'one'), 'a string') + self.assertIs(parser.Get('two', 'two', type='bool'), True) + self.assertIs(parser.Get('two', 'three', type='bool'), False) + + # Test without type should fallback to string. + eq(parser.Get('two', 'two'), 'true') + eq(parser.Get('two', 'three'), 'false') + + # If option not exist, should return None, or default. + self.assertIsNone(parser.Get('not', 'exist')) + eq(parser.Get('not', 'exist', default='DEFAULT'), 'DEFAULT') + + def test_get_option_list(self): + parser = config.IdleConfParser('') + parser.read_string(self.config) + get_list = parser.GetOptionList + self.assertCountEqual(get_list('one'), ['one', 'two', 'three']) + self.assertCountEqual(get_list('two'), ['one', 'two', 'three']) + self.assertEqual(get_list('not exist'), []) + + def test_load_nothing(self): + parser = config.IdleConfParser('') + parser.Load() + self.assertEqual(parser.sections(), []) + + def test_load_file(self): + # Borrow test/configdata/cfgparser.1 from test_configparser. + config_path = findfile('cfgparser.1', subdir='configdata') + parser = config.IdleConfParser(config_path) + parser.Load() + + self.assertEqual(parser.Get('Foo Bar', 'foo'), 'newbar') + self.assertEqual(parser.GetOptionList('Foo Bar'), ['foo']) + + +class IdleUserConfParserTest(unittest.TestCase): + """Test that IdleUserConfParser works""" + + def new_parser(self, path=''): + return config.IdleUserConfParser(path) + + def test_set_option(self): + parser = self.new_parser() + parser.add_section('Foo') + # Setting new option in existing section should return True. + self.assertTrue(parser.SetOption('Foo', 'bar', 'true')) + # Setting existing option with same value should return False. + self.assertFalse(parser.SetOption('Foo', 'bar', 'true')) + # Setting exiting option with new value should return True. + self.assertTrue(parser.SetOption('Foo', 'bar', 'false')) + self.assertEqual(parser.Get('Foo', 'bar'), 'false') + + # Setting option in new section should create section and return True. + self.assertTrue(parser.SetOption('Bar', 'bar', 'true')) + self.assertCountEqual(parser.sections(), ['Bar', 'Foo']) + self.assertEqual(parser.Get('Bar', 'bar'), 'true') + + def test_remove_option(self): + parser = self.new_parser() + parser.AddSection('Foo') + parser.SetOption('Foo', 'bar', 'true') + + self.assertTrue(parser.RemoveOption('Foo', 'bar')) + self.assertFalse(parser.RemoveOption('Foo', 'bar')) + self.assertFalse(parser.RemoveOption('Not', 'Exist')) + + def test_add_section(self): + parser = self.new_parser() + self.assertEqual(parser.sections(), []) + + # Should not add duplicate section. + # Configparser raises DuplicateError, IdleParser not. + parser.AddSection('Foo') + parser.AddSection('Foo') + parser.AddSection('Bar') + self.assertCountEqual(parser.sections(), ['Bar', 'Foo']) + + def test_remove_empty_sections(self): + parser = self.new_parser() + + parser.AddSection('Foo') + parser.AddSection('Bar') + parser.SetOption('Idle', 'name', 'val') + self.assertCountEqual(parser.sections(), ['Bar', 'Foo', 'Idle']) + parser.RemoveEmptySections() + self.assertEqual(parser.sections(), ['Idle']) + + def test_is_empty(self): + parser = self.new_parser() + + parser.AddSection('Foo') + parser.AddSection('Bar') + self.assertTrue(parser.IsEmpty()) + self.assertEqual(parser.sections(), []) + + parser.SetOption('Foo', 'bar', 'false') + parser.AddSection('Bar') + self.assertFalse(parser.IsEmpty()) + self.assertCountEqual(parser.sections(), ['Foo']) + + def test_save(self): + with tempfile.TemporaryDirectory() as tdir: + path = os.path.join(tdir, 'test.cfg') + parser = self.new_parser(path) + parser.AddSection('Foo') + parser.SetOption('Foo', 'bar', 'true') + + # Should save to path when config is not empty. + self.assertFalse(os.path.exists(path)) + parser.Save() + self.assertTrue(os.path.exists(path)) + + # Should remove the file from disk when config is empty. + parser.remove_section('Foo') + parser.Save() + self.assertFalse(os.path.exists(path)) + + +class IdleConfTest(unittest.TestCase): + """Test for idleConf""" + + @classmethod + def setUpClass(cls): + cls.config_string = {} + + conf = config.IdleConf(_utest=True) + if __name__ != '__main__': + idle_dir = os.path.dirname(__file__) + else: + idle_dir = os.path.abspath(sys.path[0]) + for ctype in conf.config_types: + config_path = os.path.join(idle_dir, '../config-%s.def' % ctype) + with open(config_path) as f: + cls.config_string[ctype] = f.read() + + cls.orig_warn = config._warn + config._warn = Func() + + @classmethod + def tearDownClass(cls): + config._warn = cls.orig_warn + + def new_config(self, _utest=False): + return config.IdleConf(_utest=_utest) + + def mock_config(self): + """Return a mocked idleConf + + Both default and user config used the same config-*.def + """ + conf = config.IdleConf(_utest=True) + for ctype in conf.config_types: + conf.defaultCfg[ctype] = config.IdleConfParser('') + conf.defaultCfg[ctype].read_string(self.config_string[ctype]) + conf.userCfg[ctype] = config.IdleUserConfParser('') + conf.userCfg[ctype].read_string(self.config_string[ctype]) + + return conf + + @unittest.skipIf(sys.platform.startswith('win'), 'this is test for unix system') + def test_get_user_cfg_dir_unix(self): + # Test to get user config directory under unix. + conf = self.new_config(_utest=True) + + # Check normal way should success + with mock.patch('os.path.expanduser', return_value='/home/foo'): + with mock.patch('os.path.exists', return_value=True): + self.assertEqual(conf.GetUserCfgDir(), '/home/foo/.idlerc') + + # Check os.getcwd should success + with mock.patch('os.path.expanduser', return_value='~'): + with mock.patch('os.getcwd', return_value='/home/foo/cpython'): + with mock.patch('os.mkdir'): + self.assertEqual(conf.GetUserCfgDir(), + '/home/foo/cpython/.idlerc') + + # Check user dir not exists and created failed should raise SystemExit + with mock.patch('os.path.join', return_value='/path/not/exists'): + with self.assertRaises(SystemExit): + with self.assertRaises(FileNotFoundError): + conf.GetUserCfgDir() + + @unittest.skipIf(not sys.platform.startswith('win'), 'this is test for Windows system') + def test_get_user_cfg_dir_windows(self): + # Test to get user config directory under Windows. + conf = self.new_config(_utest=True) + + # Check normal way should success + with mock.patch('os.path.expanduser', return_value='C:\\foo'): + with mock.patch('os.path.exists', return_value=True): + self.assertEqual(conf.GetUserCfgDir(), 'C:\\foo\\.idlerc') + + # Check os.getcwd should success + with mock.patch('os.path.expanduser', return_value='~'): + with mock.patch('os.getcwd', return_value='C:\\foo\\cpython'): + with mock.patch('os.mkdir'): + self.assertEqual(conf.GetUserCfgDir(), + 'C:\\foo\\cpython\\.idlerc') + + # Check user dir not exists and created failed should raise SystemExit + with mock.patch('os.path.join', return_value='/path/not/exists'): + with self.assertRaises(SystemExit): + with self.assertRaises(FileNotFoundError): + conf.GetUserCfgDir() + + def test_create_config_handlers(self): + conf = self.new_config(_utest=True) + + # Mock out idle_dir + idle_dir = '/home/foo' + with mock.patch.dict({'__name__': '__foo__'}): + with mock.patch('os.path.dirname', return_value=idle_dir): + conf.CreateConfigHandlers() + + # Check keys are equal + self.assertCountEqual(conf.defaultCfg, conf.config_types) + self.assertCountEqual(conf.userCfg, conf.config_types) + + # Check conf parser are correct type + for default_parser in conf.defaultCfg.values(): + self.assertIsInstance(default_parser, config.IdleConfParser) + for user_parser in conf.userCfg.values(): + self.assertIsInstance(user_parser, config.IdleUserConfParser) + + # Check config path are correct + for cfg_type, parser in conf.defaultCfg.items(): + self.assertEqual(parser.file, + os.path.join(idle_dir, f'config-{cfg_type}.def')) + for cfg_type, parser in conf.userCfg.items(): + self.assertEqual(parser.file, + os.path.join(conf.userdir or '#', f'config-{cfg_type}.cfg')) + + def test_load_cfg_files(self): + conf = self.new_config(_utest=True) + + # Borrow test/configdata/cfgparser.1 from test_configparser. + config_path = findfile('cfgparser.1', subdir='configdata') + conf.defaultCfg['foo'] = config.IdleConfParser(config_path) + conf.userCfg['foo'] = config.IdleUserConfParser(config_path) + + # Load all config from path + conf.LoadCfgFiles() + + eq = self.assertEqual + + # Check defaultCfg is loaded + eq(conf.defaultCfg['foo'].Get('Foo Bar', 'foo'), 'newbar') + eq(conf.defaultCfg['foo'].GetOptionList('Foo Bar'), ['foo']) + + # Check userCfg is loaded + eq(conf.userCfg['foo'].Get('Foo Bar', 'foo'), 'newbar') + eq(conf.userCfg['foo'].GetOptionList('Foo Bar'), ['foo']) + + def test_save_user_cfg_files(self): + conf = self.mock_config() + + with mock.patch('idlelib.config.IdleUserConfParser.Save') as m: + conf.SaveUserCfgFiles() + self.assertEqual(m.call_count, len(conf.userCfg)) + + def test_get_option(self): + conf = self.mock_config() + + eq = self.assertEqual + eq(conf.GetOption('main', 'EditorWindow', 'width'), '80') + eq(conf.GetOption('main', 'EditorWindow', 'width', type='int'), 80) + with mock.patch('idlelib.config._warn') as _warn: + eq(conf.GetOption('main', 'EditorWindow', 'font', type='int'), None) + eq(conf.GetOption('main', 'EditorWindow', 'NotExists'), None) + eq(conf.GetOption('main', 'EditorWindow', 'NotExists', default='NE'), 'NE') + eq(_warn.call_count, 4) + + def test_set_option(self): + conf = self.mock_config() + + conf.SetOption('main', 'Foo', 'bar', 'newbar') + self.assertEqual(conf.GetOption('main', 'Foo', 'bar'), 'newbar') + + def test_get_section_list(self): + conf = self.mock_config() + + self.assertCountEqual( + conf.GetSectionList('default', 'main'), + ['General', 'EditorWindow', 'PyShell', 'Indent', 'Theme', + 'Keys', 'History', 'HelpFiles']) + self.assertCountEqual( + conf.GetSectionList('user', 'main'), + ['General', 'EditorWindow', 'PyShell', 'Indent', 'Theme', + 'Keys', 'History', 'HelpFiles']) + + with self.assertRaises(config.InvalidConfigSet): + conf.GetSectionList('foobar', 'main') + with self.assertRaises(config.InvalidConfigType): + conf.GetSectionList('default', 'notexists') + + def test_get_highlight(self): + conf = self.mock_config() + + eq = self.assertEqual + eq(conf.GetHighlight('IDLE Classic', 'normal'), {'foreground': '#000000', + 'background': '#ffffff'}) + + # Test cursor (this background should be normal-background) + eq(conf.GetHighlight('IDLE Classic', 'cursor'), {'foreground': 'black', + 'background': '#ffffff'}) + + # Test get user themes + conf.SetOption('highlight', 'Foobar', 'normal-foreground', '#747474') + conf.SetOption('highlight', 'Foobar', 'normal-background', '#171717') + with mock.patch('idlelib.config._warn'): + eq(conf.GetHighlight('Foobar', 'normal'), {'foreground': '#747474', + 'background': '#171717'}) + + def test_get_theme_dict(self): + # TODO: finish. + conf = self.mock_config() + + # These two should be the same + self.assertEqual( + conf.GetThemeDict('default', 'IDLE Classic'), + conf.GetThemeDict('user', 'IDLE Classic')) + + with self.assertRaises(config.InvalidTheme): + conf.GetThemeDict('bad', 'IDLE Classic') + + def test_get_current_theme_and_keys(self): + conf = self.mock_config() + + self.assertEqual(conf.CurrentTheme(), conf.current_colors_and_keys('Theme')) + self.assertEqual(conf.CurrentKeys(), conf.current_colors_and_keys('Keys')) + + def test_current_colors_and_keys(self): + conf = self.mock_config() + + self.assertEqual(conf.current_colors_and_keys('Theme'), 'IDLE Classic') + + def test_default_keys(self): + current_platform = sys.platform + conf = self.new_config(_utest=True) + + sys.platform = 'win32' + self.assertEqual(conf.default_keys(), 'IDLE Classic Windows') + + sys.platform = 'darwin' + self.assertEqual(conf.default_keys(), 'IDLE Classic OSX') + + sys.platform = 'some-linux' + self.assertEqual(conf.default_keys(), 'IDLE Modern Unix') + + # Restore platform + sys.platform = current_platform + + def test_get_extensions(self): + userextn.read_string(''' + [ZzDummy] + enable = True + [DISABLE] + enable = False + ''') + eq = self.assertEqual + iGE = idleConf.GetExtensions + eq(iGE(shell_only=True), []) + eq(iGE(), ['ZzDummy']) + eq(iGE(editor_only=True), ['ZzDummy']) + eq(iGE(active_only=False), ['ZzDummy', 'DISABLE']) + eq(iGE(active_only=False, editor_only=True), ['ZzDummy', 'DISABLE']) + userextn.remove_section('ZzDummy') + userextn.remove_section('DISABLE') + + + def test_remove_key_bind_names(self): + conf = self.mock_config() + + self.assertCountEqual( + conf.RemoveKeyBindNames(conf.GetSectionList('default', 'extensions')), + ['AutoComplete', 'CodeContext', 'FormatParagraph', 'ParenMatch', 'ZzDummy']) + + def test_get_extn_name_for_event(self): + userextn.read_string(''' + [ZzDummy] + enable = True + ''') + eq = self.assertEqual + eq(idleConf.GetExtnNameForEvent('z-in'), 'ZzDummy') + eq(idleConf.GetExtnNameForEvent('z-out'), None) + userextn.remove_section('ZzDummy') + + def test_get_extension_keys(self): + userextn.read_string(''' + [ZzDummy] + enable = True + ''') + self.assertEqual(idleConf.GetExtensionKeys('ZzDummy'), + {'<>': ['']}) + userextn.remove_section('ZzDummy') +# need option key test +## key = [''] if sys.platform == 'darwin' else [''] +## eq(conf.GetExtensionKeys('ZoomHeight'), {'<>': key}) + + def test_get_extension_bindings(self): + userextn.read_string(''' + [ZzDummy] + enable = True + ''') + eq = self.assertEqual + iGEB = idleConf.GetExtensionBindings + eq(iGEB('NotExists'), {}) + expect = {'<>': [''], + '<>': ['']} + eq(iGEB('ZzDummy'), expect) + userextn.remove_section('ZzDummy') + + def test_get_keybinding(self): + conf = self.mock_config() + + eq = self.assertEqual + eq(conf.GetKeyBinding('IDLE Modern Unix', '<>'), + ['', '']) + eq(conf.GetKeyBinding('IDLE Classic Unix', '<>'), + ['', '']) + eq(conf.GetKeyBinding('IDLE Classic Windows', '<>'), + ['', '']) + eq(conf.GetKeyBinding('IDLE Classic Mac', '<>'), ['']) + eq(conf.GetKeyBinding('IDLE Classic OSX', '<>'), ['']) + + # Test keybinding not exists + eq(conf.GetKeyBinding('NOT EXISTS', '<>'), []) + eq(conf.GetKeyBinding('IDLE Modern Unix', 'NOT EXISTS'), []) + + def test_get_current_keyset(self): + current_platform = sys.platform + conf = self.mock_config() + + # Ensure that platform isn't darwin + sys.platform = 'some-linux' + self.assertEqual(conf.GetCurrentKeySet(), conf.GetKeySet(conf.CurrentKeys())) + + # This should not be the same, since replace ') + self.assertEqual(conf.GetKeySet('IDLE Modern Unix')['<>'], '') + + def test_is_core_binding(self): + # XXX: Should move out the core keys to config file or other place + conf = self.mock_config() + + self.assertTrue(conf.IsCoreBinding('copy')) + self.assertTrue(conf.IsCoreBinding('cut')) + self.assertTrue(conf.IsCoreBinding('del-word-right')) + self.assertFalse(conf.IsCoreBinding('not-exists')) + + def test_extra_help_source_list(self): + # Test GetExtraHelpSourceList and GetAllExtraHelpSourcesList in same + # place to prevent prepare input data twice. + conf = self.mock_config() + + # Test default with no extra help source + self.assertEqual(conf.GetExtraHelpSourceList('default'), []) + self.assertEqual(conf.GetExtraHelpSourceList('user'), []) + with self.assertRaises(config.InvalidConfigSet): + self.assertEqual(conf.GetExtraHelpSourceList('bad'), []) + self.assertCountEqual( + conf.GetAllExtraHelpSourcesList(), + conf.GetExtraHelpSourceList('default') + conf.GetExtraHelpSourceList('user')) + + # Add help source to user config + conf.userCfg['main'].SetOption('HelpFiles', '4', 'Python;https://python.org') # This is bad input + conf.userCfg['main'].SetOption('HelpFiles', '3', 'Python:https://python.org') # This is bad input + conf.userCfg['main'].SetOption('HelpFiles', '2', 'Pillow;https://pillow.readthedocs.io/en/latest/') + conf.userCfg['main'].SetOption('HelpFiles', '1', 'IDLE;C:/Programs/Python36/Lib/idlelib/help.html') + self.assertEqual(conf.GetExtraHelpSourceList('user'), + [('IDLE', 'C:/Programs/Python36/Lib/idlelib/help.html', '1'), + ('Pillow', 'https://pillow.readthedocs.io/en/latest/', '2'), + ('Python', 'https://python.org', '4')]) + self.assertCountEqual( + conf.GetAllExtraHelpSourcesList(), + conf.GetExtraHelpSourceList('default') + conf.GetExtraHelpSourceList('user')) + + def test_get_font(self): + from test.support import requires + from tkinter import Tk + from tkinter.font import Font + conf = self.mock_config() + + requires('gui') + root = Tk() + root.withdraw() + + f = Font.actual(Font(name='TkFixedFont', exists=True, root=root)) + self.assertEqual( + conf.GetFont(root, 'main', 'EditorWindow'), + (f['family'], 10 if f['size'] <= 0 else f['size'], f['weight'])) + + # Cleanup root + root.destroy() + del root + + def test_get_core_keys(self): + conf = self.mock_config() + + eq = self.assertEqual + eq(conf.GetCoreKeys()['<>'], ['']) + eq(conf.GetCoreKeys()['<>'], ['', '']) + eq(conf.GetCoreKeys()['<>'], ['']) + eq(conf.GetCoreKeys('IDLE Classic Windows')['<>'], + ['', '']) + eq(conf.GetCoreKeys('IDLE Classic OSX')['<>'], ['']) + eq(conf.GetCoreKeys('IDLE Classic Unix')['<>'], + ['', '']) + eq(conf.GetCoreKeys('IDLE Modern Unix')['<>'], + ['', '']) + + +class CurrentColorKeysTest(unittest.TestCase): + """ Test colorkeys function with user config [Theme] and [Keys] patterns. + + colorkeys = config.IdleConf.current_colors_and_keys + Test all patterns written by IDLE and some errors + Item 'default' should really be 'builtin' (versus 'custom). + """ + colorkeys = idleConf.current_colors_and_keys + default_theme = 'IDLE Classic' + default_keys = idleConf.default_keys() + + def test_old_builtin_theme(self): + # On initial installation, user main is blank. + self.assertEqual(self.colorkeys('Theme'), self.default_theme) + # For old default, name2 must be blank. + usermain.read_string(''' + [Theme] + default = True + ''') + # IDLE omits 'name' for default old builtin theme. + self.assertEqual(self.colorkeys('Theme'), self.default_theme) + # IDLE adds 'name' for non-default old builtin theme. + usermain['Theme']['name'] = 'IDLE New' + self.assertEqual(self.colorkeys('Theme'), 'IDLE New') + # Erroneous non-default old builtin reverts to default. + usermain['Theme']['name'] = 'non-existent' + self.assertEqual(self.colorkeys('Theme'), self.default_theme) + usermain.remove_section('Theme') + + def test_new_builtin_theme(self): + # IDLE writes name2 for new builtins. + usermain.read_string(''' + [Theme] + default = True + name2 = IDLE Dark + ''') + self.assertEqual(self.colorkeys('Theme'), 'IDLE Dark') + # Leftover 'name', not removed, is ignored. + usermain['Theme']['name'] = 'IDLE New' + self.assertEqual(self.colorkeys('Theme'), 'IDLE Dark') + # Erroneous non-default new builtin reverts to default. + usermain['Theme']['name2'] = 'non-existent' + self.assertEqual(self.colorkeys('Theme'), self.default_theme) + usermain.remove_section('Theme') + + def test_user_override_theme(self): + # Erroneous custom name (no definition) reverts to default. + usermain.read_string(''' + [Theme] + default = False + name = Custom Dark + ''') + self.assertEqual(self.colorkeys('Theme'), self.default_theme) + # Custom name is valid with matching Section name. + userhigh.read_string('[Custom Dark]\na=b') + self.assertEqual(self.colorkeys('Theme'), 'Custom Dark') + # Name2 is ignored. + usermain['Theme']['name2'] = 'non-existent' + self.assertEqual(self.colorkeys('Theme'), 'Custom Dark') + usermain.remove_section('Theme') + userhigh.remove_section('Custom Dark') + + def test_old_builtin_keys(self): + # On initial installation, user main is blank. + self.assertEqual(self.colorkeys('Keys'), self.default_keys) + # For old default, name2 must be blank, name is always used. + usermain.read_string(''' + [Keys] + default = True + name = IDLE Classic Unix + ''') + self.assertEqual(self.colorkeys('Keys'), 'IDLE Classic Unix') + # Erroneous non-default old builtin reverts to default. + usermain['Keys']['name'] = 'non-existent' + self.assertEqual(self.colorkeys('Keys'), self.default_keys) + usermain.remove_section('Keys') + + def test_new_builtin_keys(self): + # IDLE writes name2 for new builtins. + usermain.read_string(''' + [Keys] + default = True + name2 = IDLE Modern Unix + ''') + self.assertEqual(self.colorkeys('Keys'), 'IDLE Modern Unix') + # Leftover 'name', not removed, is ignored. + usermain['Keys']['name'] = 'IDLE Classic Unix' + self.assertEqual(self.colorkeys('Keys'), 'IDLE Modern Unix') + # Erroneous non-default new builtin reverts to default. + usermain['Keys']['name2'] = 'non-existent' + self.assertEqual(self.colorkeys('Keys'), self.default_keys) + usermain.remove_section('Keys') + + def test_user_override_keys(self): + # Erroneous custom name (no definition) reverts to default. + usermain.read_string(''' + [Keys] + default = False + name = Custom Keys + ''') + self.assertEqual(self.colorkeys('Keys'), self.default_keys) + # Custom name is valid with matching Section name. + userkeys.read_string('[Custom Keys]\na=b') + self.assertEqual(self.colorkeys('Keys'), 'Custom Keys') + # Name2 is ignored. + usermain['Keys']['name2'] = 'non-existent' + self.assertEqual(self.colorkeys('Keys'), 'Custom Keys') + usermain.remove_section('Keys') + userkeys.remove_section('Custom Keys') + + +class ChangesTest(unittest.TestCase): + + empty = {'main':{}, 'highlight':{}, 'keys':{}, 'extensions':{}} + + def load(self): # Test_add_option verifies that this works. + changes = self.changes + changes.add_option('main', 'Msec', 'mitem', 'mval') + changes.add_option('highlight', 'Hsec', 'hitem', 'hval') + changes.add_option('keys', 'Ksec', 'kitem', 'kval') + return changes + + loaded = {'main': {'Msec': {'mitem': 'mval'}}, + 'highlight': {'Hsec': {'hitem': 'hval'}}, + 'keys': {'Ksec': {'kitem':'kval'}}, + 'extensions': {}} + + def setUp(self): + self.changes = config.ConfigChanges() + + def test_init(self): + self.assertEqual(self.changes, self.empty) + + def test_add_option(self): + changes = self.load() + self.assertEqual(changes, self.loaded) + changes.add_option('main', 'Msec', 'mitem', 'mval') + self.assertEqual(changes, self.loaded) + + def test_save_option(self): # Static function does not touch changes. + save_option = self.changes.save_option + self.assertTrue(save_option('main', 'Indent', 'what', '0')) + self.assertFalse(save_option('main', 'Indent', 'what', '0')) + self.assertEqual(usermain['Indent']['what'], '0') + + self.assertTrue(save_option('main', 'Indent', 'use-spaces', '0')) + self.assertEqual(usermain['Indent']['use-spaces'], '0') + self.assertTrue(save_option('main', 'Indent', 'use-spaces', '1')) + self.assertFalse(usermain.has_option('Indent', 'use-spaces')) + usermain.remove_section('Indent') + + def test_save_added(self): + changes = self.load() + self.assertTrue(changes.save_all()) + self.assertEqual(usermain['Msec']['mitem'], 'mval') + self.assertEqual(userhigh['Hsec']['hitem'], 'hval') + self.assertEqual(userkeys['Ksec']['kitem'], 'kval') + changes.add_option('main', 'Msec', 'mitem', 'mval') + self.assertFalse(changes.save_all()) + usermain.remove_section('Msec') + userhigh.remove_section('Hsec') + userkeys.remove_section('Ksec') + + def test_save_help(self): + # Any change to HelpFiles overwrites entire section. + changes = self.changes + changes.save_option('main', 'HelpFiles', 'IDLE', 'idledoc') + changes.add_option('main', 'HelpFiles', 'ELDI', 'codeldi') + changes.save_all() + self.assertFalse(usermain.has_option('HelpFiles', 'IDLE')) + self.assertTrue(usermain.has_option('HelpFiles', 'ELDI')) + + def test_save_default(self): # Cover 2nd and 3rd false branches. + changes = self.changes + changes.add_option('main', 'Indent', 'use-spaces', '1') + # save_option returns False; cfg_type_changed remains False. + + # TODO: test that save_all calls usercfg Saves. + + def test_delete_section(self): + changes = self.load() + changes.delete_section('main', 'fake') # Test no exception. + self.assertEqual(changes, self.loaded) # Test nothing deleted. + for cfgtype, section in (('main', 'Msec'), ('keys', 'Ksec')): + testcfg[cfgtype].SetOption(section, 'name', 'value') + changes.delete_section(cfgtype, section) + with self.assertRaises(KeyError): + changes[cfgtype][section] # Test section gone from changes + testcfg[cfgtype][section] # and from mock userCfg. + # TODO test for save call. + + def test_clear(self): + changes = self.load() + changes.clear() + self.assertEqual(changes, self.empty) + + +class WarningTest(unittest.TestCase): + + def test_warn(self): + Equal = self.assertEqual + config._warned = set() + with captured_stderr() as stderr: + config._warn('warning', 'key') + Equal(config._warned, {('warning','key')}) + Equal(stderr.getvalue(), 'warning'+'\n') + with captured_stderr() as stderr: + config._warn('warning', 'key') + Equal(stderr.getvalue(), '') + with captured_stderr() as stderr: + config._warn('warn2', 'yek') + Equal(config._warned, {('warning','key'), ('warn2','yek')}) + Equal(stderr.getvalue(), 'warn2'+'\n') + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_config_key.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_config_key.py new file mode 100644 index 0000000000000000000000000000000000000000..32f878b842b276dc892c0606503d4fb8abde2180 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_config_key.py @@ -0,0 +1,356 @@ +"""Test config_key, coverage 98%. + +Coverage is effectively 100%. Tkinter dialog is mocked, Mac-only line +may be skipped, and dummy function in bind test should not be called. +Not tested: exit with 'self.advanced or self.keys_ok(keys) ...' False. +""" + +from idlelib import config_key +from test.support import requires +import unittest +from unittest import mock +from tkinter import Tk, TclError +from idlelib.idle_test.mock_idle import Func +from idlelib.idle_test.mock_tk import Mbox_func + + +class ValidationTest(unittest.TestCase): + "Test validation methods: ok, keys_ok, bind_ok." + + class Validator(config_key.GetKeysFrame): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + class list_keys_final: + get = Func() + self.list_keys_final = list_keys_final + get_modifiers = Func() + showerror = Mbox_func() + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + keylist = [[''], ['', '']] + cls.dialog = cls.Validator(cls.root, '<>', keylist) + + @classmethod + def tearDownClass(cls): + del cls.dialog + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def setUp(self): + self.dialog.showerror.message = '' + # A test that needs a particular final key value should set it. + # A test that sets a non-blank modifier list should reset it to []. + + def test_ok_empty(self): + self.dialog.key_string.set(' ') + self.dialog.ok() + self.assertEqual(self.dialog.result, '') + self.assertEqual(self.dialog.showerror.message, 'No key specified.') + + def test_ok_good(self): + self.dialog.key_string.set('') + self.dialog.list_keys_final.get.result = 'F11' + self.dialog.ok() + self.assertEqual(self.dialog.result, '') + self.assertEqual(self.dialog.showerror.message, '') + + def test_keys_no_ending(self): + self.assertFalse(self.dialog.keys_ok('')) + self.assertIn('No modifier', self.dialog.showerror.message) + + def test_keys_no_modifier_ok(self): + self.dialog.list_keys_final.get.result = 'F11' + self.assertTrue(self.dialog.keys_ok('')) + self.assertEqual(self.dialog.showerror.message, '') + + def test_keys_shift_bad(self): + self.dialog.list_keys_final.get.result = 'a' + self.dialog.get_modifiers.result = ['Shift'] + self.assertFalse(self.dialog.keys_ok('')) + self.assertIn('shift modifier', self.dialog.showerror.message) + self.dialog.get_modifiers.result = [] + + def test_keys_dup(self): + for mods, final, seq in (([], 'F12', ''), + (['Control'], 'x', ''), + (['Control'], 'X', '')): + with self.subTest(m=mods, f=final, s=seq): + self.dialog.list_keys_final.get.result = final + self.dialog.get_modifiers.result = mods + self.assertFalse(self.dialog.keys_ok(seq)) + self.assertIn('already in use', self.dialog.showerror.message) + self.dialog.get_modifiers.result = [] + + def test_bind_ok(self): + self.assertTrue(self.dialog.bind_ok('')) + self.assertEqual(self.dialog.showerror.message, '') + + def test_bind_not_ok(self): + self.assertFalse(self.dialog.bind_ok('')) + self.assertIn('not accepted', self.dialog.showerror.message) + + +class ToggleLevelTest(unittest.TestCase): + "Test toggle between Basic and Advanced frames." + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.dialog = config_key.GetKeysFrame(cls.root, '<>', []) + + @classmethod + def tearDownClass(cls): + del cls.dialog + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def test_toggle_level(self): + dialog = self.dialog + + def stackorder(): + """Get the stack order of the children of the frame. + + winfo_children() stores the children in stack order, so + this can be used to check whether a frame is above or + below another one. + """ + for index, child in enumerate(dialog.winfo_children()): + if child._name == 'keyseq_basic': + basic = index + if child._name == 'keyseq_advanced': + advanced = index + return basic, advanced + + # New window starts at basic level. + self.assertFalse(dialog.advanced) + self.assertIn('Advanced', dialog.button_level['text']) + basic, advanced = stackorder() + self.assertGreater(basic, advanced) + + # Toggle to advanced. + dialog.toggle_level() + self.assertTrue(dialog.advanced) + self.assertIn('Basic', dialog.button_level['text']) + basic, advanced = stackorder() + self.assertGreater(advanced, basic) + + # Toggle to basic. + dialog.button_level.invoke() + self.assertFalse(dialog.advanced) + self.assertIn('Advanced', dialog.button_level['text']) + basic, advanced = stackorder() + self.assertGreater(basic, advanced) + + +class KeySelectionTest(unittest.TestCase): + "Test selecting key on Basic frames." + + class Basic(config_key.GetKeysFrame): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + class list_keys_final: + get = Func() + select_clear = Func() + yview = Func() + self.list_keys_final = list_keys_final + def set_modifiers_for_platform(self): + self.modifiers = ['foo', 'bar', 'BAZ'] + self.modifier_label = {'BAZ': 'ZZZ'} + showerror = Mbox_func() + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.dialog = cls.Basic(cls.root, '<>', []) + + @classmethod + def tearDownClass(cls): + del cls.dialog + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def setUp(self): + self.dialog.clear_key_seq() + + def test_get_modifiers(self): + dialog = self.dialog + gm = dialog.get_modifiers + eq = self.assertEqual + + # Modifiers are set on/off by invoking the checkbutton. + dialog.modifier_checkbuttons['foo'].invoke() + eq(gm(), ['foo']) + + dialog.modifier_checkbuttons['BAZ'].invoke() + eq(gm(), ['foo', 'BAZ']) + + dialog.modifier_checkbuttons['foo'].invoke() + eq(gm(), ['BAZ']) + + @mock.patch.object(config_key.GetKeysFrame, 'get_modifiers') + def test_build_key_string(self, mock_modifiers): + dialog = self.dialog + key = dialog.list_keys_final + string = dialog.key_string.get + eq = self.assertEqual + + key.get.result = 'a' + mock_modifiers.return_value = [] + dialog.build_key_string() + eq(string(), '') + + mock_modifiers.return_value = ['mymod'] + dialog.build_key_string() + eq(string(), '') + + key.get.result = '' + mock_modifiers.return_value = ['mymod', 'test'] + dialog.build_key_string() + eq(string(), '') + + @mock.patch.object(config_key.GetKeysFrame, 'get_modifiers') + def test_final_key_selected(self, mock_modifiers): + dialog = self.dialog + key = dialog.list_keys_final + string = dialog.key_string.get + eq = self.assertEqual + + mock_modifiers.return_value = ['Shift'] + key.get.result = '{' + dialog.final_key_selected() + eq(string(), '') + + +class CancelWindowTest(unittest.TestCase): + "Simulate user clicking [Cancel] button." + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.dialog = config_key.GetKeysWindow( + cls.root, 'Title', '<>', [], _utest=True) + + @classmethod + def tearDownClass(cls): + cls.dialog.cancel() + del cls.dialog + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + @mock.patch.object(config_key.GetKeysFrame, 'ok') + def test_cancel(self, mock_frame_ok): + self.assertEqual(self.dialog.winfo_class(), 'Toplevel') + self.dialog.button_cancel.invoke() + with self.assertRaises(TclError): + self.dialog.winfo_class() + self.assertEqual(self.dialog.result, '') + mock_frame_ok.assert_not_called() + + +class OKWindowTest(unittest.TestCase): + "Simulate user clicking [OK] button." + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.dialog = config_key.GetKeysWindow( + cls.root, 'Title', '<>', [], _utest=True) + + @classmethod + def tearDownClass(cls): + cls.dialog.cancel() + del cls.dialog + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + @mock.patch.object(config_key.GetKeysFrame, 'ok') + def test_ok(self, mock_frame_ok): + self.assertEqual(self.dialog.winfo_class(), 'Toplevel') + self.dialog.button_ok.invoke() + with self.assertRaises(TclError): + self.dialog.winfo_class() + mock_frame_ok.assert_called() + + +class WindowResultTest(unittest.TestCase): + "Test window result get and set." + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.dialog = config_key.GetKeysWindow( + cls.root, 'Title', '<>', [], _utest=True) + + @classmethod + def tearDownClass(cls): + cls.dialog.cancel() + del cls.dialog + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def test_result(self): + dialog = self.dialog + eq = self.assertEqual + + dialog.result = '' + eq(dialog.result, '') + eq(dialog.frame.result,'') + + dialog.result = 'bar' + eq(dialog.result,'bar') + eq(dialog.frame.result,'bar') + + dialog.frame.result = 'foo' + eq(dialog.result, 'foo') + eq(dialog.frame.result,'foo') + + +class HelperTest(unittest.TestCase): + "Test module level helper functions." + + def test_translate_key(self): + tr = config_key.translate_key + eq = self.assertEqual + + # Letters return unchanged with no 'Shift'. + eq(tr('q', []), 'Key-q') + eq(tr('q', ['Control', 'Alt']), 'Key-q') + + # 'Shift' uppercases single lowercase letters. + eq(tr('q', ['Shift']), 'Key-Q') + eq(tr('q', ['Control', 'Shift']), 'Key-Q') + eq(tr('q', ['Control', 'Alt', 'Shift']), 'Key-Q') + + # Convert key name to keysym. + eq(tr('Page Up', []), 'Key-Prior') + # 'Shift' doesn't change case when it's not a single char. + eq(tr('*', ['Shift']), 'Key-asterisk') + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_configdialog.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_configdialog.py new file mode 100644 index 0000000000000000000000000000000000000000..0daca89084b04864e304d9aeacdbb2ff953d8650 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_configdialog.py @@ -0,0 +1,1581 @@ +"""Test configdialog, coverage 94%. + +Half the class creates dialog, half works with user customizations. +""" +from idlelib import configdialog +from test.support import requires +requires('gui') +from test.support.testcase import ExtraAssertions +import unittest +from unittest import mock +from idlelib.idle_test.mock_idle import Func +from tkinter import (Tk, StringVar, IntVar, BooleanVar, DISABLED, NORMAL) +from idlelib import config +from idlelib.configdialog import idleConf, changes, tracers + +# Tests should not depend on fortuitous user configurations. +# They must not affect actual user .cfg files. +# Use solution from test_config: empty parsers with no filename. +usercfg = idleConf.userCfg +testcfg = { + 'main': config.IdleUserConfParser(''), + 'highlight': config.IdleUserConfParser(''), + 'keys': config.IdleUserConfParser(''), + 'extensions': config.IdleUserConfParser(''), +} + +root = None +dialog = None +mainpage = changes['main'] +highpage = changes['highlight'] +keyspage = changes['keys'] +extpage = changes['extensions'] + + +def setUpModule(): + global root, dialog + idleConf.userCfg = testcfg + root = Tk() + # root.withdraw() # Comment out, see issue 30870 + dialog = configdialog.ConfigDialog(root, 'Test', _utest=True) + + +def tearDownModule(): + global root, dialog + idleConf.userCfg = usercfg + tracers.detach() + tracers.clear() + changes.clear() + root.update_idletasks() + root.destroy() + root = dialog = None + + +class ConfigDialogTest(unittest.TestCase): + + def test_deactivate_current_config(self): + pass + + def activate_config_changes(self): + pass + + +class ButtonTest(unittest.TestCase, ExtraAssertions): + + def test_click_ok(self): + d = dialog + apply = d.apply = mock.Mock() + destroy = d.destroy = mock.Mock() + d.buttons['Ok'].invoke() + apply.assert_called_once() + destroy.assert_called_once() + del d.destroy, d.apply + + def test_click_apply(self): + d = dialog + deactivate = d.deactivate_current_config = mock.Mock() + save_ext = d.extpage.save_all_changed_extensions = mock.Mock() + activate = d.activate_config_changes = mock.Mock() + d.buttons['Apply'].invoke() + deactivate.assert_called_once() + save_ext.assert_called_once() + activate.assert_called_once() + del d.extpage.save_all_changed_extensions + del d.activate_config_changes, d.deactivate_current_config + + def test_click_cancel(self): + d = dialog + d.destroy = Func() + changes['main']['something'] = 1 + d.buttons['Cancel'].invoke() + self.assertEqual(changes['main'], {}) + self.assertEqual(d.destroy.called, 1) + del d.destroy + + def test_click_help(self): + dialog.note.select(dialog.keyspage) + with mock.patch.object(configdialog, 'view_text', + new_callable=Func) as view: + dialog.buttons['Help'].invoke() + title, contents = view.kwds['title'], view.kwds['contents'] + self.assertEqual(title, 'Help for IDLE preferences') + self.assertStartsWith(contents, 'When you click') + self.assertEndsWith(contents,'a different name.\n') + + +class FontPageTest(unittest.TestCase): + """Test that font widgets enable users to make font changes. + + Test that widget actions set vars, that var changes add three + options to changes and call set_samples, and that set_samples + changes the font of both sample boxes. + """ + @classmethod + def setUpClass(cls): + page = cls.page = dialog.fontpage + dialog.note.select(page) + page.set_samples = Func() # Mask instance method. + page.update() + + @classmethod + def tearDownClass(cls): + del cls.page.set_samples # Unmask instance method. + + def setUp(self): + changes.clear() + + def test_load_font_cfg(self): + # Leave widget load test to human visual check. + # TODO Improve checks when add IdleConf.get_font_values. + tracers.detach() + d = self.page + d.font_name.set('Fake') + d.font_size.set('1') + d.font_bold.set(True) + d.set_samples.called = 0 + d.load_font_cfg() + self.assertNotEqual(d.font_name.get(), 'Fake') + self.assertNotEqual(d.font_size.get(), '1') + self.assertFalse(d.font_bold.get()) + self.assertEqual(d.set_samples.called, 1) + tracers.attach() + + def test_fontlist_key(self): + # Up and Down keys should select a new font. + d = self.page + if d.fontlist.size() < 2: + self.skipTest('need at least 2 fonts') + fontlist = d.fontlist + fontlist.activate(0) + font = d.fontlist.get('active') + + # Test Down key. + fontlist.focus_force() + fontlist.update() + fontlist.event_generate('') + fontlist.event_generate('') + + down_font = fontlist.get('active') + self.assertNotEqual(down_font, font) + self.assertIn(d.font_name.get(), down_font.lower()) + + # Test Up key. + fontlist.focus_force() + fontlist.update() + fontlist.event_generate('') + fontlist.event_generate('') + + up_font = fontlist.get('active') + self.assertEqual(up_font, font) + self.assertIn(d.font_name.get(), up_font.lower()) + + def test_fontlist_mouse(self): + # Click on item should select that item. + d = self.page + if d.fontlist.size() < 2: + self.skipTest('need at least 2 fonts') + fontlist = d.fontlist + fontlist.activate(0) + + # Select next item in listbox + fontlist.focus_force() + fontlist.see(1) + fontlist.update() + x, y, dx, dy = fontlist.bbox(1) + x += dx // 2 + y += dy // 2 + fontlist.event_generate('', x=x, y=y) + fontlist.event_generate('', x=x, y=y) + + font1 = fontlist.get(1) + select_font = fontlist.get('anchor') + self.assertEqual(select_font, font1) + self.assertIn(d.font_name.get(), font1.lower()) + + def test_sizelist(self): + # Click on number should select that number + d = self.page + d.sizelist.variable.set(40) + self.assertEqual(d.font_size.get(), '40') + + def test_bold_toggle(self): + # Click on checkbutton should invert it. + d = self.page + d.font_bold.set(False) + d.bold_toggle.invoke() + self.assertTrue(d.font_bold.get()) + d.bold_toggle.invoke() + self.assertFalse(d.font_bold.get()) + + def test_font_set(self): + # Test that setting a font Variable results in 3 provisional + # change entries and a call to set_samples. Use values sure to + # not be defaults. + + default_font = idleConf.GetFont(root, 'main', 'EditorWindow') + default_size = str(default_font[1]) + default_bold = default_font[2] == 'bold' + d = self.page + d.font_size.set(default_size) + d.font_bold.set(default_bold) + d.set_samples.called = 0 + + d.font_name.set('Test Font') + expected = {'EditorWindow': {'font': 'Test Font', + 'font-size': default_size, + 'font-bold': str(default_bold)}} + self.assertEqual(mainpage, expected) + self.assertEqual(d.set_samples.called, 1) + changes.clear() + + d.font_size.set('20') + expected = {'EditorWindow': {'font': 'Test Font', + 'font-size': '20', + 'font-bold': str(default_bold)}} + self.assertEqual(mainpage, expected) + self.assertEqual(d.set_samples.called, 2) + changes.clear() + + d.font_bold.set(not default_bold) + expected = {'EditorWindow': {'font': 'Test Font', + 'font-size': '20', + 'font-bold': str(not default_bold)}} + self.assertEqual(mainpage, expected) + self.assertEqual(d.set_samples.called, 3) + + def test_set_samples(self): + d = self.page + del d.set_samples # Unmask method for test + orig_samples = d.font_sample, d.highlight_sample + d.font_sample, d.highlight_sample = {}, {} + d.font_name.set('test') + d.font_size.set('5') + d.font_bold.set(1) + expected = {'font': ('test', '5', 'bold')} + + # Test set_samples. + d.set_samples() + self.assertTrue(d.font_sample == d.highlight_sample == expected) + + d.font_sample, d.highlight_sample = orig_samples + d.set_samples = Func() # Re-mask for other tests. + + +class HighPageTest(unittest.TestCase): + """Test that highlight tab widgets enable users to make changes. + + Test that widget actions set vars, that var changes add + options to changes and that themes work correctly. + """ + + @classmethod + def setUpClass(cls): + page = cls.page = dialog.highpage + dialog.note.select(page) + page.set_theme_type = Func() + page.paint_theme_sample = Func() + page.set_highlight_target = Func() + page.set_color_sample = Func() + page.update() + + @classmethod + def tearDownClass(cls): + d = cls.page + del d.set_theme_type, d.paint_theme_sample + del d.set_highlight_target, d.set_color_sample + + def setUp(self): + d = self.page + # The following is needed for test_load_key_cfg, _delete_custom_keys. + # This may indicate a defect in some test or function. + for section in idleConf.GetSectionList('user', 'highlight'): + idleConf.userCfg['highlight'].remove_section(section) + changes.clear() + d.set_theme_type.called = 0 + d.paint_theme_sample.called = 0 + d.set_highlight_target.called = 0 + d.set_color_sample.called = 0 + + def test_load_theme_cfg(self): + tracers.detach() + d = self.page + eq = self.assertEqual + + # Use builtin theme with no user themes created. + idleConf.CurrentTheme = mock.Mock(return_value='IDLE Classic') + d.load_theme_cfg() + self.assertTrue(d.theme_source.get()) + # builtinlist sets variable builtin_name to the CurrentTheme default. + eq(d.builtin_name.get(), 'IDLE Classic') + eq(d.custom_name.get(), '- no custom themes -') + eq(d.custom_theme_on.state(), ('disabled',)) + eq(d.set_theme_type.called, 1) + eq(d.paint_theme_sample.called, 1) + eq(d.set_highlight_target.called, 1) + + # Builtin theme with non-empty user theme list. + idleConf.SetOption('highlight', 'test1', 'option', 'value') + idleConf.SetOption('highlight', 'test2', 'option2', 'value2') + d.load_theme_cfg() + eq(d.builtin_name.get(), 'IDLE Classic') + eq(d.custom_name.get(), 'test1') + eq(d.set_theme_type.called, 2) + eq(d.paint_theme_sample.called, 2) + eq(d.set_highlight_target.called, 2) + + # Use custom theme. + idleConf.CurrentTheme = mock.Mock(return_value='test2') + idleConf.SetOption('main', 'Theme', 'default', '0') + d.load_theme_cfg() + self.assertFalse(d.theme_source.get()) + eq(d.builtin_name.get(), 'IDLE Classic') + eq(d.custom_name.get(), 'test2') + eq(d.set_theme_type.called, 3) + eq(d.paint_theme_sample.called, 3) + eq(d.set_highlight_target.called, 3) + + del idleConf.CurrentTheme + tracers.attach() + + def test_theme_source(self): + eq = self.assertEqual + d = self.page + # Test these separately. + d.var_changed_builtin_name = Func() + d.var_changed_custom_name = Func() + # Builtin selected. + d.builtin_theme_on.invoke() + eq(mainpage, {'Theme': {'default': 'True'}}) + eq(d.var_changed_builtin_name.called, 1) + eq(d.var_changed_custom_name.called, 0) + changes.clear() + + # Custom selected. + d.custom_theme_on.state(('!disabled',)) + d.custom_theme_on.invoke() + self.assertEqual(mainpage, {'Theme': {'default': 'False'}}) + eq(d.var_changed_builtin_name.called, 1) + eq(d.var_changed_custom_name.called, 1) + del d.var_changed_builtin_name, d.var_changed_custom_name + + def test_builtin_name(self): + eq = self.assertEqual + d = self.page + item_list = ['IDLE Classic', 'IDLE Dark', 'IDLE New'] + + # Not in old_themes, defaults name to first item. + idleConf.SetOption('main', 'Theme', 'name', 'spam') + d.builtinlist.SetMenu(item_list, 'IDLE Dark') + eq(mainpage, {'Theme': {'name': 'IDLE Classic', + 'name2': 'IDLE Dark'}}) + eq(d.theme_message['text'], 'New theme, see Help') + eq(d.paint_theme_sample.called, 1) + + # Not in old themes - uses name2. + changes.clear() + idleConf.SetOption('main', 'Theme', 'name', 'IDLE New') + d.builtinlist.SetMenu(item_list, 'IDLE Dark') + eq(mainpage, {'Theme': {'name2': 'IDLE Dark'}}) + eq(d.theme_message['text'], 'New theme, see Help') + eq(d.paint_theme_sample.called, 2) + + # Builtin name in old_themes. + changes.clear() + d.builtinlist.SetMenu(item_list, 'IDLE Classic') + eq(mainpage, {'Theme': {'name': 'IDLE Classic', 'name2': ''}}) + eq(d.theme_message['text'], '') + eq(d.paint_theme_sample.called, 3) + + def test_custom_name(self): + d = self.page + + # If no selections, doesn't get added. + d.customlist.SetMenu([], '- no custom themes -') + self.assertNotIn('Theme', mainpage) + self.assertEqual(d.paint_theme_sample.called, 0) + + # Custom name selected. + changes.clear() + d.customlist.SetMenu(['a', 'b', 'c'], 'c') + self.assertEqual(mainpage, {'Theme': {'name': 'c'}}) + self.assertEqual(d.paint_theme_sample.called, 1) + + def test_color(self): + d = self.page + d.on_new_color_set = Func() + # self.color is only set in get_color through colorchooser. + d.color.set('green') + self.assertEqual(d.on_new_color_set.called, 1) + del d.on_new_color_set + + def test_highlight_target_list_mouse(self): + # Set highlight_target through targetlist. + eq = self.assertEqual + d = self.page + + d.targetlist.SetMenu(['a', 'b', 'c'], 'c') + eq(d.highlight_target.get(), 'c') + eq(d.set_highlight_target.called, 1) + + def test_highlight_target_text_mouse(self): + # Set highlight_target through clicking highlight_sample. + eq = self.assertEqual + d = self.page + hs = d.highlight_sample + hs.focus_force() + + def click_char(index): + "Simulate click on character at *index*." + hs.see(index) + hs.update_idletasks() + x, y, dx, dy = hs.bbox(index) + x += dx // 2 + y += dy // 2 + hs.event_generate('', x=0, y=0) + hs.event_generate('', x=x, y=y) + hs.event_generate('', x=x, y=y) + hs.event_generate('', x=x, y=y) + + # Reverse theme_elements to make the tag the key. + elem = {tag: element for element, tag in d.theme_elements.items()} + + # If highlight_sample has a tag that isn't in theme_elements, there + # will be a KeyError in the test run. + count = 0 + for tag in hs.tag_names(): + try: + click_char(hs.tag_nextrange(tag, "1.0")[0]) + eq(d.highlight_target.get(), elem[tag]) + count += 1 + eq(d.set_highlight_target.called, count) + except IndexError: + pass # Skip unused theme_elements tag, like 'sel'. + + def test_highlight_sample_double_click(self): + # Test double click on highlight_sample. + eq = self.assertEqual + d = self.page + + hs = d.highlight_sample + hs.focus_force() + hs.see(1.0) + hs.update_idletasks() + + # Test binding from configdialog. + hs.event_generate('', x=0, y=0) + hs.event_generate('', x=0, y=0) + # Double click is a sequence of two clicks in a row. + for _ in range(2): + hs.event_generate('', x=0, y=0) + hs.event_generate('', x=0, y=0) + + eq(hs.tag_ranges('sel'), ()) + + def test_highlight_sample_b1_motion(self): + # Test button motion on highlight_sample. + eq = self.assertEqual + d = self.page + + hs = d.highlight_sample + hs.focus_force() + hs.see(1.0) + hs.update_idletasks() + + x, y, dx, dy, offset = hs.dlineinfo('1.0') + + # Test binding from configdialog. + hs.event_generate('') + hs.event_generate('') + hs.event_generate('', x=x, y=y) + hs.event_generate('', x=x, y=y) + hs.event_generate('', x=dx, y=dy) + hs.event_generate('', x=dx, y=dy) + + eq(hs.tag_ranges('sel'), ()) + + def test_set_theme_type(self): + eq = self.assertEqual + d = self.page + del d.set_theme_type + + # Builtin theme selected. + d.theme_source.set(True) + d.set_theme_type() + eq(d.builtinlist['state'], NORMAL) + eq(d.customlist['state'], DISABLED) + eq(d.button_delete_custom.state(), ('disabled',)) + + # Custom theme selected. + d.theme_source.set(False) + d.set_theme_type() + eq(d.builtinlist['state'], DISABLED) + eq(d.custom_theme_on.state(), ('selected',)) + eq(d.customlist['state'], NORMAL) + eq(d.button_delete_custom.state(), ()) + d.set_theme_type = Func() + + def test_get_color(self): + eq = self.assertEqual + d = self.page + orig_chooser = configdialog.colorchooser.askcolor + chooser = configdialog.colorchooser.askcolor = Func() + gntn = d.get_new_theme_name = Func() + + d.highlight_target.set('Editor Breakpoint') + d.color.set('#ffffff') + + # Nothing selected. + chooser.result = (None, None) + d.button_set_color.invoke() + eq(d.color.get(), '#ffffff') + + # Selection same as previous color. + chooser.result = ('', d.style.lookup(d.frame_color_set['style'], 'background')) + d.button_set_color.invoke() + eq(d.color.get(), '#ffffff') + + # Select different color. + chooser.result = ((222.8671875, 0.0, 0.0), '#de0000') + + # Default theme. + d.color.set('#ffffff') + d.theme_source.set(True) + + # No theme name selected therefore color not saved. + gntn.result = '' + d.button_set_color.invoke() + eq(gntn.called, 1) + eq(d.color.get(), '#ffffff') + # Theme name selected. + gntn.result = 'My New Theme' + d.button_set_color.invoke() + eq(d.custom_name.get(), gntn.result) + eq(d.color.get(), '#de0000') + + # Custom theme. + d.color.set('#ffffff') + d.theme_source.set(False) + d.button_set_color.invoke() + eq(d.color.get(), '#de0000') + + del d.get_new_theme_name + configdialog.colorchooser.askcolor = orig_chooser + + def test_on_new_color_set(self): + d = self.page + color = '#3f7cae' + d.custom_name.set('Python') + d.highlight_target.set('Selected Text') + d.fg_bg_toggle.set(True) + + d.color.set(color) + self.assertEqual(d.style.lookup(d.frame_color_set['style'], 'background'), color) + self.assertEqual(d.highlight_sample.tag_cget('hilite', 'foreground'), color) + self.assertEqual(highpage, + {'Python': {'hilite-foreground': color}}) + + def test_get_new_theme_name(self): + orig_sectionname = configdialog.SectionName + sn = configdialog.SectionName = Func(return_self=True) + d = self.page + + sn.result = 'New Theme' + self.assertEqual(d.get_new_theme_name(''), 'New Theme') + + configdialog.SectionName = orig_sectionname + + def test_save_as_new_theme(self): + d = self.page + gntn = d.get_new_theme_name = Func() + d.theme_source.set(True) + + # No name entered. + gntn.result = '' + d.button_save_custom.invoke() + self.assertNotIn(gntn.result, idleConf.userCfg['highlight']) + + # Name entered. + gntn.result = 'my new theme' + gntn.called = 0 + self.assertNotIn(gntn.result, idleConf.userCfg['highlight']) + d.button_save_custom.invoke() + self.assertIn(gntn.result, idleConf.userCfg['highlight']) + + del d.get_new_theme_name + + def test_create_new_and_save_new(self): + eq = self.assertEqual + d = self.page + + # Use default as previously active theme. + d.theme_source.set(True) + d.builtin_name.set('IDLE Classic') + first_new = 'my new custom theme' + second_new = 'my second custom theme' + + # No changes, so themes are an exact copy. + self.assertNotIn(first_new, idleConf.userCfg) + d.create_new(first_new) + eq(idleConf.GetSectionList('user', 'highlight'), [first_new]) + eq(idleConf.GetThemeDict('default', 'IDLE Classic'), + idleConf.GetThemeDict('user', first_new)) + eq(d.custom_name.get(), first_new) + self.assertFalse(d.theme_source.get()) # Use custom set. + eq(d.set_theme_type.called, 1) + + # Test that changed targets are in new theme. + changes.add_option('highlight', first_new, 'hit-background', 'yellow') + self.assertNotIn(second_new, idleConf.userCfg) + d.create_new(second_new) + eq(idleConf.GetSectionList('user', 'highlight'), [first_new, second_new]) + self.assertNotEqual(idleConf.GetThemeDict('user', first_new), + idleConf.GetThemeDict('user', second_new)) + # Check that difference in themes was in `hit-background` from `changes`. + idleConf.SetOption('highlight', first_new, 'hit-background', 'yellow') + eq(idleConf.GetThemeDict('user', first_new), + idleConf.GetThemeDict('user', second_new)) + + def test_set_highlight_target(self): + eq = self.assertEqual + d = self.page + del d.set_highlight_target + + # Target is cursor. + d.highlight_target.set('Cursor') + eq(d.fg_on.state(), ('disabled', 'selected')) + eq(d.bg_on.state(), ('disabled',)) + self.assertTrue(d.fg_bg_toggle) + eq(d.set_color_sample.called, 1) + + # Target is not cursor. + d.highlight_target.set('Comment') + eq(d.fg_on.state(), ('selected',)) + eq(d.bg_on.state(), ()) + self.assertTrue(d.fg_bg_toggle) + eq(d.set_color_sample.called, 2) + + d.set_highlight_target = Func() + + def test_set_color_sample_binding(self): + d = self.page + scs = d.set_color_sample + + d.fg_on.invoke() + self.assertEqual(scs.called, 1) + + d.bg_on.invoke() + self.assertEqual(scs.called, 2) + + def test_set_color_sample(self): + d = self.page + del d.set_color_sample + d.highlight_target.set('Selected Text') + d.fg_bg_toggle.set(True) + d.set_color_sample() + self.assertEqual( + d.style.lookup(d.frame_color_set['style'], 'background'), + d.highlight_sample.tag_cget('hilite', 'foreground')) + d.set_color_sample = Func() + + def test_paint_theme_sample(self): + eq = self.assertEqual + page = self.page + del page.paint_theme_sample # Delete masking mock. + hs_tag = page.highlight_sample.tag_cget + gh = idleConf.GetHighlight + + # Create custom theme based on IDLE Dark. + page.theme_source.set(True) + page.builtin_name.set('IDLE Dark') + theme = 'IDLE Test' + page.create_new(theme) + page.set_color_sample.called = 0 + + # Base theme with nothing in `changes`. + page.paint_theme_sample() + new_console = {'foreground': 'blue', + 'background': 'yellow',} + for key, value in new_console.items(): + self.assertNotEqual(hs_tag('console', key), value) + eq(page.set_color_sample.called, 1) + + # Apply changes. + for key, value in new_console.items(): + changes.add_option('highlight', theme, 'console-'+key, value) + page.paint_theme_sample() + for key, value in new_console.items(): + eq(hs_tag('console', key), value) + eq(page.set_color_sample.called, 2) + + page.paint_theme_sample = Func() + + def test_delete_custom(self): + eq = self.assertEqual + d = self.page + d.button_delete_custom.state(('!disabled',)) + yesno = d.askyesno = Func() + dialog.deactivate_current_config = Func() + dialog.activate_config_changes = Func() + + theme_name = 'spam theme' + idleConf.userCfg['highlight'].SetOption(theme_name, 'name', 'value') + highpage[theme_name] = {'option': 'True'} + + theme_name2 = 'other theme' + idleConf.userCfg['highlight'].SetOption(theme_name2, 'name', 'value') + highpage[theme_name2] = {'option': 'False'} + + # Force custom theme. + d.custom_theme_on.state(('!disabled',)) + d.custom_theme_on.invoke() + d.custom_name.set(theme_name) + + # Cancel deletion. + yesno.result = False + d.button_delete_custom.invoke() + eq(yesno.called, 1) + eq(highpage[theme_name], {'option': 'True'}) + eq(idleConf.GetSectionList('user', 'highlight'), [theme_name, theme_name2]) + eq(dialog.deactivate_current_config.called, 0) + eq(dialog.activate_config_changes.called, 0) + eq(d.set_theme_type.called, 0) + + # Confirm deletion. + yesno.result = True + d.button_delete_custom.invoke() + eq(yesno.called, 2) + self.assertNotIn(theme_name, highpage) + eq(idleConf.GetSectionList('user', 'highlight'), [theme_name2]) + eq(d.custom_theme_on.state(), ()) + eq(d.custom_name.get(), theme_name2) + eq(dialog.deactivate_current_config.called, 1) + eq(dialog.activate_config_changes.called, 1) + eq(d.set_theme_type.called, 1) + + # Confirm deletion of second theme - empties list. + d.custom_name.set(theme_name2) + yesno.result = True + d.button_delete_custom.invoke() + eq(yesno.called, 3) + self.assertNotIn(theme_name, highpage) + eq(idleConf.GetSectionList('user', 'highlight'), []) + eq(d.custom_theme_on.state(), ('disabled',)) + eq(d.custom_name.get(), '- no custom themes -') + eq(dialog.deactivate_current_config.called, 2) + eq(dialog.activate_config_changes.called, 2) + eq(d.set_theme_type.called, 2) + + del dialog.activate_config_changes, dialog.deactivate_current_config + del d.askyesno + + +class KeysPageTest(unittest.TestCase): + """Test that keys tab widgets enable users to make changes. + + Test that widget actions set vars, that var changes add + options to changes and that key sets works correctly. + """ + + @classmethod + def setUpClass(cls): + page = cls.page = dialog.keyspage + dialog.note.select(page) + page.set_keys_type = Func() + page.load_keys_list = Func() + + @classmethod + def tearDownClass(cls): + page = cls.page + del page.set_keys_type, page.load_keys_list + + def setUp(self): + d = self.page + # The following is needed for test_load_key_cfg, _delete_custom_keys. + # This may indicate a defect in some test or function. + for section in idleConf.GetSectionList('user', 'keys'): + idleConf.userCfg['keys'].remove_section(section) + changes.clear() + d.set_keys_type.called = 0 + d.load_keys_list.called = 0 + + def test_load_key_cfg(self): + tracers.detach() + d = self.page + eq = self.assertEqual + + # Use builtin keyset with no user keysets created. + idleConf.CurrentKeys = mock.Mock(return_value='IDLE Classic OSX') + d.load_key_cfg() + self.assertTrue(d.keyset_source.get()) + # builtinlist sets variable builtin_name to the CurrentKeys default. + eq(d.builtin_name.get(), 'IDLE Classic OSX') + eq(d.custom_name.get(), '- no custom keys -') + eq(d.custom_keyset_on.state(), ('disabled',)) + eq(d.set_keys_type.called, 1) + eq(d.load_keys_list.called, 1) + eq(d.load_keys_list.args, ('IDLE Classic OSX', )) + + # Builtin keyset with non-empty user keyset list. + idleConf.SetOption('keys', 'test1', 'option', 'value') + idleConf.SetOption('keys', 'test2', 'option2', 'value2') + d.load_key_cfg() + eq(d.builtin_name.get(), 'IDLE Classic OSX') + eq(d.custom_name.get(), 'test1') + eq(d.set_keys_type.called, 2) + eq(d.load_keys_list.called, 2) + eq(d.load_keys_list.args, ('IDLE Classic OSX', )) + + # Use custom keyset. + idleConf.CurrentKeys = mock.Mock(return_value='test2') + idleConf.default_keys = mock.Mock(return_value='IDLE Modern Unix') + idleConf.SetOption('main', 'Keys', 'default', '0') + d.load_key_cfg() + self.assertFalse(d.keyset_source.get()) + eq(d.builtin_name.get(), 'IDLE Modern Unix') + eq(d.custom_name.get(), 'test2') + eq(d.set_keys_type.called, 3) + eq(d.load_keys_list.called, 3) + eq(d.load_keys_list.args, ('test2', )) + + del idleConf.CurrentKeys, idleConf.default_keys + tracers.attach() + + def test_keyset_source(self): + eq = self.assertEqual + d = self.page + # Test these separately. + d.var_changed_builtin_name = Func() + d.var_changed_custom_name = Func() + # Builtin selected. + d.builtin_keyset_on.invoke() + eq(mainpage, {'Keys': {'default': 'True'}}) + eq(d.var_changed_builtin_name.called, 1) + eq(d.var_changed_custom_name.called, 0) + changes.clear() + + # Custom selected. + d.custom_keyset_on.state(('!disabled',)) + d.custom_keyset_on.invoke() + self.assertEqual(mainpage, {'Keys': {'default': 'False'}}) + eq(d.var_changed_builtin_name.called, 1) + eq(d.var_changed_custom_name.called, 1) + del d.var_changed_builtin_name, d.var_changed_custom_name + + def test_builtin_name(self): + eq = self.assertEqual + d = self.page + idleConf.userCfg['main'].remove_section('Keys') + item_list = ['IDLE Classic Windows', 'IDLE Classic OSX', + 'IDLE Modern UNIX'] + + # Not in old_keys, defaults name to first item. + d.builtinlist.SetMenu(item_list, 'IDLE Modern UNIX') + eq(mainpage, {'Keys': {'name': 'IDLE Classic Windows', + 'name2': 'IDLE Modern UNIX'}}) + eq(d.keys_message['text'], 'New key set, see Help') + eq(d.load_keys_list.called, 1) + eq(d.load_keys_list.args, ('IDLE Modern UNIX', )) + + # Not in old keys - uses name2. + changes.clear() + idleConf.SetOption('main', 'Keys', 'name', 'IDLE Classic Unix') + d.builtinlist.SetMenu(item_list, 'IDLE Modern UNIX') + eq(mainpage, {'Keys': {'name2': 'IDLE Modern UNIX'}}) + eq(d.keys_message['text'], 'New key set, see Help') + eq(d.load_keys_list.called, 2) + eq(d.load_keys_list.args, ('IDLE Modern UNIX', )) + + # Builtin name in old_keys. + changes.clear() + d.builtinlist.SetMenu(item_list, 'IDLE Classic OSX') + eq(mainpage, {'Keys': {'name': 'IDLE Classic OSX', 'name2': ''}}) + eq(d.keys_message['text'], '') + eq(d.load_keys_list.called, 3) + eq(d.load_keys_list.args, ('IDLE Classic OSX', )) + + def test_custom_name(self): + d = self.page + + # If no selections, doesn't get added. + d.customlist.SetMenu([], '- no custom keys -') + self.assertNotIn('Keys', mainpage) + self.assertEqual(d.load_keys_list.called, 0) + + # Custom name selected. + changes.clear() + d.customlist.SetMenu(['a', 'b', 'c'], 'c') + self.assertEqual(mainpage, {'Keys': {'name': 'c'}}) + self.assertEqual(d.load_keys_list.called, 1) + + def test_keybinding(self): + idleConf.SetOption('extensions', 'ZzDummy', 'enable', 'True') + d = self.page + d.custom_name.set('my custom keys') + d.bindingslist.delete(0, 'end') + d.bindingslist.insert(0, 'copy') + d.bindingslist.insert(1, 'z-in') + d.bindingslist.selection_set(0) + d.bindingslist.selection_anchor(0) + # Core binding - adds to keys. + d.keybinding.set('') + self.assertEqual(keyspage, + {'my custom keys': {'copy': ''}}) + + # Not a core binding - adds to extensions. + d.bindingslist.selection_set(1) + d.bindingslist.selection_anchor(1) + d.keybinding.set('') + self.assertEqual(extpage, + {'ZzDummy_cfgBindings': {'z-in': ''}}) + + def test_set_keys_type(self): + eq = self.assertEqual + d = self.page + del d.set_keys_type + + # Builtin keyset selected. + d.keyset_source.set(True) + d.set_keys_type() + eq(d.builtinlist['state'], NORMAL) + eq(d.customlist['state'], DISABLED) + eq(d.button_delete_custom_keys.state(), ('disabled',)) + + # Custom keyset selected. + d.keyset_source.set(False) + d.set_keys_type() + eq(d.builtinlist['state'], DISABLED) + eq(d.custom_keyset_on.state(), ('selected',)) + eq(d.customlist['state'], NORMAL) + eq(d.button_delete_custom_keys.state(), ()) + d.set_keys_type = Func() + + def test_get_new_keys(self): + eq = self.assertEqual + d = self.page + orig_getkeysdialog = configdialog.GetKeysWindow + gkd = configdialog.GetKeysWindow = Func(return_self=True) + gnkn = d.get_new_keys_name = Func() + + d.button_new_keys.state(('!disabled',)) + d.bindingslist.delete(0, 'end') + d.bindingslist.insert(0, 'copy - ') + d.bindingslist.selection_set(0) + d.bindingslist.selection_anchor(0) + d.keybinding.set('Key-a') + d.keyset_source.set(True) # Default keyset. + + # Default keyset; no change to binding. + gkd.result = '' + d.button_new_keys.invoke() + eq(d.bindingslist.get('anchor'), 'copy - ') + # Keybinding isn't changed when there isn't a change entered. + eq(d.keybinding.get(), 'Key-a') + + # Default keyset; binding changed. + gkd.result = '' + # No keyset name selected therefore binding not saved. + gnkn.result = '' + d.button_new_keys.invoke() + eq(gnkn.called, 1) + eq(d.bindingslist.get('anchor'), 'copy - ') + # Keyset name selected. + gnkn.result = 'My New Key Set' + d.button_new_keys.invoke() + eq(d.custom_name.get(), gnkn.result) + eq(d.bindingslist.get('anchor'), 'copy - ') + eq(d.keybinding.get(), '') + + # User keyset; binding changed. + d.keyset_source.set(False) # Custom keyset. + gnkn.called = 0 + gkd.result = '' + d.button_new_keys.invoke() + eq(gnkn.called, 0) + eq(d.bindingslist.get('anchor'), 'copy - ') + eq(d.keybinding.get(), '') + + del d.get_new_keys_name + configdialog.GetKeysWindow = orig_getkeysdialog + + def test_get_new_keys_name(self): + orig_sectionname = configdialog.SectionName + sn = configdialog.SectionName = Func(return_self=True) + d = self.page + + sn.result = 'New Keys' + self.assertEqual(d.get_new_keys_name(''), 'New Keys') + + configdialog.SectionName = orig_sectionname + + def test_save_as_new_key_set(self): + d = self.page + gnkn = d.get_new_keys_name = Func() + d.keyset_source.set(True) + + # No name entered. + gnkn.result = '' + d.button_save_custom_keys.invoke() + + # Name entered. + gnkn.result = 'my new key set' + gnkn.called = 0 + self.assertNotIn(gnkn.result, idleConf.userCfg['keys']) + d.button_save_custom_keys.invoke() + self.assertIn(gnkn.result, idleConf.userCfg['keys']) + + del d.get_new_keys_name + + def test_on_bindingslist_select(self): + d = self.page + b = d.bindingslist + b.delete(0, 'end') + b.insert(0, 'copy') + b.insert(1, 'find') + b.activate(0) + + b.focus_force() + b.see(1) + b.update() + x, y, dx, dy = b.bbox(1) + x += dx // 2 + y += dy // 2 + b.event_generate('', x=0, y=0) + b.event_generate('', x=x, y=y) + b.event_generate('', x=x, y=y) + b.event_generate('', x=x, y=y) + self.assertEqual(b.get('anchor'), 'find') + self.assertEqual(d.button_new_keys.state(), ()) + + def test_create_new_key_set_and_save_new_key_set(self): + eq = self.assertEqual + d = self.page + + # Use default as previously active keyset. + d.keyset_source.set(True) + d.builtin_name.set('IDLE Classic Windows') + first_new = 'my new custom key set' + second_new = 'my second custom keyset' + + # No changes, so keysets are an exact copy. + self.assertNotIn(first_new, idleConf.userCfg) + d.create_new_key_set(first_new) + eq(idleConf.GetSectionList('user', 'keys'), [first_new]) + eq(idleConf.GetKeySet('IDLE Classic Windows'), + idleConf.GetKeySet(first_new)) + eq(d.custom_name.get(), first_new) + self.assertFalse(d.keyset_source.get()) # Use custom set. + eq(d.set_keys_type.called, 1) + + # Test that changed keybindings are in new keyset. + changes.add_option('keys', first_new, 'copy', '') + self.assertNotIn(second_new, idleConf.userCfg) + d.create_new_key_set(second_new) + eq(idleConf.GetSectionList('user', 'keys'), [first_new, second_new]) + self.assertNotEqual(idleConf.GetKeySet(first_new), + idleConf.GetKeySet(second_new)) + # Check that difference in keysets was in option `copy` from `changes`. + idleConf.SetOption('keys', first_new, 'copy', '') + eq(idleConf.GetKeySet(first_new), idleConf.GetKeySet(second_new)) + + def test_load_keys_list(self): + eq = self.assertEqual + d = self.page + gks = idleConf.GetKeySet = Func() + del d.load_keys_list + b = d.bindingslist + + b.delete(0, 'end') + b.insert(0, '<>') + b.insert(1, '<>') + gks.result = {'<>': ['', ''], + '<>': [''], + '<>': ['']} + changes.add_option('keys', 'my keys', 'spam', '') + expected = ('copy - ', + 'force-open-completions - ', + 'spam - ') + + # No current selection. + d.load_keys_list('my keys') + eq(b.get(0, 'end'), expected) + eq(b.get('anchor'), '') + eq(b.curselection(), ()) + + # Check selection. + b.selection_set(1) + b.selection_anchor(1) + d.load_keys_list('my keys') + eq(b.get(0, 'end'), expected) + eq(b.get('anchor'), 'force-open-completions - ') + eq(b.curselection(), (1, )) + + # Change selection. + b.selection_set(2) + b.selection_anchor(2) + d.load_keys_list('my keys') + eq(b.get(0, 'end'), expected) + eq(b.get('anchor'), 'spam - ') + eq(b.curselection(), (2, )) + d.load_keys_list = Func() + + del idleConf.GetKeySet + + def test_delete_custom_keys(self): + eq = self.assertEqual + d = self.page + d.button_delete_custom_keys.state(('!disabled',)) + yesno = d.askyesno = Func() + dialog.deactivate_current_config = Func() + dialog.activate_config_changes = Func() + + keyset_name = 'spam key set' + idleConf.userCfg['keys'].SetOption(keyset_name, 'name', 'value') + keyspage[keyset_name] = {'option': 'True'} + + keyset_name2 = 'other key set' + idleConf.userCfg['keys'].SetOption(keyset_name2, 'name', 'value') + keyspage[keyset_name2] = {'option': 'False'} + + # Force custom keyset. + d.custom_keyset_on.state(('!disabled',)) + d.custom_keyset_on.invoke() + d.custom_name.set(keyset_name) + + # Cancel deletion. + yesno.result = False + d.button_delete_custom_keys.invoke() + eq(yesno.called, 1) + eq(keyspage[keyset_name], {'option': 'True'}) + eq(idleConf.GetSectionList('user', 'keys'), [keyset_name, keyset_name2]) + eq(dialog.deactivate_current_config.called, 0) + eq(dialog.activate_config_changes.called, 0) + eq(d.set_keys_type.called, 0) + + # Confirm deletion. + yesno.result = True + d.button_delete_custom_keys.invoke() + eq(yesno.called, 2) + self.assertNotIn(keyset_name, keyspage) + eq(idleConf.GetSectionList('user', 'keys'), [keyset_name2]) + eq(d.custom_keyset_on.state(), ()) + eq(d.custom_name.get(), keyset_name2) + eq(dialog.deactivate_current_config.called, 1) + eq(dialog.activate_config_changes.called, 1) + eq(d.set_keys_type.called, 1) + + # Confirm deletion of second keyset - empties list. + d.custom_name.set(keyset_name2) + yesno.result = True + d.button_delete_custom_keys.invoke() + eq(yesno.called, 3) + self.assertNotIn(keyset_name, keyspage) + eq(idleConf.GetSectionList('user', 'keys'), []) + eq(d.custom_keyset_on.state(), ('disabled',)) + eq(d.custom_name.get(), '- no custom keys -') + eq(dialog.deactivate_current_config.called, 2) + eq(dialog.activate_config_changes.called, 2) + eq(d.set_keys_type.called, 2) + + del dialog.activate_config_changes, dialog.deactivate_current_config + del d.askyesno + + +class WinPageTest(unittest.TestCase): + """Test that general tab widgets enable users to make changes. + + Test that widget actions set vars, that var changes add + options to changes. + """ + @classmethod + def setUpClass(cls): + page = cls.page = dialog.winpage + dialog.note.select(page) + page.update() + + def setUp(self): + changes.clear() + + def test_load_windows_cfg(self): + # Set to wrong values, load, check right values. + eq = self.assertEqual + d = self.page + d.startup_edit.set(1) + d.win_width.set(1) + d.win_height.set(1) + d.load_windows_cfg() + eq(d.startup_edit.get(), 0) + eq(d.win_width.get(), '80') + eq(d.win_height.get(), '40') + + def test_startup(self): + d = self.page + d.startup_editor_on.invoke() + self.assertEqual(mainpage, + {'General': {'editor-on-startup': '1'}}) + changes.clear() + d.startup_shell_on.invoke() + self.assertEqual(mainpage, + {'General': {'editor-on-startup': '0'}}) + + def test_editor_size(self): + d = self.page + d.win_height_int.delete(0, 'end') + d.win_height_int.insert(0, '11') + self.assertEqual(mainpage, {'EditorWindow': {'height': '11'}}) + changes.clear() + d.win_width_int.delete(0, 'end') + d.win_width_int.insert(0, '11') + self.assertEqual(mainpage, {'EditorWindow': {'width': '11'}}) + + def test_indent_spaces(self): + d = self.page + d.indent_chooser.set(6) + self.assertEqual(d.indent_spaces.get(), '6') + self.assertEqual(mainpage, {'Indent': {'num-spaces': '6'}}) + + def test_cursor_blink(self): + self.page.cursor_blink_bool.invoke() + self.assertEqual(mainpage, {'EditorWindow': {'cursor-blink': 'False'}}) + + def test_autocomplete_wait(self): + self.page.auto_wait_int.delete(0, 'end') + self.page.auto_wait_int.insert(0, '11') + self.assertEqual(extpage, {'AutoComplete': {'popupwait': '11'}}) + + def test_parenmatch(self): + d = self.page + eq = self.assertEqual + d.paren_style_type['menu'].invoke(0) + eq(extpage, {'ParenMatch': {'style': 'opener'}}) + changes.clear() + d.paren_flash_time.delete(0, 'end') + d.paren_flash_time.insert(0, '11') + eq(extpage, {'ParenMatch': {'flash-delay': '11'}}) + changes.clear() + d.bell_on.invoke() + eq(extpage, {'ParenMatch': {'bell': 'False'}}) + + def test_paragraph(self): + self.page.format_width_int.delete(0, 'end') + self.page.format_width_int.insert(0, '11') + self.assertEqual(extpage, {'FormatParagraph': {'max-width': '11'}}) + + +class ShedPageTest(unittest.TestCase): + """Test that shed tab widgets enable users to make changes. + + Test that widget actions set vars, that var changes add + options to changes. + """ + @classmethod + def setUpClass(cls): + page = cls.page = dialog.shedpage + dialog.note.select(page) + page.update() + + def setUp(self): + changes.clear() + + def test_load_shelled_cfg(self): + # Set to wrong values, load, check right values. + eq = self.assertEqual + d = self.page + d.autosave.set(1) + d.load_shelled_cfg() + eq(d.autosave.get(), 0) + + def test_autosave(self): + d = self.page + d.save_auto_on.invoke() + self.assertEqual(mainpage, {'General': {'autosave': '1'}}) + d.save_ask_on.invoke() + self.assertEqual(mainpage, {'General': {'autosave': '0'}}) + + def test_context(self): + self.page.context_int.delete(0, 'end') + self.page.context_int.insert(0, '1') + self.assertEqual(extpage, {'CodeContext': {'maxlines': '1'}}) + + +#unittest.skip("Nothing here yet TODO") +class ExtPageTest(unittest.TestCase): + """Test that the help source list works correctly.""" + @classmethod + def setUpClass(cls): + page = dialog.extpage + dialog.note.select(page) + + +class HelpSourceTest(unittest.TestCase): + """Test that the help source list works correctly.""" + @classmethod + def setUpClass(cls): + page = dialog.extpage + dialog.note.select(page) + frame = cls.frame = page.frame_help + frame.set = frame.set_add_delete_state = Func() + frame.upc = frame.update_help_changes = Func() + frame.update() + + @classmethod + def tearDownClass(cls): + frame = cls.frame + del frame.set, frame.set_add_delete_state + del frame.upc, frame.update_help_changes + frame.helplist.delete(0, 'end') + frame.user_helplist.clear() + + def setUp(self): + changes.clear() + + def test_load_helplist(self): + eq = self.assertEqual + fr = self.frame + fr.helplist.insert('end', 'bad') + fr.user_helplist = ['bad', 'worse'] + idleConf.SetOption('main', 'HelpFiles', '1', 'name;file') + fr.load_helplist() + eq(fr.helplist.get(0, 'end'), ('name',)) + eq(fr.user_helplist, [('name', 'file', '1')]) + + def test_source_selected(self): + fr = self.frame + fr.set = fr.set_add_delete_state + fr.upc = fr.update_help_changes + helplist = fr.helplist + dex = 'end' + helplist.insert(dex, 'source') + helplist.activate(dex) + + helplist.focus_force() + helplist.see(dex) + helplist.update() + x, y, dx, dy = helplist.bbox(dex) + x += dx // 2 + y += dy // 2 + fr.set.called = fr.upc.called = 0 + helplist.event_generate('', x=0, y=0) + helplist.event_generate('', x=x, y=y) + helplist.event_generate('', x=x, y=y) + helplist.event_generate('', x=x, y=y) + self.assertEqual(helplist.get('anchor'), 'source') + self.assertTrue(fr.set.called) + self.assertFalse(fr.upc.called) + + def test_set_add_delete_state(self): + # Call with 0 items, 1 unselected item, 1 selected item. + eq = self.assertEqual + fr = self.frame + del fr.set_add_delete_state # Unmask method. + sad = fr.set_add_delete_state + h = fr.helplist + + h.delete(0, 'end') + sad() + eq(fr.button_helplist_edit.state(), ('disabled',)) + eq(fr.button_helplist_remove.state(), ('disabled',)) + + h.insert(0, 'source') + sad() + eq(fr.button_helplist_edit.state(), ('disabled',)) + eq(fr.button_helplist_remove.state(), ('disabled',)) + + h.selection_set(0) + sad() + eq(fr.button_helplist_edit.state(), ()) + eq(fr.button_helplist_remove.state(), ()) + fr.set_add_delete_state = Func() # Mask method. + + def test_helplist_item_add(self): + # Call without and twice with HelpSource result. + # Double call enables check on order. + eq = self.assertEqual + orig_helpsource = configdialog.HelpSource + hs = configdialog.HelpSource = Func(return_self=True) + fr = self.frame + fr.helplist.delete(0, 'end') + fr.user_helplist.clear() + fr.set.called = fr.upc.called = 0 + + hs.result = '' + fr.helplist_item_add() + self.assertTrue(list(fr.helplist.get(0, 'end')) == + fr.user_helplist == []) + self.assertFalse(fr.upc.called) + + hs.result = ('name1', 'file1') + fr.helplist_item_add() + hs.result = ('name2', 'file2') + fr.helplist_item_add() + eq(fr.helplist.get(0, 'end'), ('name1', 'name2')) + eq(fr.user_helplist, [('name1', 'file1'), ('name2', 'file2')]) + eq(fr.upc.called, 2) + self.assertFalse(fr.set.called) + + configdialog.HelpSource = orig_helpsource + + def test_helplist_item_edit(self): + # Call without and with HelpSource change. + eq = self.assertEqual + orig_helpsource = configdialog.HelpSource + hs = configdialog.HelpSource = Func(return_self=True) + fr = self.frame + fr.helplist.delete(0, 'end') + fr.helplist.insert(0, 'name1') + fr.helplist.selection_set(0) + fr.helplist.selection_anchor(0) + fr.user_helplist.clear() + fr.user_helplist.append(('name1', 'file1')) + fr.set.called = fr.upc.called = 0 + + hs.result = '' + fr.helplist_item_edit() + hs.result = ('name1', 'file1') + fr.helplist_item_edit() + eq(fr.helplist.get(0, 'end'), ('name1',)) + eq(fr.user_helplist, [('name1', 'file1')]) + self.assertFalse(fr.upc.called) + + hs.result = ('name2', 'file2') + fr.helplist_item_edit() + eq(fr.helplist.get(0, 'end'), ('name2',)) + eq(fr.user_helplist, [('name2', 'file2')]) + self.assertTrue(fr.upc.called == fr.set.called == 1) + + configdialog.HelpSource = orig_helpsource + + def test_helplist_item_remove(self): + eq = self.assertEqual + fr = self.frame + fr.helplist.delete(0, 'end') + fr.helplist.insert(0, 'name1') + fr.helplist.selection_set(0) + fr.helplist.selection_anchor(0) + fr.user_helplist.clear() + fr.user_helplist.append(('name1', 'file1')) + fr.set.called = fr.upc.called = 0 + + fr.helplist_item_remove() + eq(fr.helplist.get(0, 'end'), ()) + eq(fr.user_helplist, []) + self.assertTrue(fr.upc.called == fr.set.called == 1) + + def test_update_help_changes(self): + fr = self.frame + del fr.update_help_changes + fr.user_helplist.clear() + fr.user_helplist.append(('name1', 'file1')) + fr.user_helplist.append(('name2', 'file2')) + + fr.update_help_changes() + self.assertEqual(mainpage['HelpFiles'], + {'1': 'name1;file1', '2': 'name2;file2'}) + fr.update_help_changes = Func() + + +class VarTraceTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + cls.tracers = configdialog.VarTrace() + cls.iv = IntVar(root) + cls.bv = BooleanVar(root) + + @classmethod + def tearDownClass(cls): + del cls.tracers, cls.iv, cls.bv + + def setUp(self): + self.tracers.clear() + self.called = 0 + + def var_changed_increment(self, *params): + self.called += 13 + + def var_changed_boolean(self, *params): + pass + + def test_init(self): + tr = self.tracers + tr.__init__() + self.assertEqual(tr.untraced, []) + self.assertEqual(tr.traced, []) + + def test_clear(self): + tr = self.tracers + tr.untraced.append(0) + tr.traced.append(1) + tr.clear() + self.assertEqual(tr.untraced, []) + self.assertEqual(tr.traced, []) + + def test_add(self): + tr = self.tracers + func = Func() + cb = tr.make_callback = mock.Mock(return_value=func) + + iv = tr.add(self.iv, self.var_changed_increment) + self.assertIs(iv, self.iv) + bv = tr.add(self.bv, self.var_changed_boolean) + self.assertIs(bv, self.bv) + + sv = StringVar(root) + sv2 = tr.add(sv, ('main', 'section', 'option')) + self.assertIs(sv2, sv) + cb.assert_called_once() + cb.assert_called_with(sv, ('main', 'section', 'option')) + + expected = [(iv, self.var_changed_increment), + (bv, self.var_changed_boolean), + (sv, func)] + self.assertEqual(tr.traced, []) + self.assertEqual(tr.untraced, expected) + + del tr.make_callback + + def test_make_callback(self): + cb = self.tracers.make_callback(self.iv, ('main', 'section', 'option')) + self.assertTrue(callable(cb)) + self.iv.set(42) + # Not attached, so set didn't invoke the callback. + self.assertNotIn('section', changes['main']) + # Invoke callback manually. + cb() + self.assertIn('section', changes['main']) + self.assertEqual(changes['main']['section']['option'], '42') + changes.clear() + + def test_attach_detach(self): + tr = self.tracers + iv = tr.add(self.iv, self.var_changed_increment) + bv = tr.add(self.bv, self.var_changed_boolean) + expected = [(iv, self.var_changed_increment), + (bv, self.var_changed_boolean)] + + # Attach callbacks and test call increment. + tr.attach() + self.assertEqual(tr.untraced, []) + self.assertCountEqual(tr.traced, expected) + iv.set(1) + self.assertEqual(iv.get(), 1) + self.assertEqual(self.called, 13) + + # Check that only one callback is attached to a variable. + # If more than one callback were attached, then var_changed_increment + # would be called twice and the counter would be 2. + self.called = 0 + tr.attach() + iv.set(1) + self.assertEqual(self.called, 13) + + # Detach callbacks. + self.called = 0 + tr.detach() + self.assertEqual(tr.traced, []) + self.assertCountEqual(tr.untraced, expected) + iv.set(1) + self.assertEqual(self.called, 0) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_debugger.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_debugger.py new file mode 100644 index 0000000000000000000000000000000000000000..f4009258e0594ca78937e567c415af59701fb380 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_debugger.py @@ -0,0 +1,298 @@ +"""Test debugger, coverage 66% + +Try to make tests pass with draft bdbx, which may replace bdb in 3.13+. +""" + +from idlelib import debugger +from collections import namedtuple +from textwrap import dedent +from tkinter import Tk + +from test.support import requires +from test.support.testcase import ExtraAssertions +import unittest +from unittest import mock +from unittest.mock import Mock, patch + +"""A test python script for the debug tests.""" +TEST_CODE = dedent(""" + i = 1 + i += 2 + if i == 3: + print(i) + """) + + +class MockFrame: + "Minimal mock frame." + + def __init__(self, code, lineno): + self.f_code = code + self.f_lineno = lineno + + +class IdbTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + cls.gui = Mock() + cls.idb = debugger.Idb(cls.gui) + + # Create test and code objects to simulate a debug session. + code_obj = compile(TEST_CODE, 'idlelib/file.py', mode='exec') + frame1 = MockFrame(code_obj, 1) + frame1.f_back = None + frame2 = MockFrame(code_obj, 2) + frame2.f_back = frame1 + cls.frame = frame2 + cls.msg = 'file.py:2: ()' + + def test_init(self): + self.assertIs(self.idb.gui, self.gui) + # Won't test super call since two Bdbs are very different. + + def test_user_line(self): + # Test that .user_line() creates a string message for a frame. + self.gui.interaction = Mock() + self.idb.user_line(self.frame) + self.gui.interaction.assert_called_once_with(self.msg, self.frame) + + def test_user_exception(self): + # Test that .user_exception() creates a string message for a frame. + exc_info = (type(ValueError), ValueError(), None) + self.gui.interaction = Mock() + self.idb.user_exception(self.frame, exc_info) + self.gui.interaction.assert_called_once_with( + self.msg, self.frame, exc_info) + + +class FunctionTest(unittest.TestCase): + # Test module functions together. + + def test_functions(self): + rpc_obj = compile(TEST_CODE,'rpc.py', mode='exec') + rpc_frame = MockFrame(rpc_obj, 2) + rpc_frame.f_back = rpc_frame + self.assertTrue(debugger._in_rpc_code(rpc_frame)) + self.assertEqual(debugger._frame2message(rpc_frame), + 'rpc.py:2: ()') + + code_obj = compile(TEST_CODE, 'idlelib/debugger.py', mode='exec') + code_frame = MockFrame(code_obj, 1) + code_frame.f_back = None + self.assertFalse(debugger._in_rpc_code(code_frame)) + self.assertEqual(debugger._frame2message(code_frame), + 'debugger.py:1: ()') + + code_frame.f_back = code_frame + self.assertFalse(debugger._in_rpc_code(code_frame)) + code_frame.f_back = rpc_frame + self.assertTrue(debugger._in_rpc_code(code_frame)) + + +class DebuggerTest(unittest.TestCase): + "Tests for Debugger that do not need a real root." + + @classmethod + def setUpClass(cls): + cls.pyshell = Mock() + cls.pyshell.root = Mock() + cls.idb = Mock() + with patch.object(debugger.Debugger, 'make_gui'): + cls.debugger = debugger.Debugger(cls.pyshell, cls.idb) + cls.debugger.root = Mock() + + def test_cont(self): + self.debugger.cont() + self.idb.set_continue.assert_called_once() + + def test_step(self): + self.debugger.step() + self.idb.set_step.assert_called_once() + + def test_quit(self): + self.debugger.quit() + self.idb.set_quit.assert_called_once() + + def test_next(self): + with patch.object(self.debugger, 'frame') as frame: + self.debugger.next() + self.idb.set_next.assert_called_once_with(frame) + + def test_ret(self): + with patch.object(self.debugger, 'frame') as frame: + self.debugger.ret() + self.idb.set_return.assert_called_once_with(frame) + + def test_clear_breakpoint(self): + self.debugger.clear_breakpoint('test.py', 4) + self.idb.clear_break.assert_called_once_with('test.py', 4) + + def test_clear_file_breaks(self): + self.debugger.clear_file_breaks('test.py') + self.idb.clear_all_file_breaks.assert_called_once_with('test.py') + + def test_set_load_breakpoints(self): + # Test the .load_breakpoints() method calls idb. + FileIO = namedtuple('FileIO', 'filename') + + class MockEditWindow(object): + def __init__(self, fn, breakpoints): + self.io = FileIO(fn) + self.breakpoints = breakpoints + + self.pyshell.flist = Mock() + self.pyshell.flist.inversedict = ( + MockEditWindow('test1.py', [4, 4]), + MockEditWindow('test2.py', [13, 44, 45]), + ) + self.debugger.set_breakpoint('test0.py', 1) + self.idb.set_break.assert_called_once_with('test0.py', 1) + self.debugger.load_breakpoints() # Call set_breakpoint 5 times. + self.idb.set_break.assert_has_calls( + [mock.call('test0.py', 1), + mock.call('test1.py', 4), + mock.call('test1.py', 4), + mock.call('test2.py', 13), + mock.call('test2.py', 44), + mock.call('test2.py', 45)]) + + def test_sync_source_line(self): + # Test that .sync_source_line() will set the flist.gotofileline with fixed frame. + test_code = compile(TEST_CODE, 'test_sync.py', 'exec') + test_frame = MockFrame(test_code, 1) + self.debugger.frame = test_frame + + self.debugger.flist = Mock() + with patch('idlelib.debugger.os.path.exists', return_value=True): + self.debugger.sync_source_line() + self.debugger.flist.gotofileline.assert_called_once_with('test_sync.py', 1) + + +class DebuggerGuiTest(unittest.TestCase): + """Tests for debugger.Debugger that need tk root. + + close needs debugger.top set in make_gui. + """ + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = root = Tk() + root.withdraw() + cls.pyshell = Mock() + cls.pyshell.root = root + cls.idb = Mock() +# stack tests fail with debugger here. +## cls.debugger = debugger.Debugger(cls.pyshell, cls.idb) +## cls.debugger.root = root +## # real root needed for real make_gui +## # run, interacting, abort_loop + + @classmethod + def tearDownClass(cls): + cls.root.destroy() + del cls.root + + def setUp(self): + self.debugger = debugger.Debugger(self.pyshell, self.idb) + self.debugger.root = self.root + # real root needed for real make_gui + # run, interacting, abort_loop + + def test_run_debugger(self): + self.debugger.run(1, 'two') + self.idb.run.assert_called_once_with(1, 'two') + self.assertEqual(self.debugger.interacting, 0) + + def test_close(self): + # Test closing the window in an idle state. + self.debugger.close() + self.pyshell.close_debugger.assert_called_once() + + def test_show_stack(self): + self.debugger.show_stack() + self.assertEqual(self.debugger.stackviewer.gui, self.debugger) + + def test_show_stack_with_frame(self): + test_frame = MockFrame(None, None) + self.debugger.frame = test_frame + + # Reset the stackviewer to force it to be recreated. + self.debugger.stackviewer = None + self.idb.get_stack.return_value = ([], 0) + self.debugger.show_stack() + + # Check that the newly created stackviewer has the test gui as a field. + self.assertEqual(self.debugger.stackviewer.gui, self.debugger) + self.idb.get_stack.assert_called_once_with(test_frame, None) + + +class StackViewerTest(unittest.TestCase, ExtraAssertions): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + + @classmethod + def tearDownClass(cls): + cls.root.destroy() + del cls.root + + def setUp(self): + self.code = compile(TEST_CODE, 'test_stackviewer.py', 'exec') + self.stack = [ + (MockFrame(self.code, 1), 1), + (MockFrame(self.code, 2), 2) + ] + # Create a stackviewer and load the test stack. + self.sv = debugger.StackViewer(self.root, None, None) + self.sv.load_stack(self.stack) + + def test_init(self): + # Test creation of StackViewer. + gui = None + flist = None + master_window = self.root + sv = debugger.StackViewer(master_window, flist, gui) + self.assertHasAttr(sv, 'stack') + + def test_load_stack(self): + # Test the .load_stack() method against a fixed test stack. + # Check the test stack is assigned and the list contains the repr of them. + self.assertEqual(self.sv.stack, self.stack) + self.assertTrue('?.(), line 1:' in self.sv.get(0)) + self.assertEqual(self.sv.get(1), '?.(), line 2: ') + + def test_show_source(self): + # Test the .show_source() method against a fixed test stack. + # Patch out the file list to monitor it + self.sv.flist = Mock() + # Patch out isfile to pretend file exists. + with patch('idlelib.debugger.os.path.isfile', return_value=True) as isfile: + self.sv.show_source(1) + isfile.assert_called_once_with('test_stackviewer.py') + self.sv.flist.open.assert_called_once_with('test_stackviewer.py') + + +class NameSpaceTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + + @classmethod + def tearDownClass(cls): + cls.root.destroy() + del cls.root + + def test_init(self): + debugger.NamespaceViewer(self.root, 'Test') + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_debugger_r.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_debugger_r.py new file mode 100644 index 0000000000000000000000000000000000000000..cf8af05fe27e77b7a4ec17c2bd9dfcd163a4750e --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_debugger_r.py @@ -0,0 +1,36 @@ +"Test debugger_r, coverage 30%." + +from idlelib import debugger_r +import unittest + +# Boilerplate likely to be needed for future test classes. +##from test.support import requires +##from tkinter import Tk +##class Test(unittest.TestCase): +## @classmethod +## def setUpClass(cls): +## requires('gui') +## cls.root = Tk() +## @classmethod +## def tearDownClass(cls): +## cls.root.destroy() + +# GUIProxy, IdbAdapter, FrameProxy, CodeProxy, DictProxy, +# GUIAdapter, IdbProxy, and 7 functions still need tests. + +class IdbAdapterTest(unittest.TestCase): + + def test_dict_item_noattr(self): # Issue 33065. + + class BinData: + def __repr__(self): + return self.length + + debugger_r.dicttable[0] = {'BinData': BinData()} + idb = debugger_r.IdbAdapter(None) + self.assertTrue(idb.dict_item(0, 'BinData')) + debugger_r.dicttable.clear() + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_debugobj.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_debugobj.py new file mode 100644 index 0000000000000000000000000000000000000000..90ace4e1bc4f9ef8ca24028c4c01b985412fdc6d --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_debugobj.py @@ -0,0 +1,57 @@ +"Test debugobj, coverage 40%." + +from idlelib import debugobj +import unittest + + +class ObjectTreeItemTest(unittest.TestCase): + + def test_init(self): + ti = debugobj.ObjectTreeItem('label', 22) + self.assertEqual(ti.labeltext, 'label') + self.assertEqual(ti.object, 22) + self.assertEqual(ti.setfunction, None) + + +class ClassTreeItemTest(unittest.TestCase): + + def test_isexpandable(self): + ti = debugobj.ClassTreeItem('label', 0) + self.assertTrue(ti.IsExpandable()) + + +class AtomicObjectTreeItemTest(unittest.TestCase): + + def test_isexpandable(self): + ti = debugobj.AtomicObjectTreeItem('label', 0) + self.assertFalse(ti.IsExpandable()) + + +class SequenceTreeItemTest(unittest.TestCase): + + def test_isexpandable(self): + ti = debugobj.SequenceTreeItem('label', ()) + self.assertFalse(ti.IsExpandable()) + ti = debugobj.SequenceTreeItem('label', (1,)) + self.assertTrue(ti.IsExpandable()) + + def test_keys(self): + ti = debugobj.SequenceTreeItem('label', 'abc') + self.assertEqual(list(ti.keys()), [0, 1, 2]) # keys() is a range. + + +class DictTreeItemTest(unittest.TestCase): + + def test_isexpandable(self): + ti = debugobj.DictTreeItem('label', {}) + self.assertFalse(ti.IsExpandable()) + ti = debugobj.DictTreeItem('label', {1:1}) + self.assertTrue(ti.IsExpandable()) + + def test_keys(self): + ti = debugobj.DictTreeItem('label', {1:1, 0:0, 2:2}) + self.assertEqual(ti.keys(), [0, 1, 2]) # keys() is a sorted list. + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_debugobj_r.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_debugobj_r.py new file mode 100644 index 0000000000000000000000000000000000000000..86e51b6cb2cb22d31aa9c4a1d8cc5b713b8eec34 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_debugobj_r.py @@ -0,0 +1,22 @@ +"Test debugobj_r, coverage 56%." + +from idlelib import debugobj_r +import unittest + + +class WrappedObjectTreeItemTest(unittest.TestCase): + + def test_getattr(self): + ti = debugobj_r.WrappedObjectTreeItem(list) + self.assertEqual(ti.append, list.append) + +class StubObjectTreeItemTest(unittest.TestCase): + + def test_init(self): + ti = debugobj_r.StubObjectTreeItem('socket', 1111) + self.assertEqual(ti.sockio, 'socket') + self.assertEqual(ti.oid, 1111) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_delegator.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_delegator.py new file mode 100644 index 0000000000000000000000000000000000000000..922416297a42e028bc0db33fb1f5195190b29f6e --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_delegator.py @@ -0,0 +1,44 @@ +"Test delegator, coverage 100%." + +from idlelib.delegator import Delegator +import unittest + + +class DelegatorTest(unittest.TestCase): + + def test_mydel(self): + # Test a simple use scenario. + + # Initialize an int delegator. + mydel = Delegator(int) + self.assertIs(mydel.delegate, int) + self.assertEqual(mydel._Delegator__cache, set()) + # Trying to access a non-attribute of int fails. + self.assertRaises(AttributeError, mydel.__getattr__, 'xyz') + + # Add real int attribute 'bit_length' by accessing it. + bl = mydel.bit_length + self.assertIs(bl, int.bit_length) + self.assertIs(mydel.__dict__['bit_length'], int.bit_length) + self.assertEqual(mydel._Delegator__cache, {'bit_length'}) + + # Add attribute 'numerator'. + mydel.numerator + self.assertEqual(mydel._Delegator__cache, {'bit_length', 'numerator'}) + + # Delete 'numerator'. + del mydel.numerator + self.assertNotIn('numerator', mydel.__dict__) + # The current implementation leaves it in the name cache. + # self.assertIn('numerator', mydel._Delegator__cache) + # However, this is not required and not part of the specification + + # Change delegate to float, first resetting the attributes. + mydel.setdelegate(float) # calls resetcache + self.assertNotIn('bit_length', mydel.__dict__) + self.assertEqual(mydel._Delegator__cache, set()) + self.assertIs(mydel.delegate, float) + + +if __name__ == '__main__': + unittest.main(verbosity=2, exit=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_editmenu.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_editmenu.py new file mode 100644 index 0000000000000000000000000000000000000000..17478473a3d1b2711fd8e1ffa7f6076c540c4386 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_editmenu.py @@ -0,0 +1,74 @@ +'''Test (selected) IDLE Edit menu items. + +Edit modules have their own test files +''' +from test.support import requires +requires('gui') +import tkinter as tk +from tkinter import ttk +import unittest +from idlelib import pyshell + +class PasteTest(unittest.TestCase): + '''Test pasting into widgets that allow pasting. + + On X11, replacing selections requires tk fix. + ''' + @classmethod + def setUpClass(cls): + cls.root = root = tk.Tk() + cls.root.withdraw() + pyshell.fix_x11_paste(root) + cls.text = tk.Text(root) + cls.entry = tk.Entry(root) + cls.tentry = ttk.Entry(root) + cls.spin = tk.Spinbox(root) + root.clipboard_clear() + root.clipboard_append('two') + + @classmethod + def tearDownClass(cls): + del cls.text, cls.entry, cls.tentry + cls.root.clipboard_clear() + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def test_paste_text(self): + "Test pasting into text with and without a selection." + text = self.text + for tag, ans in ('', 'onetwo\n'), ('sel', 'two\n'): + with self.subTest(tag=tag, ans=ans): + text.delete('1.0', 'end') + text.insert('1.0', 'one', tag) + text.event_generate('<>') + self.assertEqual(text.get('1.0', 'end'), ans) + + def test_paste_entry(self): + "Test pasting into an entry with and without a selection." + # Generated <> fails for tk entry without empty select + # range for 'no selection'. Live widget works fine. + for entry in self.entry, self.tentry: + for end, ans in (0, 'onetwo'), ('end', 'two'): + with self.subTest(entry=entry, end=end, ans=ans): + entry.delete(0, 'end') + entry.insert(0, 'one') + entry.select_range(0, end) + entry.event_generate('<>') + self.assertEqual(entry.get(), ans) + + def test_paste_spin(self): + "Test pasting into a spinbox with and without a selection." + # See note above for entry. + spin = self.spin + for end, ans in (0, 'onetwo'), ('end', 'two'): + with self.subTest(end=end, ans=ans): + spin.delete(0, 'end') + spin.insert(0, 'one') + spin.selection('range', 0, end) # see note + spin.event_generate('<>') + self.assertEqual(spin.get(), ans) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_editor.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_editor.py new file mode 100644 index 0000000000000000000000000000000000000000..0dfe2f3c58befadd0e85765cac1c1f29083d26fc --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_editor.py @@ -0,0 +1,241 @@ +"Test editor, coverage 53%." + +from idlelib import editor +import unittest +from collections import namedtuple +from test.support import requires +from tkinter import Tk, Text + +Editor = editor.EditorWindow + + +class EditorWindowTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + + @classmethod + def tearDownClass(cls): + cls.root.update_idletasks() + for id in cls.root.tk.call('after', 'info'): + cls.root.after_cancel(id) + cls.root.destroy() + del cls.root + + def test_init(self): + e = Editor(root=self.root) + self.assertEqual(e.root, self.root) + e._close() + + +class GetLineIndentTest(unittest.TestCase): + def test_empty_lines(self): + for tabwidth in [1, 2, 4, 6, 8]: + for line in ['', '\n']: + with self.subTest(line=line, tabwidth=tabwidth): + self.assertEqual( + editor.get_line_indent(line, tabwidth=tabwidth), + (0, 0), + ) + + def test_tabwidth_4(self): + # (line, (raw, effective)) + tests = (('no spaces', (0, 0)), + # Internal space isn't counted. + (' space test', (4, 4)), + ('\ttab test', (1, 4)), + ('\t\tdouble tabs test', (2, 8)), + # Different results when mixing tabs and spaces. + (' \tmixed test', (5, 8)), + (' \t mixed test', (5, 6)), + ('\t mixed test', (5, 8)), + # Spaces not divisible by tabwidth. + (' \tmixed test', (3, 4)), + (' \t mixed test', (3, 5)), + ('\t mixed test', (3, 6)), + # Only checks spaces and tabs. + ('\nnewline test', (0, 0))) + + for line, expected in tests: + with self.subTest(line=line): + self.assertEqual( + editor.get_line_indent(line, tabwidth=4), + expected, + ) + + def test_tabwidth_8(self): + # (line, (raw, effective)) + tests = (('no spaces', (0, 0)), + # Internal space isn't counted. + (' space test', (8, 8)), + ('\ttab test', (1, 8)), + ('\t\tdouble tabs test', (2, 16)), + # Different results when mixing tabs and spaces. + (' \tmixed test', (9, 16)), + (' \t mixed test', (9, 10)), + ('\t mixed test', (9, 16)), + # Spaces not divisible by tabwidth. + (' \tmixed test', (3, 8)), + (' \t mixed test', (3, 9)), + ('\t mixed test', (3, 10)), + # Only checks spaces and tabs. + ('\nnewline test', (0, 0))) + + for line, expected in tests: + with self.subTest(line=line): + self.assertEqual( + editor.get_line_indent(line, tabwidth=8), + expected, + ) + + +def insert(text, string): + text.delete('1.0', 'end') + text.insert('end', string) + text.update_idletasks() # Force update for colorizer to finish. + + +class IndentAndNewlineTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.window = Editor(root=cls.root) + cls.window.indentwidth = 2 + cls.window.tabwidth = 2 + + @classmethod + def tearDownClass(cls): + cls.window._close() + del cls.window + cls.root.update_idletasks() + for id in cls.root.tk.call('after', 'info'): + cls.root.after_cancel(id) + cls.root.destroy() + del cls.root + + def test_indent_and_newline_event(self): + eq = self.assertEqual + w = self.window + text = w.text + get = text.get + nl = w.newline_and_indent_event + + TestInfo = namedtuple('Tests', ['label', 'text', 'expected', 'mark']) + + tests = (TestInfo('Empty line inserts with no indent.', + ' \n def __init__(self):', + '\n \n def __init__(self):\n', + '1.end'), + TestInfo('Inside bracket before space, deletes space.', + ' def f1(self, a, b):', + ' def f1(self,\n a, b):\n', + '1.14'), + TestInfo('Inside bracket after space, deletes space.', + ' def f1(self, a, b):', + ' def f1(self,\n a, b):\n', + '1.15'), + TestInfo('Inside string with one line - no indent.', + ' """Docstring."""', + ' """Docstring.\n"""\n', + '1.15'), + TestInfo('Inside string with more than one line.', + ' """Docstring.\n Docstring Line 2"""', + ' """Docstring.\n Docstring Line 2\n """\n', + '2.18'), + TestInfo('Backslash with one line.', + 'a =\\', + 'a =\\\n \n', + '1.end'), + TestInfo('Backslash with more than one line.', + 'a =\\\n multiline\\', + 'a =\\\n multiline\\\n \n', + '2.end'), + TestInfo('Block opener - indents +1 level.', + ' def f1(self):\n pass', + ' def f1(self):\n \n pass\n', + '1.end'), + TestInfo('Block closer - dedents -1 level.', + ' def f1(self):\n pass', + ' def f1(self):\n pass\n \n', + '2.end'), + ) + + for test in tests: + with self.subTest(label=test.label): + insert(text, test.text) + text.mark_set('insert', test.mark) + nl(event=None) + eq(get('1.0', 'end'), test.expected) + + # Selected text. + insert(text, ' def f1(self, a, b):\n return a + b') + text.tag_add('sel', '1.17', '1.end') + nl(None) + # Deletes selected text before adding new line. + eq(get('1.0', 'end'), ' def f1(self, a,\n \n return a + b\n') + + +class IndentSearcherTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.text = Text(cls.root) + + @classmethod + def tearDownClass(cls): + cls.root.destroy() + del cls.root + + def test_searcher(self): + text = self.text + searcher = (self.text) + test_info = (# text, (block, indent)) + ("", (None, None)), + ("[1,", (None, None)), # TokenError + ("if 1:\n", ('if 1:\n', None)), + ("if 1:\n 2\n 3\n", ('if 1:\n', ' 2\n')), + ) + for code, expected_pair in test_info: + with self.subTest(code=code): + insert(text, code) + actual_pair = editor.IndentSearcher(text).run() + self.assertEqual(actual_pair, expected_pair) + + +class RMenuTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.window = Editor(root=cls.root) + + @classmethod + def tearDownClass(cls): + cls.window._close() + del cls.window + cls.root.update_idletasks() + for id in cls.root.tk.call('after', 'info'): + cls.root.after_cancel(id) + cls.root.destroy() + del cls.root + + class DummyRMenu: + def tk_popup(x, y): pass + + def test_rclick(self): + pass + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_filelist.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_filelist.py new file mode 100644 index 0000000000000000000000000000000000000000..731f1975e50e23907f60764c0c149f101c6fe898 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_filelist.py @@ -0,0 +1,33 @@ +"Test filelist, coverage 19%." + +from idlelib import filelist +import unittest +from test.support import requires +from tkinter import Tk + +class FileListTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + + @classmethod + def tearDownClass(cls): + cls.root.update_idletasks() + for id in cls.root.tk.call('after', 'info'): + cls.root.after_cancel(id) + cls.root.destroy() + del cls.root + + def test_new_empty(self): + flist = filelist.FileList(self.root) + self.assertEqual(flist.root, self.root) + e = flist.new() + self.assertEqual(type(e), flist.EditorWindow) + e._close() + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_format.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_format.py new file mode 100644 index 0000000000000000000000000000000000000000..e5e903688597aa770452f15102f9ee7850ace49e --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_format.py @@ -0,0 +1,668 @@ +"Test format, coverage 99%." + +from idlelib import format as ft +import unittest +from unittest import mock +from test.support import requires +from tkinter import Tk, Text +from idlelib.editor import EditorWindow +from idlelib.idle_test.mock_idle import Editor as MockEditor + + +class Is_Get_Test(unittest.TestCase): + """Test the is_ and get_ functions""" + test_comment = '# This is a comment' + test_nocomment = 'This is not a comment' + trailingws_comment = '# This is a comment ' + leadingws_comment = ' # This is a comment' + leadingws_nocomment = ' This is not a comment' + + def test_is_all_white(self): + self.assertTrue(ft.is_all_white('')) + self.assertTrue(ft.is_all_white('\t\n\r\f\v')) + self.assertFalse(ft.is_all_white(self.test_comment)) + + def test_get_indent(self): + Equal = self.assertEqual + Equal(ft.get_indent(self.test_comment), '') + Equal(ft.get_indent(self.trailingws_comment), '') + Equal(ft.get_indent(self.leadingws_comment), ' ') + Equal(ft.get_indent(self.leadingws_nocomment), ' ') + + def test_get_comment_header(self): + Equal = self.assertEqual + # Test comment strings + Equal(ft.get_comment_header(self.test_comment), '#') + Equal(ft.get_comment_header(self.trailingws_comment), '#') + Equal(ft.get_comment_header(self.leadingws_comment), ' #') + # Test non-comment strings + Equal(ft.get_comment_header(self.leadingws_nocomment), ' ') + Equal(ft.get_comment_header(self.test_nocomment), '') + + +class FindTest(unittest.TestCase): + """Test the find_paragraph function in paragraph module. + + Using the runcase() function, find_paragraph() is called with 'mark' set at + multiple indexes before and inside the test paragraph. + + It appears that code with the same indentation as a quoted string is grouped + as part of the same paragraph, which is probably incorrect behavior. + """ + + @classmethod + def setUpClass(cls): + from idlelib.idle_test.mock_tk import Text + cls.text = Text() + + def runcase(self, inserttext, stopline, expected): + # Check that find_paragraph returns the expected paragraph when + # the mark index is set to beginning, middle, end of each line + # up to but not including the stop line + text = self.text + text.insert('1.0', inserttext) + for line in range(1, stopline): + linelength = int(text.index("%d.end" % line).split('.')[1]) + for col in (0, linelength//2, linelength): + tempindex = "%d.%d" % (line, col) + self.assertEqual(ft.find_paragraph(text, tempindex), expected) + text.delete('1.0', 'end') + + def test_find_comment(self): + comment = ( + "# Comment block with no blank lines before\n" + "# Comment line\n" + "\n") + self.runcase(comment, 3, ('1.0', '3.0', '#', comment[0:58])) + + comment = ( + "\n" + "# Comment block with whitespace line before and after\n" + "# Comment line\n" + "\n") + self.runcase(comment, 4, ('2.0', '4.0', '#', comment[1:70])) + + comment = ( + "\n" + " # Indented comment block with whitespace before and after\n" + " # Comment line\n" + "\n") + self.runcase(comment, 4, ('2.0', '4.0', ' #', comment[1:82])) + + comment = ( + "\n" + "# Single line comment\n" + "\n") + self.runcase(comment, 3, ('2.0', '3.0', '#', comment[1:23])) + + comment = ( + "\n" + " # Single line comment with leading whitespace\n" + "\n") + self.runcase(comment, 3, ('2.0', '3.0', ' #', comment[1:51])) + + comment = ( + "\n" + "# Comment immediately followed by code\n" + "x = 42\n" + "\n") + self.runcase(comment, 3, ('2.0', '3.0', '#', comment[1:40])) + + comment = ( + "\n" + " # Indented comment immediately followed by code\n" + "x = 42\n" + "\n") + self.runcase(comment, 3, ('2.0', '3.0', ' #', comment[1:53])) + + comment = ( + "\n" + "# Comment immediately followed by indented code\n" + " x = 42\n" + "\n") + self.runcase(comment, 3, ('2.0', '3.0', '#', comment[1:49])) + + def test_find_paragraph(self): + teststring = ( + '"""String with no blank lines before\n' + 'String line\n' + '"""\n' + '\n') + self.runcase(teststring, 4, ('1.0', '4.0', '', teststring[0:53])) + + teststring = ( + "\n" + '"""String with whitespace line before and after\n' + 'String line.\n' + '"""\n' + '\n') + self.runcase(teststring, 5, ('2.0', '5.0', '', teststring[1:66])) + + teststring = ( + '\n' + ' """Indented string with whitespace before and after\n' + ' Comment string.\n' + ' """\n' + '\n') + self.runcase(teststring, 5, ('2.0', '5.0', ' ', teststring[1:85])) + + teststring = ( + '\n' + '"""Single line string."""\n' + '\n') + self.runcase(teststring, 3, ('2.0', '3.0', '', teststring[1:27])) + + teststring = ( + '\n' + ' """Single line string with leading whitespace."""\n' + '\n') + self.runcase(teststring, 3, ('2.0', '3.0', ' ', teststring[1:55])) + + +class ReformatFunctionTest(unittest.TestCase): + """Test the reformat_paragraph function without the editor window.""" + + def test_reformat_paragraph(self): + Equal = self.assertEqual + reform = ft.reformat_paragraph + hw = "O hello world" + Equal(reform(' ', 1), ' ') + Equal(reform("Hello world", 20), "Hello world") + + # Test without leading newline + Equal(reform(hw, 1), "O\nhello\nworld") + Equal(reform(hw, 6), "O\nhello\nworld") + Equal(reform(hw, 7), "O hello\nworld") + Equal(reform(hw, 12), "O hello\nworld") + Equal(reform(hw, 13), "O hello world") + + # Test with leading newline + hw = "\nO hello world" + Equal(reform(hw, 1), "\nO\nhello\nworld") + Equal(reform(hw, 6), "\nO\nhello\nworld") + Equal(reform(hw, 7), "\nO hello\nworld") + Equal(reform(hw, 12), "\nO hello\nworld") + Equal(reform(hw, 13), "\nO hello world") + + +class ReformatCommentTest(unittest.TestCase): + """Test the reformat_comment function without the editor window.""" + + def test_reformat_comment(self): + Equal = self.assertEqual + + # reformat_comment formats to a minimum of 20 characters + test_string = ( + " \"\"\"this is a test of a reformat for a triple quoted string" + " will it reformat to less than 70 characters for me?\"\"\"") + result = ft.reformat_comment(test_string, 70, " ") + expected = ( + " \"\"\"this is a test of a reformat for a triple quoted string will it\n" + " reformat to less than 70 characters for me?\"\"\"") + Equal(result, expected) + + test_comment = ( + "# this is a test of a reformat for a triple quoted string will " + "it reformat to less than 70 characters for me?") + result = ft.reformat_comment(test_comment, 70, "#") + expected = ( + "# this is a test of a reformat for a triple quoted string will it\n" + "# reformat to less than 70 characters for me?") + Equal(result, expected) + + +class FormatClassTest(unittest.TestCase): + def test_init_close(self): + instance = ft.FormatParagraph('editor') + self.assertEqual(instance.editwin, 'editor') + instance.close() + self.assertEqual(instance.editwin, None) + + +# For testing format_paragraph_event, Initialize FormatParagraph with +# a mock Editor with .text and .get_selection_indices. The text must +# be a Text wrapper that adds two methods + +# A real EditorWindow creates unneeded, time-consuming baggage and +# sometimes emits shutdown warnings like this: +# "warning: callback failed in WindowList +# : invalid command name ".55131368.windows". +# Calling EditorWindow._close in tearDownClass prevents this but causes +# other problems (windows left open). + +class TextWrapper: + def __init__(self, master): + self.text = Text(master=master) + def __getattr__(self, name): + return getattr(self.text, name) + def undo_block_start(self): pass + def undo_block_stop(self): pass + +class Editor: + def __init__(self, root): + self.text = TextWrapper(root) + get_selection_indices = EditorWindow. get_selection_indices + +class FormatEventTest(unittest.TestCase): + """Test the formatting of text inside a Text widget. + + This is done with FormatParagraph.format.paragraph_event, + which calls functions in the module as appropriate. + """ + test_string = ( + " '''this is a test of a reformat for a triple " + "quoted string will it reformat to less than 70 " + "characters for me?'''\n") + multiline_test_string = ( + " '''The first line is under the max width.\n" + " The second line's length is way over the max width. It goes " + "on and on until it is over 100 characters long.\n" + " Same thing with the third line. It is also way over the max " + "width, but FormatParagraph will fix it.\n" + " '''\n") + multiline_test_comment = ( + "# The first line is under the max width.\n" + "# The second line's length is way over the max width. It goes on " + "and on until it is over 100 characters long.\n" + "# Same thing with the third line. It is also way over the max " + "width, but FormatParagraph will fix it.\n" + "# The fourth line is short like the first line.") + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + editor = Editor(root=cls.root) + cls.text = editor.text.text # Test code does not need the wrapper. + cls.formatter = ft.FormatParagraph(editor).format_paragraph_event + # Sets the insert mark just after the re-wrapped and inserted text. + + @classmethod + def tearDownClass(cls): + del cls.text, cls.formatter + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def test_short_line(self): + self.text.insert('1.0', "Short line\n") + self.formatter("Dummy") + self.assertEqual(self.text.get('1.0', 'insert'), "Short line\n" ) + self.text.delete('1.0', 'end') + + def test_long_line(self): + text = self.text + + # Set cursor ('insert' mark) to '1.0', within text. + text.insert('1.0', self.test_string) + text.mark_set('insert', '1.0') + self.formatter('ParameterDoesNothing', limit=70) + result = text.get('1.0', 'insert') + # find function includes \n + expected = ( +" '''this is a test of a reformat for a triple quoted string will it\n" +" reformat to less than 70 characters for me?'''\n") # yes + self.assertEqual(result, expected) + text.delete('1.0', 'end') + + # Select from 1.11 to line end. + text.insert('1.0', self.test_string) + text.tag_add('sel', '1.11', '1.end') + self.formatter('ParameterDoesNothing', limit=70) + result = text.get('1.0', 'insert') + # selection excludes \n + expected = ( +" '''this is a test of a reformat for a triple quoted string will it reformat\n" +" to less than 70 characters for me?'''") # no + self.assertEqual(result, expected) + text.delete('1.0', 'end') + + def test_multiple_lines(self): + text = self.text + # Select 2 long lines. + text.insert('1.0', self.multiline_test_string) + text.tag_add('sel', '2.0', '4.0') + self.formatter('ParameterDoesNothing', limit=70) + result = text.get('2.0', 'insert') + expected = ( +" The second line's length is way over the max width. It goes on and\n" +" on until it is over 100 characters long. Same thing with the third\n" +" line. It is also way over the max width, but FormatParagraph will\n" +" fix it.\n") + self.assertEqual(result, expected) + text.delete('1.0', 'end') + + def test_comment_block(self): + text = self.text + + # Set cursor ('insert') to '1.0', within block. + text.insert('1.0', self.multiline_test_comment) + self.formatter('ParameterDoesNothing', limit=70) + result = text.get('1.0', 'insert') + expected = ( +"# The first line is under the max width. The second line's length is\n" +"# way over the max width. It goes on and on until it is over 100\n" +"# characters long. Same thing with the third line. It is also way over\n" +"# the max width, but FormatParagraph will fix it. The fourth line is\n" +"# short like the first line.\n") + self.assertEqual(result, expected) + text.delete('1.0', 'end') + + # Select line 2, verify line 1 unaffected. + text.insert('1.0', self.multiline_test_comment) + text.tag_add('sel', '2.0', '3.0') + self.formatter('ParameterDoesNothing', limit=70) + result = text.get('1.0', 'insert') + expected = ( +"# The first line is under the max width.\n" +"# The second line's length is way over the max width. It goes on and\n" +"# on until it is over 100 characters long.\n") + self.assertEqual(result, expected) + text.delete('1.0', 'end') + +# The following block worked with EditorWindow but fails with the mock. +# Lines 2 and 3 get pasted together even though the previous block left +# the previous line alone. More investigation is needed. +## # Select lines 3 and 4 +## text.insert('1.0', self.multiline_test_comment) +## text.tag_add('sel', '3.0', '5.0') +## self.formatter('ParameterDoesNothing') +## result = text.get('3.0', 'insert') +## expected = ( +##"# Same thing with the third line. It is also way over the max width,\n" +##"# but FormatParagraph will fix it. The fourth line is short like the\n" +##"# first line.\n") +## self.assertEqual(result, expected) +## text.delete('1.0', 'end') + + +class DummyEditwin: + def __init__(self, root, text): + self.root = root + self.text = text + self.indentwidth = 4 + self.tabwidth = 4 + self.usetabs = False + self.context_use_ps1 = True + + _make_blanks = EditorWindow._make_blanks + get_selection_indices = EditorWindow.get_selection_indices + + +class FormatRegionTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.text = Text(cls.root) + cls.text.undo_block_start = mock.Mock() + cls.text.undo_block_stop = mock.Mock() + cls.editor = DummyEditwin(cls.root, cls.text) + cls.formatter = ft.FormatRegion(cls.editor) + + @classmethod + def tearDownClass(cls): + del cls.text, cls.formatter, cls.editor + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def setUp(self): + self.text.insert('1.0', self.code_sample) + + def tearDown(self): + self.text.delete('1.0', 'end') + + code_sample = """\ +# WS line needed for test. +class C1: + # Class comment. + def __init__(self, a, b): + self.a = a + self.b = b + + def compare(self): + if a > b: + return a + elif a < b: + return b + else: + return None +""" + + def test_get_region(self): + get = self.formatter.get_region + text = self.text + eq = self.assertEqual + + # Add selection. + text.tag_add('sel', '7.0', '10.0') + expected_lines = ['', + ' def compare(self):', + ' if a > b:', + ''] + eq(get(), ('7.0', '10.0', '\n'.join(expected_lines), expected_lines)) + + # Remove selection. + text.tag_remove('sel', '1.0', 'end') + eq(get(), ('15.0', '16.0', '\n', ['', ''])) + + def test_set_region(self): + set_ = self.formatter.set_region + text = self.text + eq = self.assertEqual + + save_bell = text.bell + text.bell = mock.Mock() + line6 = self.code_sample.splitlines()[5] + line10 = self.code_sample.splitlines()[9] + + text.tag_add('sel', '6.0', '11.0') + head, tail, chars, lines = self.formatter.get_region() + + # No changes. + set_(head, tail, chars, lines) + text.bell.assert_called_once() + eq(text.get('6.0', '11.0'), chars) + eq(text.get('sel.first', 'sel.last'), chars) + text.tag_remove('sel', '1.0', 'end') + + # Alter selected lines by changing lines and adding a newline. + newstring = 'added line 1\n\n\n\n' + newlines = newstring.split('\n') + set_('7.0', '10.0', chars, newlines) + # Selection changed. + eq(text.get('sel.first', 'sel.last'), newstring) + # Additional line added, so last index is changed. + eq(text.get('7.0', '11.0'), newstring) + # Before and after lines unchanged. + eq(text.get('6.0', '7.0-1c'), line6) + eq(text.get('11.0', '12.0-1c'), line10) + text.tag_remove('sel', '1.0', 'end') + + text.bell = save_bell + + def test_indent_region_event(self): + indent = self.formatter.indent_region_event + text = self.text + eq = self.assertEqual + + text.tag_add('sel', '7.0', '10.0') + indent() + # Blank lines aren't affected by indent. + eq(text.get('7.0', '10.0'), ('\n def compare(self):\n if a > b:\n')) + + def test_dedent_region_event(self): + dedent = self.formatter.dedent_region_event + text = self.text + eq = self.assertEqual + + text.tag_add('sel', '7.0', '10.0') + dedent() + # Blank lines aren't affected by dedent. + eq(text.get('7.0', '10.0'), ('\ndef compare(self):\n if a > b:\n')) + + def test_comment_region_event(self): + comment = self.formatter.comment_region_event + text = self.text + eq = self.assertEqual + + text.tag_add('sel', '7.0', '10.0') + comment() + eq(text.get('7.0', '10.0'), ('##\n## def compare(self):\n## if a > b:\n')) + + def test_uncomment_region_event(self): + comment = self.formatter.comment_region_event + uncomment = self.formatter.uncomment_region_event + text = self.text + eq = self.assertEqual + + text.tag_add('sel', '7.0', '10.0') + comment() + uncomment() + eq(text.get('7.0', '10.0'), ('\n def compare(self):\n if a > b:\n')) + + # Only remove comments at the beginning of a line. + text.tag_remove('sel', '1.0', 'end') + text.tag_add('sel', '3.0', '4.0') + uncomment() + eq(text.get('3.0', '3.end'), (' # Class comment.')) + + self.formatter.set_region('3.0', '4.0', '', ['# Class comment.', '']) + uncomment() + eq(text.get('3.0', '3.end'), (' Class comment.')) + + @mock.patch.object(ft.FormatRegion, "_asktabwidth") + def test_tabify_region_event(self, _asktabwidth): + tabify = self.formatter.tabify_region_event + text = self.text + eq = self.assertEqual + + text.tag_add('sel', '7.0', '10.0') + # No tabwidth selected. + _asktabwidth.return_value = None + self.assertIsNone(tabify()) + + _asktabwidth.return_value = 3 + self.assertIsNotNone(tabify()) + eq(text.get('7.0', '10.0'), ('\n\t def compare(self):\n\t\t if a > b:\n')) + + @mock.patch.object(ft.FormatRegion, "_asktabwidth") + def test_untabify_region_event(self, _asktabwidth): + untabify = self.formatter.untabify_region_event + text = self.text + eq = self.assertEqual + + text.tag_add('sel', '7.0', '10.0') + # No tabwidth selected. + _asktabwidth.return_value = None + self.assertIsNone(untabify()) + + _asktabwidth.return_value = 2 + self.formatter.tabify_region_event() + _asktabwidth.return_value = 3 + self.assertIsNotNone(untabify()) + eq(text.get('7.0', '10.0'), ('\n def compare(self):\n if a > b:\n')) + + @mock.patch.object(ft, "askinteger") + def test_ask_tabwidth(self, askinteger): + ask = self.formatter._asktabwidth + askinteger.return_value = 10 + self.assertEqual(ask(), 10) + + +class IndentsTest(unittest.TestCase): + + @mock.patch.object(ft, "askyesno") + def test_toggle_tabs(self, askyesno): + editor = DummyEditwin(None, None) # usetabs == False. + indents = ft.Indents(editor) + askyesno.return_value = True + + indents.toggle_tabs_event(None) + self.assertEqual(editor.usetabs, True) + self.assertEqual(editor.indentwidth, 8) + + indents.toggle_tabs_event(None) + self.assertEqual(editor.usetabs, False) + self.assertEqual(editor.indentwidth, 8) + + @mock.patch.object(ft, "askinteger") + def test_change_indentwidth(self, askinteger): + editor = DummyEditwin(None, None) # indentwidth == 4. + indents = ft.Indents(editor) + + askinteger.return_value = None + indents.change_indentwidth_event(None) + self.assertEqual(editor.indentwidth, 4) + + askinteger.return_value = 3 + indents.change_indentwidth_event(None) + self.assertEqual(editor.indentwidth, 3) + + askinteger.return_value = 5 + editor.usetabs = True + indents.change_indentwidth_event(None) + self.assertEqual(editor.indentwidth, 3) + + +class RstripTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.text = Text(cls.root) + cls.editor = MockEditor(text=cls.text) + cls.do_rstrip = ft.Rstrip(cls.editor).do_rstrip + + @classmethod + def tearDownClass(cls): + del cls.text, cls.do_rstrip, cls.editor + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def tearDown(self): + self.text.delete('1.0', 'end-1c') + + def test_rstrip_lines(self): + original = ( + "Line with an ending tab \n" + "Line ending in 5 spaces \n" + "Linewithnospaces\n" + " indented line\n" + " indented line with trailing space \n" + " \n") + stripped = ( + "Line with an ending tab\n" + "Line ending in 5 spaces\n" + "Linewithnospaces\n" + " indented line\n" + " indented line with trailing space\n") + + self.text.insert('1.0', original) + self.do_rstrip() + self.assertEqual(self.text.get('1.0', 'insert'), stripped) + + def test_rstrip_end(self): + text = self.text + for code in ('', '\n', '\n\n\n'): + with self.subTest(code=code): + text.insert('1.0', code) + self.do_rstrip() + self.assertEqual(text.get('1.0','end-1c'), '') + for code in ('a\n', 'a\n\n', 'a\n\n\n'): + with self.subTest(code=code): + text.delete('1.0', 'end-1c') + text.insert('1.0', code) + self.do_rstrip() + self.assertEqual(text.get('1.0','end-1c'), 'a\n') + + +if __name__ == '__main__': + unittest.main(verbosity=2, exit=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_grep.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_grep.py new file mode 100644 index 0000000000000000000000000000000000000000..ad0a813e71d7b8699682a7228405938d1e93d74a --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_grep.py @@ -0,0 +1,157 @@ +""" !Changing this line will break Test_findfile.test_found! +Non-gui unit tests for grep.GrepDialog methods. +dummy_command calls grep_it calls findfiles. +An exception raised in one method will fail callers. +Otherwise, tests are mostly independent. +Currently only test grep_it, coverage 51%. +""" +from idlelib import grep +import unittest +from test.support import captured_stdout +from test.support.testcase import ExtraAssertions +from idlelib.idle_test.mock_tk import Var +import os +import re + + +class Dummy_searchengine: + '''GrepDialog.__init__ calls parent SearchDiabolBase which attaches the + passed in SearchEngine instance as attribute 'engine'. Only a few of the + many possible self.engine.x attributes are needed here. + ''' + def getpat(self): + return self._pat + +searchengine = Dummy_searchengine() + + +class Dummy_grep: + # Methods tested + #default_command = GrepDialog.default_command + grep_it = grep.GrepDialog.grep_it + # Other stuff needed + recvar = Var(False) + engine = searchengine + def close(self): # gui method + pass + +_grep = Dummy_grep() + + +class FindfilesTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + cls.realpath = os.path.realpath(__file__) + cls.path = os.path.dirname(cls.realpath) + + @classmethod + def tearDownClass(cls): + del cls.realpath, cls.path + + def test_invaliddir(self): + with captured_stdout() as s: + filelist = list(grep.findfiles('invaliddir', '*.*', False)) + self.assertEqual(filelist, []) + self.assertIn('invalid', s.getvalue()) + + def test_curdir(self): + # Test os.curdir. + ff = grep.findfiles + save_cwd = os.getcwd() + os.chdir(self.path) + filename = 'test_grep.py' + filelist = list(ff(os.curdir, filename, False)) + self.assertIn(os.path.join(os.curdir, filename), filelist) + os.chdir(save_cwd) + + def test_base(self): + ff = grep.findfiles + readme = os.path.join(self.path, 'README.txt') + + # Check for Python files in path where this file lives. + filelist = list(ff(self.path, '*.py', False)) + # This directory has many Python files. + self.assertGreater(len(filelist), 10) + self.assertIn(self.realpath, filelist) + self.assertNotIn(readme, filelist) + + # Look for .txt files in path where this file lives. + filelist = list(ff(self.path, '*.txt', False)) + self.assertNotEqual(len(filelist), 0) + self.assertNotIn(self.realpath, filelist) + self.assertIn(readme, filelist) + + # Look for non-matching pattern. + filelist = list(ff(self.path, 'grep.*', False)) + self.assertEqual(len(filelist), 0) + self.assertNotIn(self.realpath, filelist) + + def test_recurse(self): + ff = grep.findfiles + parent = os.path.dirname(self.path) + grepfile = os.path.join(parent, 'grep.py') + pat = '*.py' + + # Get Python files only in parent directory. + filelist = list(ff(parent, pat, False)) + parent_size = len(filelist) + # Lots of Python files in idlelib. + self.assertGreater(parent_size, 20) + self.assertIn(grepfile, filelist) + # Without subdirectories, this file isn't returned. + self.assertNotIn(self.realpath, filelist) + + # Include subdirectories. + filelist = list(ff(parent, pat, True)) + # More files found now. + self.assertGreater(len(filelist), parent_size) + self.assertIn(grepfile, filelist) + # This file exists in list now. + self.assertIn(self.realpath, filelist) + + # Check another level up the tree. + parent = os.path.dirname(parent) + filelist = list(ff(parent, '*.py', True)) + self.assertIn(self.realpath, filelist) + + +class Grep_itTest(unittest.TestCase, ExtraAssertions): + # Test captured reports with 0 and some hits. + # Should test file names, but Windows reports have mixed / and \ separators + # from incomplete replacement, so 'later'. + + def report(self, pat): + _grep.engine._pat = pat + with captured_stdout() as s: + _grep.grep_it(re.compile(pat), __file__) + lines = s.getvalue().split('\n') + lines.pop() # remove bogus '' after last \n + return lines + + def test_unfound(self): + pat = 'xyz*'*7 + lines = self.report(pat) + self.assertEqual(len(lines), 2) + self.assertIn(pat, lines[0]) + self.assertEqual(lines[1], 'No hits.') + + def test_found(self): + + pat = '""" !Changing this line will break Test_findfile.test_found!' + lines = self.report(pat) + self.assertEqual(len(lines), 5) + self.assertIn(pat, lines[0]) + self.assertIn('py: 1:', lines[1]) # line number 1 + self.assertIn('2', lines[3]) # hits found 2 + self.assertStartsWith(lines[4], '(Hint:') + + +class Default_commandTest(unittest.TestCase): + # To write this, move outwin import to top of GrepDialog + # so it can be replaced by captured_stdout in class setup/teardown. + pass + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_help.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_help.py new file mode 100644 index 0000000000000000000000000000000000000000..ebb02b5c0d8356a89c70acc64de226064ef7e63d --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_help.py @@ -0,0 +1,36 @@ +"Test help, coverage 94%." + +from idlelib import help +import unittest +from test.support import requires +requires('gui') +from os.path import abspath, dirname, join +from tkinter import Tk + + +class IdleDocTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + "By itself, this tests that file parsed without exception." + cls.root = root = Tk() + root.withdraw() + cls.window = help.show_idlehelp(root) + + @classmethod + def tearDownClass(cls): + del cls.window + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def test_1window(self): + self.assertIn('IDLE Doc', self.window.wm_title()) + + def test_4text(self): + text = self.window.frame.text + self.assertEqual(text.get('1.0', '1.end'), ' IDLE — Python editor and shell ') + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_help_about.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_help_about.py new file mode 100644 index 0000000000000000000000000000000000000000..7e16abdb7c9f96f1a939ec0d27f0cb426922f6d9 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_help_about.py @@ -0,0 +1,182 @@ +"""Test help_about, coverage 100%. +help_about.build_bits branches on sys.platform='darwin'. +'100% combines coverage on Mac and others. +""" + +from idlelib import help_about +import unittest +from test.support import requires, findfile +from tkinter import Tk, TclError +from idlelib.idle_test.mock_idle import Func +from idlelib.idle_test.mock_tk import Mbox_func +from idlelib import textview +import os.path +from platform import python_version + +About = help_about.AboutDialog + + +class LiveDialogTest(unittest.TestCase): + """Simulate user clicking buttons other than [Close]. + + Test that invoked textview has text from source. + """ + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.dialog = About(cls.root, 'About IDLE', _utest=True) + + @classmethod + def tearDownClass(cls): + del cls.dialog + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def test_build_bits(self): + self.assertIn(help_about.bits, ('32', '64')) + + def test_dialog_title(self): + """Test about dialog title""" + self.assertEqual(self.dialog.title(), 'About IDLE') + + def test_dialog_logo(self): + """Test about dialog logo.""" + path, file = os.path.split(self.dialog.icon_image['file']) + fn, ext = os.path.splitext(file) + self.assertEqual(fn, 'idle_48') + + def test_printer_buttons(self): + """Test buttons whose commands use printer function.""" + dialog = self.dialog + button_sources = [(dialog.py_license, license, 'license'), + (dialog.py_copyright, copyright, 'copyright'), + (dialog.py_credits, credits, 'credits')] + + for button, printer, name in button_sources: + with self.subTest(name=name): + printer._Printer__setup() + button.invoke() + get = dialog._current_textview.viewframe.textframe.text.get + lines = printer._Printer__lines + if len(lines) < 2: + self.fail(name + ' full text was not found') + self.assertEqual(lines[0], get('1.0', '1.end')) + self.assertEqual(lines[1], get('2.0', '2.end')) + dialog._current_textview.destroy() + + def test_file_buttons(self): + """Test buttons that display files.""" + dialog = self.dialog + button_sources = [(self.dialog.readme, 'README.txt', 'readme'), + (self.dialog.idle_news, 'News3.txt', 'news'), + (self.dialog.idle_credits, 'CREDITS.txt', 'credits')] + + for button, filename, name in button_sources: + with self.subTest(name=name): + button.invoke() + fn = findfile(filename, subdir='idlelib') + get = dialog._current_textview.viewframe.textframe.text.get + with open(fn, encoding='utf-8') as f: + self.assertEqual(f.readline().strip(), get('1.0', '1.end')) + f.readline() + self.assertEqual(f.readline().strip(), get('3.0', '3.end')) + dialog._current_textview.destroy() + + +class DefaultTitleTest(unittest.TestCase): + "Test default title." + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.dialog = About(cls.root, _utest=True) + + @classmethod + def tearDownClass(cls): + del cls.dialog + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def test_dialog_title(self): + """Test about dialog title""" + self.assertEqual(self.dialog.title(), + f'About IDLE {python_version()}' + f' ({help_about.bits} bit)') + + +class CloseTest(unittest.TestCase): + """Simulate user clicking [Close] button""" + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.dialog = About(cls.root, 'About IDLE', _utest=True) + + @classmethod + def tearDownClass(cls): + del cls.dialog + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def test_close(self): + self.assertEqual(self.dialog.winfo_class(), 'Toplevel') + self.dialog.button_ok.invoke() + with self.assertRaises(TclError): + self.dialog.winfo_class() + + +class Dummy_about_dialog: + # Dummy class for testing file display functions. + idle_credits = About.show_idle_credits + idle_readme = About.show_readme + idle_news = About.show_idle_news + # Called by the above + display_file_text = About.display_file_text + _utest = True + + +class DisplayFileTest(unittest.TestCase): + """Test functions that display files. + + While somewhat redundant with gui-based test_file_dialog, + these unit tests run on all buildbots, not just a few. + """ + dialog = Dummy_about_dialog() + + @classmethod + def setUpClass(cls): + cls.orig_error = textview.showerror + cls.orig_view = textview.view_text + cls.error = Mbox_func() + cls.view = Func() + textview.showerror = cls.error + textview.view_text = cls.view + + @classmethod + def tearDownClass(cls): + textview.showerror = cls.orig_error + textview.view_text = cls.orig_view + + def test_file_display(self): + for handler in (self.dialog.idle_credits, + self.dialog.idle_readme, + self.dialog.idle_news): + self.error.message = '' + self.view.called = False + with self.subTest(handler=handler): + handler() + self.assertEqual(self.error.message, '') + self.assertEqual(self.view.called, True) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_history.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_history.py new file mode 100644 index 0000000000000000000000000000000000000000..675396514447514ff9c6811d095fe054fef589b0 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_history.py @@ -0,0 +1,172 @@ +" Test history, coverage 100%." + +from idlelib.history import History +import unittest +from test.support import requires + +import tkinter as tk +from tkinter import Text as tkText +from idlelib.idle_test.mock_tk import Text as mkText +from idlelib.config import idleConf + +line1 = 'a = 7' +line2 = 'b = a' + + +class StoreTest(unittest.TestCase): + '''Tests History.__init__ and History.store with mock Text''' + + @classmethod + def setUpClass(cls): + cls.text = mkText() + cls.history = History(cls.text) + + def tearDown(self): + self.text.delete('1.0', 'end') + self.history.history = [] + + def test_init(self): + self.assertIs(self.history.text, self.text) + self.assertEqual(self.history.history, []) + self.assertIsNone(self.history.prefix) + self.assertIsNone(self.history.pointer) + self.assertEqual(self.history.cyclic, + idleConf.GetOption("main", "History", "cyclic", 1, "bool")) + + def test_store_short(self): + self.history.store('a') + self.assertEqual(self.history.history, []) + self.history.store(' a ') + self.assertEqual(self.history.history, []) + + def test_store_dup(self): + self.history.store(line1) + self.assertEqual(self.history.history, [line1]) + self.history.store(line2) + self.assertEqual(self.history.history, [line1, line2]) + self.history.store(line1) + self.assertEqual(self.history.history, [line2, line1]) + + def test_store_reset(self): + self.history.prefix = line1 + self.history.pointer = 0 + self.history.store(line2) + self.assertIsNone(self.history.prefix) + self.assertIsNone(self.history.pointer) + + +class TextWrapper: + def __init__(self, master): + self.text = tkText(master=master) + self._bell = False + def __getattr__(self, name): + return getattr(self.text, name) + def bell(self): + self._bell = True + + +class FetchTest(unittest.TestCase): + '''Test History.fetch with wrapped tk.Text. + ''' + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = tk.Tk() + cls.root.withdraw() + + def setUp(self): + self.text = text = TextWrapper(self.root) + text.insert('1.0', ">>> ") + text.mark_set('iomark', '1.4') + text.mark_gravity('iomark', 'left') + self.history = History(text) + self.history.history = [line1, line2] + + @classmethod + def tearDownClass(cls): + cls.root.destroy() + del cls.root + + def fetch_test(self, reverse, line, prefix, index, *, bell=False): + # Perform one fetch as invoked by Alt-N or Alt-P + # Test the result. The line test is the most important. + # The last two are diagnostic of fetch internals. + History = self.history + History.fetch(reverse) + + Equal = self.assertEqual + Equal(self.text.get('iomark', 'end-1c'), line) + Equal(self.text._bell, bell) + if bell: + self.text._bell = False + Equal(History.prefix, prefix) + Equal(History.pointer, index) + Equal(self.text.compare("insert", '==', "end-1c"), 1) + + def test_fetch_prev_cyclic(self): + prefix = '' + test = self.fetch_test + test(True, line2, prefix, 1) + test(True, line1, prefix, 0) + test(True, prefix, None, None, bell=True) + + def test_fetch_next_cyclic(self): + prefix = '' + test = self.fetch_test + test(False, line1, prefix, 0) + test(False, line2, prefix, 1) + test(False, prefix, None, None, bell=True) + + # Prefix 'a' tests skip line2, which starts with 'b' + def test_fetch_prev_prefix(self): + prefix = 'a' + self.text.insert('iomark', prefix) + self.fetch_test(True, line1, prefix, 0) + self.fetch_test(True, prefix, None, None, bell=True) + + def test_fetch_next_prefix(self): + prefix = 'a' + self.text.insert('iomark', prefix) + self.fetch_test(False, line1, prefix, 0) + self.fetch_test(False, prefix, None, None, bell=True) + + def test_fetch_prev_noncyclic(self): + prefix = '' + self.history.cyclic = False + test = self.fetch_test + test(True, line2, prefix, 1) + test(True, line1, prefix, 0) + test(True, line1, prefix, 0, bell=True) + + def test_fetch_next_noncyclic(self): + prefix = '' + self.history.cyclic = False + test = self.fetch_test + test(False, prefix, None, None, bell=True) + test(True, line2, prefix, 1) + test(False, prefix, None, None, bell=True) + test(False, prefix, None, None, bell=True) + + def test_fetch_cursor_move(self): + # Move cursor after fetch + self.history.fetch(reverse=True) # initialization + self.text.mark_set('insert', 'iomark') + self.fetch_test(True, line2, None, None, bell=True) + + def test_fetch_edit(self): + # Edit after fetch + self.history.fetch(reverse=True) # initialization + self.text.delete('iomark', 'insert', ) + self.text.insert('iomark', 'a =') + self.fetch_test(True, line1, 'a =', 0) # prefix is reset + + def test_history_prev_next(self): + # Minimally test functions bound to events + self.history.history_prev('dummy event') + self.assertEqual(self.history.pointer, 1) + self.history.history_next('dummy event') + self.assertEqual(self.history.pointer, None) + + +if __name__ == '__main__': + unittest.main(verbosity=2, exit=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_hyperparser.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_hyperparser.py new file mode 100644 index 0000000000000000000000000000000000000000..343843c4166e97dcab123c4b9835341e15f65739 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_hyperparser.py @@ -0,0 +1,276 @@ +"Test hyperparser, coverage 98%." + +from idlelib.hyperparser import HyperParser +import unittest +from test.support import requires +from tkinter import Tk, Text +from idlelib.editor import EditorWindow + +class DummyEditwin: + def __init__(self, text): + self.text = text + self.indentwidth = 8 + self.tabwidth = 8 + self.prompt_last_line = '>>>' + self.num_context_lines = 50, 500, 1000 + + _build_char_in_string_func = EditorWindow._build_char_in_string_func + is_char_in_string = EditorWindow.is_char_in_string + + +class HyperParserTest(unittest.TestCase): + code = ( + '"""This is a module docstring"""\n' + '# this line is a comment\n' + 'x = "this is a string"\n' + "y = 'this is also a string'\n" + 'l = [i for i in range(10)]\n' + 'm = [py*py for # comment\n' + ' py in l]\n' + 'x.__len__\n' + "z = ((r'asdf')+('a')))\n" + '[x for x in\n' + 'for = False\n' + 'cliché = "this is a string with unicode, what a cliché"' + ) + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.text = Text(cls.root) + cls.editwin = DummyEditwin(cls.text) + + @classmethod + def tearDownClass(cls): + del cls.text, cls.editwin + cls.root.destroy() + del cls.root + + def setUp(self): + self.text.insert('insert', self.code) + + def tearDown(self): + self.text.delete('1.0', 'end') + self.editwin.prompt_last_line = '>>>' + + def get_parser(self, index): + """ + Return a parser object with index at 'index' + """ + return HyperParser(self.editwin, index) + + def test_init(self): + """ + test corner cases in the init method + """ + with self.assertRaises(ValueError) as ve: + self.text.tag_add('console', '1.0', '1.end') + p = self.get_parser('1.5') + self.assertIn('precedes', str(ve.exception)) + + # test without ps1 + self.editwin.prompt_last_line = '' + + # number of lines lesser than 50 + p = self.get_parser('end') + self.assertEqual(p.rawtext, self.text.get('1.0', 'end')) + + # number of lines greater than 50 + self.text.insert('end', self.text.get('1.0', 'end')*4) + p = self.get_parser('54.5') + + def test_is_in_string(self): + get = self.get_parser + + p = get('1.0') + self.assertFalse(p.is_in_string()) + p = get('1.4') + self.assertTrue(p.is_in_string()) + p = get('2.3') + self.assertFalse(p.is_in_string()) + p = get('3.3') + self.assertFalse(p.is_in_string()) + p = get('3.7') + self.assertTrue(p.is_in_string()) + p = get('4.6') + self.assertTrue(p.is_in_string()) + p = get('12.54') + self.assertTrue(p.is_in_string()) + + def test_is_in_code(self): + get = self.get_parser + + p = get('1.0') + self.assertTrue(p.is_in_code()) + p = get('1.1') + self.assertFalse(p.is_in_code()) + p = get('2.5') + self.assertFalse(p.is_in_code()) + p = get('3.4') + self.assertTrue(p.is_in_code()) + p = get('3.6') + self.assertFalse(p.is_in_code()) + p = get('4.14') + self.assertFalse(p.is_in_code()) + + def test_get_surrounding_bracket(self): + get = self.get_parser + + def without_mustclose(parser): + # a utility function to get surrounding bracket + # with mustclose=False + return parser.get_surrounding_brackets(mustclose=False) + + def with_mustclose(parser): + # a utility function to get surrounding bracket + # with mustclose=True + return parser.get_surrounding_brackets(mustclose=True) + + p = get('3.2') + self.assertIsNone(with_mustclose(p)) + self.assertIsNone(without_mustclose(p)) + + p = get('5.6') + self.assertTupleEqual(without_mustclose(p), ('5.4', '5.25')) + self.assertTupleEqual(without_mustclose(p), with_mustclose(p)) + + p = get('5.23') + self.assertTupleEqual(without_mustclose(p), ('5.21', '5.24')) + self.assertTupleEqual(without_mustclose(p), with_mustclose(p)) + + p = get('6.15') + self.assertTupleEqual(without_mustclose(p), ('6.4', '6.end')) + self.assertIsNone(with_mustclose(p)) + + p = get('9.end') + self.assertIsNone(with_mustclose(p)) + self.assertIsNone(without_mustclose(p)) + + def test_get_expression(self): + get = self.get_parser + + p = get('4.2') + self.assertEqual(p.get_expression(), 'y ') + + p = get('4.7') + with self.assertRaises(ValueError) as ve: + p.get_expression() + self.assertIn('is inside a code', str(ve.exception)) + + p = get('5.25') + self.assertEqual(p.get_expression(), 'range(10)') + + p = get('6.7') + self.assertEqual(p.get_expression(), 'py') + + p = get('6.8') + self.assertEqual(p.get_expression(), '') + + p = get('7.9') + self.assertEqual(p.get_expression(), 'py') + + p = get('8.end') + self.assertEqual(p.get_expression(), 'x.__len__') + + p = get('9.13') + self.assertEqual(p.get_expression(), "r'asdf'") + + p = get('9.17') + with self.assertRaises(ValueError) as ve: + p.get_expression() + self.assertIn('is inside a code', str(ve.exception)) + + p = get('10.0') + self.assertEqual(p.get_expression(), '') + + p = get('10.6') + self.assertEqual(p.get_expression(), '') + + p = get('10.11') + self.assertEqual(p.get_expression(), '') + + p = get('11.3') + self.assertEqual(p.get_expression(), '') + + p = get('11.11') + self.assertEqual(p.get_expression(), 'False') + + p = get('12.6') + self.assertEqual(p.get_expression(), 'cliché') + + def test_eat_identifier(self): + def is_valid_id(candidate): + result = HyperParser._eat_identifier(candidate, 0, len(candidate)) + if result == len(candidate): + return True + elif result == 0: + return False + else: + err_msg = "Unexpected result: {} (expected 0 or {}".format( + result, len(candidate) + ) + raise Exception(err_msg) + + # invalid first character which is valid elsewhere in an identifier + self.assertFalse(is_valid_id('2notid')) + + # ASCII-only valid identifiers + self.assertTrue(is_valid_id('valid_id')) + self.assertTrue(is_valid_id('_valid_id')) + self.assertTrue(is_valid_id('valid_id_')) + self.assertTrue(is_valid_id('_2valid_id')) + + # keywords which should be "eaten" + self.assertTrue(is_valid_id('True')) + self.assertTrue(is_valid_id('False')) + self.assertTrue(is_valid_id('None')) + + # keywords which should not be "eaten" + self.assertFalse(is_valid_id('for')) + self.assertFalse(is_valid_id('import')) + self.assertFalse(is_valid_id('return')) + + # valid unicode identifiers + self.assertTrue(is_valid_id('cliche')) + self.assertTrue(is_valid_id('cliché')) + self.assertTrue(is_valid_id('a٢')) + + # invalid unicode identifiers + self.assertFalse(is_valid_id('2a')) + self.assertFalse(is_valid_id('٢a')) + self.assertFalse(is_valid_id('a²')) + + # valid identifier after "punctuation" + self.assertEqual(HyperParser._eat_identifier('+ var', 0, 5), len('var')) + self.assertEqual(HyperParser._eat_identifier('+var', 0, 4), len('var')) + self.assertEqual(HyperParser._eat_identifier('.var', 0, 4), len('var')) + + # invalid identifiers + self.assertFalse(is_valid_id('+')) + self.assertFalse(is_valid_id(' ')) + self.assertFalse(is_valid_id(':')) + self.assertFalse(is_valid_id('?')) + self.assertFalse(is_valid_id('^')) + self.assertFalse(is_valid_id('\\')) + self.assertFalse(is_valid_id('"')) + self.assertFalse(is_valid_id('"a string"')) + + def test_eat_identifier_various_lengths(self): + eat_id = HyperParser._eat_identifier + + for length in range(1, 21): + self.assertEqual(eat_id('a' * length, 0, length), length) + self.assertEqual(eat_id('é' * length, 0, length), length) + self.assertEqual(eat_id('a' + '2' * (length - 1), 0, length), length) + self.assertEqual(eat_id('é' + '2' * (length - 1), 0, length), length) + self.assertEqual(eat_id('é' + 'a' * (length - 1), 0, length), length) + self.assertEqual(eat_id('é' * (length - 1) + 'a', 0, length), length) + self.assertEqual(eat_id('+' * length, 0, length), 0) + self.assertEqual(eat_id('2' + 'a' * (length - 1), 0, length), 0) + self.assertEqual(eat_id('2' + 'é' * (length - 1), 0, length), 0) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_iomenu.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_iomenu.py new file mode 100644 index 0000000000000000000000000000000000000000..e0642cf0cabef0470424d9e04cfc4aa68c4adb26 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_iomenu.py @@ -0,0 +1,84 @@ +"Test , coverage 17%." + +from idlelib import iomenu +import unittest +from test.support import requires +from tkinter import Tk +from idlelib.editor import EditorWindow +from idlelib import util +from idlelib.idle_test.mock_idle import Func + +# Fail if either tokenize.open and t.detect_encoding does not exist. +# These are used in loadfile and encode. +# Also used in pyshell.MI.execfile and runscript.tabnanny. +from tokenize import open, detect_encoding +# Remove when we have proper tests that use both. + + +class IOBindingTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.editwin = EditorWindow(root=cls.root) + cls.io = iomenu.IOBinding(cls.editwin) + + @classmethod + def tearDownClass(cls): + cls.io.close() + cls.editwin._close() + del cls.editwin + cls.root.update_idletasks() + for id in cls.root.tk.call('after', 'info'): + cls.root.after_cancel(id) # Need for EditorWindow. + cls.root.destroy() + del cls.root + + def test_init(self): + self.assertIs(self.io.editwin, self.editwin) + + def test_fixnewlines_end(self): + eq = self.assertEqual + io = self.io + fix = io.fixnewlines + text = io.editwin.text + + # Make the editor temporarily look like Shell. + self.editwin.interp = None + shelltext = '>>> if 1' + self.editwin.get_prompt_text = Func(result=shelltext) + eq(fix(), shelltext) # Get... call and '\n' not added. + del self.editwin.interp, self.editwin.get_prompt_text + + text.insert(1.0, 'a') + eq(fix(), 'a'+io.eol_convention) + eq(text.get('1.0', 'end-1c'), 'a\n') + eq(fix(), 'a'+io.eol_convention) + + +def _extension_in_filetypes(extension): + return any( + f'*{extension}' in filetype_tuple[1] + for filetype_tuple in iomenu.IOBinding.filetypes + ) + + +class FiletypesTest(unittest.TestCase): + def test_python_source_files(self): + for extension in util.py_extensions: + with self.subTest(extension=extension): + self.assertTrue( + _extension_in_filetypes(extension) + ) + + def test_text_files(self): + self.assertTrue(_extension_in_filetypes('.txt')) + + def test_all_files(self): + self.assertTrue(_extension_in_filetypes('')) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_macosx.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_macosx.py new file mode 100644 index 0000000000000000000000000000000000000000..86da8849e5ca00f55affd806b4b89e74f55fdcb5 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_macosx.py @@ -0,0 +1,113 @@ +"Test macosx, coverage 45% on Windows." + +from idlelib import macosx +import unittest +from test.support import requires +import tkinter as tk +import unittest.mock as mock +from idlelib.filelist import FileList + +mactypes = {'carbon', 'cocoa', 'xquartz'} +nontypes = {'other'} +alltypes = mactypes | nontypes + + +def setUpModule(): + global orig_tktype + orig_tktype = macosx._tk_type + + +def tearDownModule(): + macosx._tk_type = orig_tktype + + +class InitTktypeTest(unittest.TestCase): + "Test _init_tk_type." + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = tk.Tk() + cls.root.withdraw() + cls.orig_platform = macosx.platform + + @classmethod + def tearDownClass(cls): + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + macosx.platform = cls.orig_platform + + def test_init_sets_tktype(self): + "Test that _init_tk_type sets _tk_type according to platform." + for platform, types in ('darwin', alltypes), ('other', nontypes): + with self.subTest(platform=platform): + macosx.platform = platform + macosx._tk_type = None + macosx._init_tk_type() + self.assertIn(macosx._tk_type, types) + + +class IsTypeTkTest(unittest.TestCase): + "Test each of the four isTypeTk predecates." + isfuncs = ((macosx.isAquaTk, ('carbon', 'cocoa')), + (macosx.isCarbonTk, ('carbon')), + (macosx.isCocoaTk, ('cocoa')), + (macosx.isXQuartz, ('xquartz')), + ) + + @mock.patch('idlelib.macosx._init_tk_type') + def test_is_calls_init(self, mockinit): + "Test that each isTypeTk calls _init_tk_type when _tk_type is None." + macosx._tk_type = None + for func, whentrue in self.isfuncs: + with self.subTest(func=func): + func() + self.assertTrue(mockinit.called) + mockinit.reset_mock() + + def test_isfuncs(self): + "Test that each isTypeTk return correct bool." + for func, whentrue in self.isfuncs: + for tktype in alltypes: + with self.subTest(func=func, whentrue=whentrue, tktype=tktype): + macosx._tk_type = tktype + (self.assertTrue if tktype in whentrue else self.assertFalse)\ + (func()) + + +class SetupTest(unittest.TestCase): + "Test setupApp." + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = tk.Tk() + cls.root.withdraw() + def cmd(tkpath, func): + assert isinstance(tkpath, str) + assert isinstance(func, type(cmd)) + cls.root.createcommand = cmd + + @classmethod + def tearDownClass(cls): + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + @mock.patch('idlelib.macosx.overrideRootMenu') #27312 + def test_setupapp(self, overrideRootMenu): + "Call setupApp with each possible graphics type." + root = self.root + flist = FileList(root) + for tktype in alltypes: + with self.subTest(tktype=tktype): + macosx._tk_type = tktype + macosx.setupApp(root, flist) + if tktype in ('carbon', 'cocoa'): + self.assertTrue(overrideRootMenu.called) + overrideRootMenu.reset_mock() + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_mainmenu.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_mainmenu.py new file mode 100644 index 0000000000000000000000000000000000000000..51d2accfe48a1c738b73509563d21bc59e5d3a12 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_mainmenu.py @@ -0,0 +1,42 @@ +"Test mainmenu, coverage 100%." +# Reported as 88%; mocking turtledemo absence would have no point. + +from idlelib import mainmenu +import re +import unittest + + +class MainMenuTest(unittest.TestCase): + + def test_menudefs(self): + actual = [item[0] for item in mainmenu.menudefs] + expect = ['file', 'edit', 'format', 'run', 'shell', + 'debug', 'options', 'window', 'help'] + self.assertEqual(actual, expect) + + def test_default_keydefs(self): + self.assertGreaterEqual(len(mainmenu.default_keydefs), 50) + + def test_tcl_indexes(self): + # Test tcl patterns used to find menuitem to alter. + # On failure, change pattern here and in function(s). + # Patterns here have '.*' for re instead of '*' for tcl. + for menu, pattern in ( + ('debug', '.*tack.*iewer'), # PyShell.debug_menu_postcommand + ('options', '.*ode.*ontext'), # EW.__init__, CodeContext.toggle... + ('options', '.*ine.*umbers'), # EW.__init__, EW.toggle...event. + ): + with self.subTest(menu=menu, pattern=pattern): + for menutup in mainmenu.menudefs: + if menutup[0] == menu: + break + else: + self.assertTrue(0, f"{menu} not in menudefs") + self.assertTrue(any(re.search(pattern, menuitem[0]) + for menuitem in menutup[1] + if menuitem is not None), # Separator. + f"{pattern} not in {menu}") + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_multicall.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_multicall.py new file mode 100644 index 0000000000000000000000000000000000000000..0c1fbfd648820ff10a8935ca0190c031b2523619 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_multicall.py @@ -0,0 +1,49 @@ +"Test multicall, coverage 33%." + +from idlelib import multicall +import unittest +from test.support import requires +from test.support.testcase import ExtraAssertions +from tkinter import Tk, Text + + +class MultiCallTest(unittest.TestCase, ExtraAssertions): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.mc = multicall.MultiCallCreator(Text) + + @classmethod + def tearDownClass(cls): + del cls.mc + cls.root.update_idletasks() +## for id in cls.root.tk.call('after', 'info'): +## cls.root.after_cancel(id) # Need for EditorWindow. + cls.root.destroy() + del cls.root + + def test_creator(self): + mc = self.mc + self.assertIs(multicall._multicall_dict[Text], mc) + self.assertIsSubclass(mc, Text) + mc2 = multicall.MultiCallCreator(Text) + self.assertIs(mc, mc2) + + def test_init(self): + mctext = self.mc(self.root) + self.assertIsInstance(mctext._MultiCall__binders, list) + + def test_yview(self): + # Added for tree.wheel_event + # (it depends on yview to not be overridden) + mc = self.mc + self.assertIs(mc.yview, Text.yview) + mctext = self.mc(self.root) + self.assertIs(mctext.yview.__func__, Text.yview) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_outwin.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_outwin.py new file mode 100644 index 0000000000000000000000000000000000000000..0f13363f84f36107283d074ba7ed208f288e5eea --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_outwin.py @@ -0,0 +1,172 @@ +"Test outwin, coverage 76%." + +from idlelib import outwin +import platform +import sys +import unittest +from test.support import requires +from tkinter import Tk, Text +from idlelib.idle_test.mock_tk import Mbox_func +from idlelib.idle_test.mock_idle import Func +from unittest import mock + + +class OutputWindowTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + root = cls.root = Tk() + root.withdraw() + w = cls.window = outwin.OutputWindow(None, None, None, root) + cls.text = w.text = Text(root) + if sys.platform == 'darwin': # Issue 112938 + cls.text.update = cls.text.update_idletasks + # Without this, test write, writelines, and goto... fail. + # The reasons and why macOS-specific are unclear. + + @classmethod + def tearDownClass(cls): + cls.window.close() + del cls.text, cls.window + cls.root.destroy() + del cls.root + + def setUp(self): + self.text.delete('1.0', 'end') + + def test_ispythonsource(self): + # OutputWindow overrides ispythonsource to always return False. + w = self.window + self.assertFalse(w.ispythonsource('test.txt')) + self.assertFalse(w.ispythonsource(__file__)) + + def test_window_title(self): + self.assertEqual(self.window.top.title(), 'Output' + ' (%s)' % platform.python_version()) + + def test_maybesave(self): + w = self.window + eq = self.assertEqual + w.get_saved = Func() + + w.get_saved.result = False + eq(w.maybesave(), 'no') + eq(w.get_saved.called, 1) + + w.get_saved.result = True + eq(w.maybesave(), 'yes') + eq(w.get_saved.called, 2) + del w.get_saved + + def test_write(self): + eq = self.assertEqual + delete = self.text.delete + get = self.text.get + write = self.window.write + + # No new line - insert stays on same line. + delete('1.0', 'end') + test_text = 'test text' + eq(write(test_text), len(test_text)) + eq(get('1.0', '1.end'), 'test text') + eq(get('insert linestart', 'insert lineend'), 'test text') + + # New line - insert moves to next line. + delete('1.0', 'end') + test_text = 'test text\n' + eq(write(test_text), len(test_text)) + eq(get('1.0', '1.end'), 'test text') + eq(get('insert linestart', 'insert lineend'), '') + + # Text after new line is tagged for second line of Text widget. + delete('1.0', 'end') + test_text = 'test text\nLine 2' + eq(write(test_text), len(test_text)) + eq(get('1.0', '1.end'), 'test text') + eq(get('2.0', '2.end'), 'Line 2') + eq(get('insert linestart', 'insert lineend'), 'Line 2') + + # Test tags. + delete('1.0', 'end') + test_text = 'test text\n' + test_text2 = 'Line 2\n' + eq(write(test_text, tags='mytag'), len(test_text)) + eq(write(test_text2, tags='secondtag'), len(test_text2)) + eq(get('mytag.first', 'mytag.last'), test_text) + eq(get('secondtag.first', 'secondtag.last'), test_text2) + eq(get('1.0', '1.end'), test_text.rstrip('\n')) + eq(get('2.0', '2.end'), test_text2.rstrip('\n')) + + def test_writelines(self): + eq = self.assertEqual + get = self.text.get + writelines = self.window.writelines + + writelines(('Line 1\n', 'Line 2\n', 'Line 3\n')) + eq(get('1.0', '1.end'), 'Line 1') + eq(get('2.0', '2.end'), 'Line 2') + eq(get('3.0', '3.end'), 'Line 3') + eq(get('insert linestart', 'insert lineend'), '') + + def test_goto_file_line(self): + eq = self.assertEqual + w = self.window + text = self.text + + w.flist = mock.Mock() + gfl = w.flist.gotofileline = Func() + showerror = w.showerror = Mbox_func() + + # No file/line number. + w.write('Not a file line') + self.assertIsNone(w.goto_file_line()) + eq(gfl.called, 0) + eq(showerror.title, 'No special line') + + # Current file/line number. + w.write(f'{str(__file__)}: 42: spam\n') + w.write(f'{str(__file__)}: 21: spam') + self.assertIsNone(w.goto_file_line()) + eq(gfl.args, (str(__file__), 21)) + + # Previous line has file/line number. + text.delete('1.0', 'end') + w.write(f'{str(__file__)}: 42: spam\n') + w.write('Not a file line') + self.assertIsNone(w.goto_file_line()) + eq(gfl.args, (str(__file__), 42)) + + del w.flist.gotofileline, w.showerror + + +class ModuleFunctionTest(unittest.TestCase): + + @classmethod + def setUp(cls): + outwin.file_line_progs = None + + def test_compile_progs(self): + outwin.compile_progs() + for pat, regex in zip(outwin.file_line_pats, outwin.file_line_progs): + self.assertEqual(regex.pattern, pat) + + @mock.patch('builtins.open') + def test_file_line_helper(self, mock_open): + flh = outwin.file_line_helper + test_lines = ( + (r'foo file "testfile1", line 42, bar', ('testfile1', 42)), + (r'foo testfile2(21) bar', ('testfile2', 21)), + (r' testfile3 : 42: foo bar\n', (' testfile3 ', 42)), + (r'foo testfile4.py :1: ', ('foo testfile4.py ', 1)), + ('testfile5: \u19D4\u19D2: ', ('testfile5', 42)), + (r'testfile6: 42', None), # only one `:` + (r'testfile7 42 text', None) # no separators + ) + for line, expected_output in test_lines: + self.assertEqual(flh(line), expected_output) + if expected_output: + mock_open.assert_called_with(expected_output[0]) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_parenmatch.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_parenmatch.py new file mode 100644 index 0000000000000000000000000000000000000000..2e10d7cd36760ff66f33c4b22ab62e5ac3f7d46c --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_parenmatch.py @@ -0,0 +1,112 @@ +"""Test parenmatch, coverage 91%. + +This must currently be a gui test because ParenMatch methods use +several text methods not defined on idlelib.idle_test.mock_tk.Text. +""" +from idlelib.parenmatch import ParenMatch +from test.support import requires +requires('gui') + +import unittest +from unittest.mock import Mock +from tkinter import Tk, Text + + +class DummyEditwin: + def __init__(self, text): + self.text = text + self.indentwidth = 8 + self.tabwidth = 8 + self.prompt_last_line = '>>>' # Currently not used by parenmatch. + + +class ParenMatchTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + cls.root = Tk() + cls.root.withdraw() + cls.text = Text(cls.root) + cls.editwin = DummyEditwin(cls.text) + cls.editwin.text_frame = Mock() + + @classmethod + def tearDownClass(cls): + del cls.text, cls.editwin + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def tearDown(self): + self.text.delete('1.0', 'end') + + def get_parenmatch(self): + pm = ParenMatch(self.editwin) + pm.bell = lambda: None + return pm + + def test_paren_styles(self): + """ + Test ParenMatch with each style. + """ + text = self.text + pm = self.get_parenmatch() + for style, range1, range2 in ( + ('opener', ('1.10', '1.11'), ('1.10', '1.11')), + ('default',('1.10', '1.11'),('1.10', '1.11')), + ('parens', ('1.14', '1.15'), ('1.15', '1.16')), + ('expression', ('1.10', '1.15'), ('1.10', '1.16'))): + with self.subTest(style=style): + text.delete('1.0', 'end') + pm.STYLE = style + text.insert('insert', 'def foobar(a, b') + + pm.flash_paren_event('event') + self.assertIn('<>', text.event_info()) + if style == 'parens': + self.assertTupleEqual(text.tag_nextrange('paren', '1.0'), + ('1.10', '1.11')) + self.assertTupleEqual( + text.tag_prevrange('paren', 'end'), range1) + + text.insert('insert', ')') + pm.restore_event() + self.assertNotIn('<>', + text.event_info()) + self.assertEqual(text.tag_prevrange('paren', 'end'), ()) + + pm.paren_closed_event('event') + self.assertTupleEqual( + text.tag_prevrange('paren', 'end'), range2) + + def test_paren_corner(self): + """ + Test corner cases in flash_paren_event and paren_closed_event. + + Force execution of conditional expressions and alternate paths. + """ + text = self.text + pm = self.get_parenmatch() + + text.insert('insert', '# Comment.)') + pm.paren_closed_event('event') + + text.insert('insert', '\ndef') + pm.flash_paren_event('event') + pm.paren_closed_event('event') + + text.insert('insert', ' a, *arg)') + pm.paren_closed_event('event') + + def test_handle_restore_timer(self): + pm = self.get_parenmatch() + pm.restore_event = Mock() + pm.handle_restore_timer(0) + self.assertTrue(pm.restore_event.called) + pm.restore_event.reset_mock() + pm.handle_restore_timer(1) + self.assertFalse(pm.restore_event.called) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_pathbrowser.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_pathbrowser.py new file mode 100644 index 0000000000000000000000000000000000000000..13d8b9e1ba9572afeefc20b2bf0f6b7bf3a50716 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_pathbrowser.py @@ -0,0 +1,86 @@ +"Test pathbrowser, coverage 95%." + +from idlelib import pathbrowser +import unittest +from test.support import requires +from tkinter import Tk + +import os.path +import pyclbr # for _modules +import sys # for sys.path + +from idlelib.idle_test.mock_idle import Func +import idlelib # for __file__ +from idlelib import browser +from idlelib.tree import TreeNode + + +class PathBrowserTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.pb = pathbrowser.PathBrowser(cls.root, _utest=True) + + @classmethod + def tearDownClass(cls): + cls.pb.close() + cls.root.update_idletasks() + cls.root.destroy() + del cls.root, cls.pb + + def test_init(self): + pb = self.pb + eq = self.assertEqual + eq(pb.master, self.root) + eq(pyclbr._modules, {}) + self.assertIsInstance(pb.node, TreeNode) + self.assertIsNotNone(browser.file_open) + + def test_settitle(self): + pb = self.pb + self.assertEqual(pb.top.title(), 'Path Browser') + self.assertEqual(pb.top.iconname(), 'Path Browser') + + def test_rootnode(self): + pb = self.pb + rn = pb.rootnode() + self.assertIsInstance(rn, pathbrowser.PathBrowserTreeItem) + + def test_close(self): + pb = self.pb + pb.top.destroy = Func() + pb.node.destroy = Func() + pb.close() + self.assertTrue(pb.top.destroy.called) + self.assertTrue(pb.node.destroy.called) + del pb.top.destroy, pb.node.destroy + + +class DirBrowserTreeItemTest(unittest.TestCase): + + def test_DirBrowserTreeItem(self): + # Issue16226 - make sure that getting a sublist works + d = pathbrowser.DirBrowserTreeItem('') + d.GetSubList() + self.assertEqual('', d.GetText()) + + dir = os.path.split(os.path.abspath(idlelib.__file__))[0] + self.assertEqual(d.ispackagedir(dir), True) + self.assertEqual(d.ispackagedir(dir + '/Icons'), False) + + +class PathBrowserTreeItemTest(unittest.TestCase): + + def test_PathBrowserTreeItem(self): + p = pathbrowser.PathBrowserTreeItem() + self.assertEqual(p.GetText(), 'sys.path') + sub = p.GetSubList() + self.assertEqual(len(sub), len(sys.path)) + self.assertEqual(type(sub[0]), pathbrowser.DirBrowserTreeItem) + + +if __name__ == '__main__': + unittest.main(verbosity=2, exit=False) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_percolator.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_percolator.py new file mode 100644 index 0000000000000000000000000000000000000000..17668ccd1227b7834cdf374287c812f23f048337 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_percolator.py @@ -0,0 +1,118 @@ +"Test percolator, coverage 100%." + +from idlelib.percolator import Percolator, Delegator +import unittest +from test.support import requires +requires('gui') +from tkinter import Text, Tk, END + + +class MyFilter(Delegator): + def __init__(self): + Delegator.__init__(self, None) + + def insert(self, *args): + self.insert_called_with = args + self.delegate.insert(*args) + + def delete(self, *args): + self.delete_called_with = args + self.delegate.delete(*args) + + def uppercase_insert(self, index, chars, tags=None): + chars = chars.upper() + self.delegate.insert(index, chars) + + def lowercase_insert(self, index, chars, tags=None): + chars = chars.lower() + self.delegate.insert(index, chars) + + def dont_insert(self, index, chars, tags=None): + pass + + +class PercolatorTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + cls.root = Tk() + cls.text = Text(cls.root) + + @classmethod + def tearDownClass(cls): + del cls.text + cls.root.destroy() + del cls.root + + def setUp(self): + self.percolator = Percolator(self.text) + self.filter_one = MyFilter() + self.filter_two = MyFilter() + self.percolator.insertfilter(self.filter_one) + self.percolator.insertfilter(self.filter_two) + + def tearDown(self): + self.percolator.close() + self.text.delete('1.0', END) + + def test_insertfilter(self): + self.assertIsNotNone(self.filter_one.delegate) + self.assertEqual(self.percolator.top, self.filter_two) + self.assertEqual(self.filter_two.delegate, self.filter_one) + self.assertEqual(self.filter_one.delegate, self.percolator.bottom) + + def test_removefilter(self): + filter_three = MyFilter() + self.percolator.removefilter(self.filter_two) + self.assertEqual(self.percolator.top, self.filter_one) + self.assertIsNone(self.filter_two.delegate) + + filter_three = MyFilter() + self.percolator.insertfilter(self.filter_two) + self.percolator.insertfilter(filter_three) + self.percolator.removefilter(self.filter_one) + self.assertEqual(self.percolator.top, filter_three) + self.assertEqual(filter_three.delegate, self.filter_two) + self.assertEqual(self.filter_two.delegate, self.percolator.bottom) + self.assertIsNone(self.filter_one.delegate) + + def test_insert(self): + self.text.insert('insert', 'foo') + self.assertEqual(self.text.get('1.0', END), 'foo\n') + self.assertTupleEqual(self.filter_one.insert_called_with, + ('insert', 'foo', None)) + + def test_modify_insert(self): + self.filter_one.insert = self.filter_one.uppercase_insert + self.text.insert('insert', 'bAr') + self.assertEqual(self.text.get('1.0', END), 'BAR\n') + + def test_modify_chain_insert(self): + filter_three = MyFilter() + self.percolator.insertfilter(filter_three) + self.filter_two.insert = self.filter_two.uppercase_insert + self.filter_one.insert = self.filter_one.lowercase_insert + self.text.insert('insert', 'BaR') + self.assertEqual(self.text.get('1.0', END), 'bar\n') + + def test_dont_insert(self): + self.filter_one.insert = self.filter_one.dont_insert + self.text.insert('insert', 'foo bar') + self.assertEqual(self.text.get('1.0', END), '\n') + self.filter_one.insert = self.filter_one.dont_insert + self.text.insert('insert', 'foo bar') + self.assertEqual(self.text.get('1.0', END), '\n') + + def test_without_filter(self): + self.text.insert('insert', 'hello') + self.assertEqual(self.text.get('1.0', 'end'), 'hello\n') + + def test_delete(self): + self.text.insert('insert', 'foo') + self.text.delete('1.0', '1.2') + self.assertEqual(self.text.get('1.0', END), 'o\n') + self.assertTupleEqual(self.filter_one.delete_called_with, + ('1.0', '1.2')) + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_pyparse.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_pyparse.py new file mode 100644 index 0000000000000000000000000000000000000000..384db566ac76cdb44fb3c2998a989e848d56cd6c --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_pyparse.py @@ -0,0 +1,483 @@ +"Test pyparse, coverage 96%." + +from idlelib import pyparse +import unittest +from collections import namedtuple + + +class ParseMapTest(unittest.TestCase): + + def test_parsemap(self): + keepwhite = {ord(c): ord(c) for c in ' \t\n\r'} + mapping = pyparse.ParseMap(keepwhite) + self.assertEqual(mapping[ord('\t')], ord('\t')) + self.assertEqual(mapping[ord('a')], ord('x')) + self.assertEqual(mapping[1000], ord('x')) + + def test_trans(self): + # trans is the production instance of ParseMap, used in _study1 + parser = pyparse.Parser(4, 4) + self.assertEqual('\t a([{b}])b"c\'d\n'.translate(pyparse.trans), + 'xxx(((x)))x"x\'x\n') + + +class PyParseTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + cls.parser = pyparse.Parser(indentwidth=4, tabwidth=4) + + @classmethod + def tearDownClass(cls): + del cls.parser + + def test_init(self): + self.assertEqual(self.parser.indentwidth, 4) + self.assertEqual(self.parser.tabwidth, 4) + + def test_set_code(self): + eq = self.assertEqual + p = self.parser + setcode = p.set_code + + # Not empty and doesn't end with newline. + with self.assertRaises(AssertionError): + setcode('a') + + tests = ('', + 'a\n') + + for string in tests: + with self.subTest(string=string): + setcode(string) + eq(p.code, string) + eq(p.study_level, 0) + + def test_find_good_parse_start(self): + eq = self.assertEqual + p = self.parser + setcode = p.set_code + start = p.find_good_parse_start + def char_in_string_false(index): return False + + # First line starts with 'def' and ends with ':', then 0 is the pos. + setcode('def spam():\n') + eq(start(char_in_string_false), 0) + + # First line begins with a keyword in the list and ends + # with an open brace, then 0 is the pos. This is how + # hyperparser calls this function as the newline is not added + # in the editor, but rather on the call to setcode. + setcode('class spam( ' + ' \n') + eq(start(char_in_string_false), 0) + + # Split def across lines. + setcode('"""This is a module docstring"""\n' + 'class C:\n' + ' def __init__(self, a,\n' + ' b=True):\n' + ' pass\n' + ) + pos0, pos = 33, 42 # Start of 'class...', ' def' lines. + + # Passing no value or non-callable should fail (issue 32989). + with self.assertRaises(TypeError): + start() + with self.assertRaises(TypeError): + start(False) + + # Make text look like a string. This returns pos as the start + # position, but it's set to None. + self.assertIsNone(start(is_char_in_string=lambda index: True)) + + # Make all text look like it's not in a string. This means that it + # found a good start position. + eq(start(char_in_string_false), pos) + + # If the beginning of the def line is not in a string, then it + # returns that as the index. + eq(start(is_char_in_string=lambda index: index > pos), pos) + # If the beginning of the def line is in a string, then it + # looks for a previous index. + eq(start(is_char_in_string=lambda index: index >= pos), pos0) + # If everything before the 'def' is in a string, then returns None. + # The non-continuation def line returns 44 (see below). + eq(start(is_char_in_string=lambda index: index < pos), None) + + # Code without extra line break in def line - mostly returns the same + # values. + setcode('"""This is a module docstring"""\n' + 'class C:\n' + ' def __init__(self, a, b=True):\n' + ' pass\n' + ) # Does not affect class, def positions. + eq(start(char_in_string_false), pos) + eq(start(is_char_in_string=lambda index: index > pos), pos) + eq(start(is_char_in_string=lambda index: index >= pos), pos0) + # When the def line isn't split, this returns which doesn't match the + # split line test. + eq(start(is_char_in_string=lambda index: index < pos), pos) + + def test_set_lo(self): + code = ( + '"""This is a module docstring"""\n' + 'class C:\n' + ' def __init__(self, a,\n' + ' b=True):\n' + ' pass\n' + ) + pos = 42 + p = self.parser + p.set_code(code) + + # Previous character is not a newline. + with self.assertRaises(AssertionError): + p.set_lo(5) + + # A value of 0 doesn't change self.code. + p.set_lo(0) + self.assertEqual(p.code, code) + + # An index that is preceded by a newline. + p.set_lo(pos) + self.assertEqual(p.code, code[pos:]) + + def test_study1(self): + eq = self.assertEqual + p = self.parser + setcode = p.set_code + study = p._study1 + + (NONE, BACKSLASH, FIRST, NEXT, BRACKET) = range(5) + TestInfo = namedtuple('TestInfo', ['string', 'goodlines', + 'continuation']) + tests = ( + TestInfo('', [0], NONE), + # Docstrings. + TestInfo('"""This is a complete docstring."""\n', [0, 1], NONE), + TestInfo("'''This is a complete docstring.'''\n", [0, 1], NONE), + TestInfo('"""This is a continued docstring.\n', [0, 1], FIRST), + TestInfo("'''This is a continued docstring.\n", [0, 1], FIRST), + TestInfo('"""Closing quote does not match."\n', [0, 1], FIRST), + TestInfo('"""Bracket in docstring [\n', [0, 1], FIRST), + TestInfo("'''Incomplete two line docstring.\n\n", [0, 2], NEXT), + # Single-quoted strings. + TestInfo('"This is a complete string."\n', [0, 1], NONE), + TestInfo('"This is an incomplete string.\n', [0, 1], NONE), + TestInfo("'This is more incomplete.\n\n", [0, 1, 2], NONE), + # Comment (backslash does not continue comments). + TestInfo('# Comment\\\n', [0, 1], NONE), + # Brackets. + TestInfo('("""Complete string in bracket"""\n', [0, 1], BRACKET), + TestInfo('("""Open string in bracket\n', [0, 1], FIRST), + TestInfo('a = (1 + 2) - 5 *\\\n', [0, 1], BACKSLASH), # No bracket. + TestInfo('\n def function1(self, a,\n b):\n', + [0, 1, 3], NONE), + TestInfo('\n def function1(self, a,\\\n', [0, 1, 2], BRACKET), + TestInfo('\n def function1(self, a,\n', [0, 1, 2], BRACKET), + TestInfo('())\n', [0, 1], NONE), # Extra closer. + TestInfo(')(\n', [0, 1], BRACKET), # Extra closer. + # For the mismatched example, it doesn't look like continuation. + TestInfo('{)(]\n', [0, 1], NONE), # Mismatched. + ) + + for test in tests: + with self.subTest(string=test.string): + setcode(test.string) # resets study_level + study() + eq(p.study_level, 1) + eq(p.goodlines, test.goodlines) + eq(p.continuation, test.continuation) + + # Called again, just returns without reprocessing. + self.assertIsNone(study()) + + def test_get_continuation_type(self): + eq = self.assertEqual + p = self.parser + setcode = p.set_code + gettype = p.get_continuation_type + + (NONE, BACKSLASH, FIRST, NEXT, BRACKET) = range(5) + TestInfo = namedtuple('TestInfo', ['string', 'continuation']) + tests = ( + TestInfo('', NONE), + TestInfo('"""This is a continuation docstring.\n', FIRST), + TestInfo("'''This is a multiline-continued docstring.\n\n", NEXT), + TestInfo('a = (1 + 2) - 5 *\\\n', BACKSLASH), + TestInfo('\n def function1(self, a,\\\n', BRACKET) + ) + + for test in tests: + with self.subTest(string=test.string): + setcode(test.string) + eq(gettype(), test.continuation) + + def test_study2(self): + eq = self.assertEqual + p = self.parser + setcode = p.set_code + study = p._study2 + + TestInfo = namedtuple('TestInfo', ['string', 'start', 'end', 'lastch', + 'openbracket', 'bracketing']) + tests = ( + TestInfo('', 0, 0, '', None, ((0, 0),)), + TestInfo("'''This is a multiline continuation docstring.\n\n", + 0, 48, "'", None, ((0, 0), (0, 1), (48, 0))), + TestInfo(' # Comment\\\n', + 0, 12, '', None, ((0, 0), (1, 1), (12, 0))), + # A comment without a space is a special case + TestInfo(' #Comment\\\n', + 0, 0, '', None, ((0, 0),)), + # Backslash continuation. + TestInfo('a = (1 + 2) - 5 *\\\n', + 0, 19, '*', None, ((0, 0), (4, 1), (11, 0))), + # Bracket continuation with close. + TestInfo('\n def function1(self, a,\n b):\n', + 1, 48, ':', None, ((1, 0), (17, 1), (46, 0))), + # Bracket continuation with unneeded backslash. + TestInfo('\n def function1(self, a,\\\n', + 1, 28, ',', 17, ((1, 0), (17, 1))), + # Bracket continuation. + TestInfo('\n def function1(self, a,\n', + 1, 27, ',', 17, ((1, 0), (17, 1))), + # Bracket continuation with comment at end of line with text. + TestInfo('\n def function1(self, a, # End of line comment.\n', + 1, 51, ',', 17, ((1, 0), (17, 1), (28, 2), (51, 1))), + # Multi-line statement with comment line in between code lines. + TestInfo(' a = ["first item",\n # Comment line\n "next item",\n', + 0, 55, ',', 6, ((0, 0), (6, 1), (7, 2), (19, 1), + (23, 2), (38, 1), (42, 2), (53, 1))), + TestInfo('())\n', + 0, 4, ')', None, ((0, 0), (0, 1), (2, 0), (3, 0))), + TestInfo(')(\n', 0, 3, '(', 1, ((0, 0), (1, 0), (1, 1))), + # Wrong closers still decrement stack level. + TestInfo('{)(]\n', + 0, 5, ']', None, ((0, 0), (0, 1), (2, 0), (2, 1), (4, 0))), + # Character after backslash. + TestInfo(':\\a\n', 0, 4, '\\a', None, ((0, 0),)), + TestInfo('\n', 0, 0, '', None, ((0, 0),)), + ) + + for test in tests: + with self.subTest(string=test.string): + setcode(test.string) + study() + eq(p.study_level, 2) + eq(p.stmt_start, test.start) + eq(p.stmt_end, test.end) + eq(p.lastch, test.lastch) + eq(p.lastopenbracketpos, test.openbracket) + eq(p.stmt_bracketing, test.bracketing) + + # Called again, just returns without reprocessing. + self.assertIsNone(study()) + + def test_get_num_lines_in_stmt(self): + eq = self.assertEqual + p = self.parser + setcode = p.set_code + getlines = p.get_num_lines_in_stmt + + TestInfo = namedtuple('TestInfo', ['string', 'lines']) + tests = ( + TestInfo('[x for x in a]\n', 1), # Closed on one line. + TestInfo('[x\nfor x in a\n', 2), # Not closed. + TestInfo('[x\\\nfor x in a\\\n', 2), # "", unneeded backslashes. + TestInfo('[x\nfor x in a\n]\n', 3), # Closed on multi-line. + TestInfo('\n"""Docstring comment L1"""\nL2\nL3\nL4\n', 1), + TestInfo('\n"""Docstring comment L1\nL2"""\nL3\nL4\n', 1), + TestInfo('\n"""Docstring comment L1\\\nL2\\\nL3\\\nL4\\\n', 4), + TestInfo('\n\n"""Docstring comment L1\\\nL2\\\nL3\\\nL4\\\n"""\n', 5) + ) + + # Blank string doesn't have enough elements in goodlines. + setcode('') + with self.assertRaises(IndexError): + getlines() + + for test in tests: + with self.subTest(string=test.string): + setcode(test.string) + eq(getlines(), test.lines) + + def test_compute_bracket_indent(self): + eq = self.assertEqual + p = self.parser + setcode = p.set_code + indent = p.compute_bracket_indent + + TestInfo = namedtuple('TestInfo', ['string', 'spaces']) + tests = ( + TestInfo('def function1(self, a,\n', 14), + # Characters after bracket. + TestInfo('\n def function1(self, a,\n', 18), + TestInfo('\n\tdef function1(self, a,\n', 18), + # No characters after bracket. + TestInfo('\n def function1(\n', 8), + TestInfo('\n\tdef function1(\n', 8), + TestInfo('\n def function1( \n', 8), # Ignore extra spaces. + TestInfo('[\n"first item",\n # Comment line\n "next item",\n', 0), + TestInfo('[\n "first item",\n # Comment line\n "next item",\n', 2), + TestInfo('["first item",\n # Comment line\n "next item",\n', 1), + TestInfo('(\n', 4), + TestInfo('(a\n', 1), + ) + + # Must be C_BRACKET continuation type. + setcode('def function1(self, a, b):\n') + with self.assertRaises(AssertionError): + indent() + + for test in tests: + setcode(test.string) + eq(indent(), test.spaces) + + def test_compute_backslash_indent(self): + eq = self.assertEqual + p = self.parser + setcode = p.set_code + indent = p.compute_backslash_indent + + # Must be C_BACKSLASH continuation type. + errors = (('def function1(self, a, b\\\n'), # Bracket. + (' """ (\\\n'), # Docstring. + ('a = #\\\n'), # Inline comment. + ) + for string in errors: + with self.subTest(string=string): + setcode(string) + with self.assertRaises(AssertionError): + indent() + + TestInfo = namedtuple('TestInfo', ('string', 'spaces')) + tests = (TestInfo('a = (1 + 2) - 5 *\\\n', 4), + TestInfo('a = 1 + 2 - 5 *\\\n', 4), + TestInfo(' a = 1 + 2 - 5 *\\\n', 8), + TestInfo(' a = "spam"\\\n', 6), + TestInfo(' a = \\\n"a"\\\n', 4), + TestInfo(' a = #\\\n"a"\\\n', 5), + TestInfo('a == \\\n', 2), + TestInfo('a != \\\n', 2), + # Difference between containing = and those not. + TestInfo('\\\n', 2), + TestInfo(' \\\n', 6), + TestInfo('\t\\\n', 6), + TestInfo('a\\\n', 3), + TestInfo('{}\\\n', 4), + TestInfo('(1 + 2) - 5 *\\\n', 3), + ) + for test in tests: + with self.subTest(string=test.string): + setcode(test.string) + eq(indent(), test.spaces) + + def test_get_base_indent_string(self): + eq = self.assertEqual + p = self.parser + setcode = p.set_code + baseindent = p.get_base_indent_string + + TestInfo = namedtuple('TestInfo', ['string', 'indent']) + tests = (TestInfo('', ''), + TestInfo('def a():\n', ''), + TestInfo('\tdef a():\n', '\t'), + TestInfo(' def a():\n', ' '), + TestInfo(' def a(\n', ' '), + TestInfo('\t\n def a(\n', ' '), + TestInfo('\t\n # Comment.\n', ' '), + ) + + for test in tests: + with self.subTest(string=test.string): + setcode(test.string) + eq(baseindent(), test.indent) + + def test_is_block_opener(self): + yes = self.assertTrue + no = self.assertFalse + p = self.parser + setcode = p.set_code + opener = p.is_block_opener + + TestInfo = namedtuple('TestInfo', ['string', 'assert_']) + tests = ( + TestInfo('def a():\n', yes), + TestInfo('\n def function1(self, a,\n b):\n', yes), + TestInfo(':\n', yes), + TestInfo('a:\n', yes), + TestInfo('):\n', yes), + TestInfo('(:\n', yes), + TestInfo('":\n', no), + TestInfo('\n def function1(self, a,\n', no), + TestInfo('def function1(self, a):\n pass\n', no), + TestInfo('# A comment:\n', no), + TestInfo('"""A docstring:\n', no), + TestInfo('"""A docstring:\n', no), + ) + + for test in tests: + with self.subTest(string=test.string): + setcode(test.string) + test.assert_(opener()) + + def test_is_block_closer(self): + yes = self.assertTrue + no = self.assertFalse + p = self.parser + setcode = p.set_code + closer = p.is_block_closer + + TestInfo = namedtuple('TestInfo', ['string', 'assert_']) + tests = ( + TestInfo('return\n', yes), + TestInfo('\tbreak\n', yes), + TestInfo(' continue\n', yes), + TestInfo(' raise\n', yes), + TestInfo('pass \n', yes), + TestInfo('pass\t\n', yes), + TestInfo('return #\n', yes), + TestInfo('raised\n', no), + TestInfo('returning\n', no), + TestInfo('# return\n', no), + TestInfo('"""break\n', no), + TestInfo('"continue\n', no), + TestInfo('def function1(self, a):\n pass\n', yes), + ) + + for test in tests: + with self.subTest(string=test.string): + setcode(test.string) + test.assert_(closer()) + + def test_get_last_stmt_bracketing(self): + eq = self.assertEqual + p = self.parser + setcode = p.set_code + bracketing = p.get_last_stmt_bracketing + + TestInfo = namedtuple('TestInfo', ['string', 'bracket']) + tests = ( + TestInfo('', ((0, 0),)), + TestInfo('a\n', ((0, 0),)), + TestInfo('()()\n', ((0, 0), (0, 1), (2, 0), (2, 1), (4, 0))), + TestInfo('(\n)()\n', ((0, 0), (0, 1), (3, 0), (3, 1), (5, 0))), + TestInfo('()\n()\n', ((3, 0), (3, 1), (5, 0))), + TestInfo('()(\n)\n', ((0, 0), (0, 1), (2, 0), (2, 1), (5, 0))), + TestInfo('(())\n', ((0, 0), (0, 1), (1, 2), (3, 1), (4, 0))), + TestInfo('(\n())\n', ((0, 0), (0, 1), (2, 2), (4, 1), (5, 0))), + # Same as matched test. + TestInfo('{)(]\n', ((0, 0), (0, 1), (2, 0), (2, 1), (4, 0))), + TestInfo('(((())\n', + ((0, 0), (0, 1), (1, 2), (2, 3), (3, 4), (5, 3), (6, 2))), + ) + + for test in tests: + with self.subTest(string=test.string): + setcode(test.string) + eq(bracketing(), test.bracket) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_pyshell.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_pyshell.py new file mode 100644 index 0000000000000000000000000000000000000000..706703965bffd6f74d3b5916b4c21be8c897426b --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_pyshell.py @@ -0,0 +1,148 @@ +"Test pyshell, coverage 12%." +# Plus coverage of test_warning. Was 20% with test_openshell. + +from idlelib import pyshell +import unittest +from test.support import requires +from tkinter import Tk + + +class FunctionTest(unittest.TestCase): + # Test stand-alone module level non-gui functions. + + def test_restart_line_wide(self): + eq = self.assertEqual + for file, mul, extra in (('', 22, ''), ('finame', 21, '=')): + width = 60 + bar = mul * '=' + with self.subTest(file=file, bar=bar): + file = file or 'Shell' + line = pyshell.restart_line(width, file) + eq(len(line), width) + eq(line, f"{bar+extra} RESTART: {file} {bar}") + + def test_restart_line_narrow(self): + expect, taglen = "= RESTART: Shell", 16 + for width in (taglen-1, taglen, taglen+1): + with self.subTest(width=width): + self.assertEqual(pyshell.restart_line(width, ''), expect) + self.assertEqual(pyshell.restart_line(taglen+2, ''), expect+' =') + + +class PyShellFileListTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + + @classmethod + def tearDownClass(cls): + #cls.root.update_idletasks() +## for id in cls.root.tk.call('after', 'info'): +## cls.root.after_cancel(id) # Need for EditorWindow. + cls.root.destroy() + del cls.root + + def test_init(self): + psfl = pyshell.PyShellFileList(self.root) + self.assertEqual(psfl.EditorWindow, pyshell.PyShellEditorWindow) + self.assertIsNone(psfl.pyshell) + +# The following sometimes causes 'invalid command name "109734456recolorize"'. +# Uncommenting after_cancel above prevents this, but results in +# TclError: bad window path name ".!listedtoplevel.!frame.text" +# which is normally prevented by after_cancel. +## def test_openshell(self): +## pyshell.use_subprocess = False +## ps = pyshell.PyShellFileList(self.root).open_shell() +## self.assertIsInstance(ps, pyshell.PyShell) + + +class PyShellRemoveLastNewlineAndSurroundingWhitespaceTest(unittest.TestCase): + regexp = pyshell.PyShell._last_newline_re + + def all_removed(self, text): + self.assertEqual('', self.regexp.sub('', text)) + + def none_removed(self, text): + self.assertEqual(text, self.regexp.sub('', text)) + + def check_result(self, text, expected): + self.assertEqual(expected, self.regexp.sub('', text)) + + def test_empty(self): + self.all_removed('') + + def test_newline(self): + self.all_removed('\n') + + def test_whitespace_no_newline(self): + self.all_removed(' ') + self.all_removed(' ') + self.all_removed(' ') + self.all_removed(' ' * 20) + self.all_removed('\t') + self.all_removed('\t\t') + self.all_removed('\t\t\t') + self.all_removed('\t' * 20) + self.all_removed('\t ') + self.all_removed(' \t') + self.all_removed(' \t \t ') + self.all_removed('\t \t \t') + + def test_newline_with_whitespace(self): + self.all_removed(' \n') + self.all_removed('\t\n') + self.all_removed(' \t\n') + self.all_removed('\t \n') + self.all_removed('\n ') + self.all_removed('\n\t') + self.all_removed('\n \t') + self.all_removed('\n\t ') + self.all_removed(' \n ') + self.all_removed('\t\n ') + self.all_removed(' \n\t') + self.all_removed('\t\n\t') + self.all_removed('\t \t \t\n') + self.all_removed(' \t \t \n') + self.all_removed('\n\t \t \t') + self.all_removed('\n \t \t ') + + def test_multiple_newlines(self): + self.check_result('\n\n', '\n') + self.check_result('\n' * 5, '\n' * 4) + self.check_result('\n' * 5 + '\t', '\n' * 4) + self.check_result('\n' * 20, '\n' * 19) + self.check_result('\n' * 20 + ' ', '\n' * 19) + self.check_result(' \n \n ', ' \n') + self.check_result(' \n\n ', ' \n') + self.check_result(' \n\n', ' \n') + self.check_result('\t\n\n', '\t\n') + self.check_result('\n\n ', '\n') + self.check_result('\n\n\t', '\n') + self.check_result(' \n \n ', ' \n') + self.check_result('\t\n\t\n\t', '\t\n') + + def test_non_whitespace(self): + self.none_removed('a') + self.check_result('a\n', 'a') + self.check_result('a\n ', 'a') + self.check_result('a \n ', 'a') + self.check_result('a \n\t', 'a') + self.none_removed('-') + self.check_result('-\n', '-') + self.none_removed('.') + self.check_result('.\n', '.') + + def test_unsupported_whitespace(self): + self.none_removed('\v') + self.none_removed('\n\v') + self.check_result('\v\n', '\v') + self.none_removed(' \n\v') + self.check_result('\v\n ', '\v') + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_query.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_query.py new file mode 100644 index 0000000000000000000000000000000000000000..ee368255f9b5c7e58266ae88041fa3adcc494418 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_query.py @@ -0,0 +1,452 @@ +"""Test query, coverage 93%. + +Non-gui tests for Query, SectionName, ModuleName, and HelpSource use +dummy versions that extract the non-gui methods and add other needed +attributes. GUI tests create an instance of each class and simulate +entries and button clicks. Subclass tests only target the new code in +the subclass definition. + +The appearance of the widgets is checked by the Query and +HelpSource htests. These are run by running query.py. +""" +from idlelib import query +import unittest +from test.support import requires +from test.support.testcase import ExtraAssertions +from tkinter import Tk, END + +import sys +from unittest import mock +from idlelib.idle_test.mock_tk import Var + + +# NON-GUI TESTS + +class QueryTest(unittest.TestCase): + "Test Query base class." + + class Dummy_Query: + # Test the following Query methods. + entry_ok = query.Query.entry_ok + ok = query.Query.ok + cancel = query.Query.cancel + # Add attributes and initialization needed for tests. + def __init__(self, dummy_entry): + self.entry = Var(value=dummy_entry) + self.entry_error = {'text': ''} + self.result = None + self.destroyed = False + def showerror(self, message): + self.entry_error['text'] = message + def destroy(self): + self.destroyed = True + + def test_entry_ok_blank(self): + dialog = self.Dummy_Query(' ') + self.assertEqual(dialog.entry_ok(), None) + self.assertEqual((dialog.result, dialog.destroyed), (None, False)) + self.assertIn('blank line', dialog.entry_error['text']) + + def test_entry_ok_good(self): + dialog = self.Dummy_Query(' good ') + Equal = self.assertEqual + Equal(dialog.entry_ok(), 'good') + Equal((dialog.result, dialog.destroyed), (None, False)) + Equal(dialog.entry_error['text'], '') + + def test_ok_blank(self): + dialog = self.Dummy_Query('') + dialog.entry.focus_set = mock.Mock() + self.assertEqual(dialog.ok(), None) + self.assertTrue(dialog.entry.focus_set.called) + del dialog.entry.focus_set + self.assertEqual((dialog.result, dialog.destroyed), (None, False)) + + def test_ok_good(self): + dialog = self.Dummy_Query('good') + self.assertEqual(dialog.ok(), None) + self.assertEqual((dialog.result, dialog.destroyed), ('good', True)) + + def test_cancel(self): + dialog = self.Dummy_Query('does not matter') + self.assertEqual(dialog.cancel(), None) + self.assertEqual((dialog.result, dialog.destroyed), (None, True)) + + +class SectionNameTest(unittest.TestCase): + "Test SectionName subclass of Query." + + class Dummy_SectionName: + entry_ok = query.SectionName.entry_ok # Function being tested. + used_names = ['used'] + def __init__(self, dummy_entry): + self.entry = Var(value=dummy_entry) + self.entry_error = {'text': ''} + def showerror(self, message): + self.entry_error['text'] = message + + def test_blank_section_name(self): + dialog = self.Dummy_SectionName(' ') + self.assertEqual(dialog.entry_ok(), None) + self.assertIn('no name', dialog.entry_error['text']) + + def test_used_section_name(self): + dialog = self.Dummy_SectionName('used') + self.assertEqual(dialog.entry_ok(), None) + self.assertIn('use', dialog.entry_error['text']) + + def test_long_section_name(self): + dialog = self.Dummy_SectionName('good'*8) + self.assertEqual(dialog.entry_ok(), None) + self.assertIn('longer than 30', dialog.entry_error['text']) + + def test_good_section_name(self): + dialog = self.Dummy_SectionName(' good ') + self.assertEqual(dialog.entry_ok(), 'good') + self.assertEqual(dialog.entry_error['text'], '') + + +class ModuleNameTest(unittest.TestCase, ExtraAssertions): + "Test ModuleName subclass of Query." + + class Dummy_ModuleName: + entry_ok = query.ModuleName.entry_ok # Function being tested. + text0 = '' + def __init__(self, dummy_entry): + self.entry = Var(value=dummy_entry) + self.entry_error = {'text': ''} + def showerror(self, message): + self.entry_error['text'] = message + + def test_blank_module_name(self): + dialog = self.Dummy_ModuleName(' ') + self.assertEqual(dialog.entry_ok(), None) + self.assertIn('no name', dialog.entry_error['text']) + + def test_bogus_module_name(self): + dialog = self.Dummy_ModuleName('__name_xyz123_should_not_exist__') + self.assertEqual(dialog.entry_ok(), None) + self.assertIn('not found', dialog.entry_error['text']) + + def test_c_source_name(self): + dialog = self.Dummy_ModuleName('itertools') + self.assertEqual(dialog.entry_ok(), None) + self.assertIn('source-based', dialog.entry_error['text']) + + def test_good_module_name(self): + dialog = self.Dummy_ModuleName('idlelib') + self.assertEndsWith(dialog.entry_ok(), '__init__.py') + self.assertEqual(dialog.entry_error['text'], '') + dialog = self.Dummy_ModuleName('idlelib.idle') + self.assertEndsWith(dialog.entry_ok(), 'idle.py') + self.assertEqual(dialog.entry_error['text'], '') + + +class GotoTest(unittest.TestCase): + "Test Goto subclass of Query." + + class Dummy_ModuleName: + entry_ok = query.Goto.entry_ok # Function being tested. + def __init__(self, dummy_entry): + self.entry = Var(value=dummy_entry) + self.entry_error = {'text': ''} + def showerror(self, message): + self.entry_error['text'] = message + + def test_bogus_goto(self): + dialog = self.Dummy_ModuleName('a') + self.assertEqual(dialog.entry_ok(), None) + self.assertIn('not a base 10 integer', dialog.entry_error['text']) + + def test_bad_goto(self): + dialog = self.Dummy_ModuleName('0') + self.assertEqual(dialog.entry_ok(), None) + self.assertIn('not a positive integer', dialog.entry_error['text']) + + def test_good_goto(self): + dialog = self.Dummy_ModuleName('1') + self.assertEqual(dialog.entry_ok(), 1) + self.assertEqual(dialog.entry_error['text'], '') + + +# 3 HelpSource test classes each test one method. + +class HelpsourceBrowsefileTest(unittest.TestCase): + "Test browse_file method of ModuleName subclass of Query." + + class Dummy_HelpSource: + browse_file = query.HelpSource.browse_file + pathvar = Var() + + def test_file_replaces_path(self): + dialog = self.Dummy_HelpSource() + # Path is widget entry, either '' or something. + # Func return is file dialog return, either '' or something. + # Func return should override widget entry. + # We need all 4 combinations to test all (most) code paths. + for path, func, result in ( + ('', lambda a,b,c:'', ''), + ('', lambda a,b,c: __file__, __file__), + ('htest', lambda a,b,c:'', 'htest'), + ('htest', lambda a,b,c: __file__, __file__)): + with self.subTest(): + dialog.pathvar.set(path) + dialog.askfilename = func + dialog.browse_file() + self.assertEqual(dialog.pathvar.get(), result) + + +class HelpsourcePathokTest(unittest.TestCase): + "Test path_ok method of HelpSource subclass of Query." + + class Dummy_HelpSource: + path_ok = query.HelpSource.path_ok + def __init__(self, dummy_path): + self.path = Var(value=dummy_path) + self.path_error = {'text': ''} + def showerror(self, message, widget=None): + self.path_error['text'] = message + + orig_platform = query.platform # Set in test_path_ok_file. + @classmethod + def tearDownClass(cls): + query.platform = cls.orig_platform + + def test_path_ok_blank(self): + dialog = self.Dummy_HelpSource(' ') + self.assertEqual(dialog.path_ok(), None) + self.assertIn('no help file', dialog.path_error['text']) + + def test_path_ok_bad(self): + dialog = self.Dummy_HelpSource(__file__ + 'bad-bad-bad') + self.assertEqual(dialog.path_ok(), None) + self.assertIn('not exist', dialog.path_error['text']) + + def test_path_ok_web(self): + dialog = self.Dummy_HelpSource('') + Equal = self.assertEqual + for url in 'www.py.org', 'http://py.org': + with self.subTest(): + dialog.path.set(url) + self.assertEqual(dialog.path_ok(), url) + self.assertEqual(dialog.path_error['text'], '') + + def test_path_ok_file(self): + dialog = self.Dummy_HelpSource('') + for platform, prefix in ('darwin', 'file://'), ('other', ''): + with self.subTest(): + query.platform = platform + dialog.path.set(__file__) + self.assertEqual(dialog.path_ok(), prefix + __file__) + self.assertEqual(dialog.path_error['text'], '') + + +class HelpsourceEntryokTest(unittest.TestCase): + "Test entry_ok method of HelpSource subclass of Query." + + class Dummy_HelpSource: + entry_ok = query.HelpSource.entry_ok + entry_error = {} + path_error = {} + def item_ok(self): + return self.name + def path_ok(self): + return self.path + + def test_entry_ok_helpsource(self): + dialog = self.Dummy_HelpSource() + for name, path, result in ((None, None, None), + (None, 'doc.txt', None), + ('doc', None, None), + ('doc', 'doc.txt', ('doc', 'doc.txt'))): + with self.subTest(): + dialog.name, dialog.path = name, path + self.assertEqual(dialog.entry_ok(), result) + + +# 2 CustomRun test classes each test one method. + +class CustomRunCLIargsokTest(unittest.TestCase): + "Test cli_ok method of the CustomRun subclass of Query." + + class Dummy_CustomRun: + cli_args_ok = query.CustomRun.cli_args_ok + def __init__(self, dummy_entry): + self.entry = Var(value=dummy_entry) + self.entry_error = {'text': ''} + def showerror(self, message): + self.entry_error['text'] = message + + def test_blank_args(self): + dialog = self.Dummy_CustomRun(' ') + self.assertEqual(dialog.cli_args_ok(), []) + + def test_invalid_args(self): + dialog = self.Dummy_CustomRun("'no-closing-quote") + self.assertEqual(dialog.cli_args_ok(), None) + self.assertIn('No closing', dialog.entry_error['text']) + + def test_good_args(self): + args = ['-n', '10', '--verbose', '-p', '/path', '--name'] + dialog = self.Dummy_CustomRun(' '.join(args) + ' "my name"') + self.assertEqual(dialog.cli_args_ok(), args + ["my name"]) + self.assertEqual(dialog.entry_error['text'], '') + + +class CustomRunEntryokTest(unittest.TestCase): + "Test entry_ok method of the CustomRun subclass of Query." + + class Dummy_CustomRun: + entry_ok = query.CustomRun.entry_ok + entry_error = {} + restartvar = Var() + def cli_args_ok(self): + return self.cli_args + + def test_entry_ok_customrun(self): + dialog = self.Dummy_CustomRun() + for restart in {True, False}: + dialog.restartvar.set(restart) + for cli_args, result in ((None, None), + (['my arg'], (['my arg'], restart))): + with self.subTest(restart=restart, cli_args=cli_args): + dialog.cli_args = cli_args + self.assertEqual(dialog.entry_ok(), result) + + +# GUI TESTS + +class QueryGuiTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = root = Tk() + cls.root.withdraw() + cls.dialog = query.Query(root, 'TEST', 'test', _utest=True) + cls.dialog.destroy = mock.Mock() + + @classmethod + def tearDownClass(cls): + del cls.dialog.destroy + del cls.dialog + cls.root.destroy() + del cls.root + + def setUp(self): + self.dialog.entry.delete(0, 'end') + self.dialog.result = None + self.dialog.destroy.reset_mock() + + def test_click_ok(self): + dialog = self.dialog + dialog.entry.insert(0, 'abc') + dialog.button_ok.invoke() + self.assertEqual(dialog.result, 'abc') + self.assertTrue(dialog.destroy.called) + + def test_click_blank(self): + dialog = self.dialog + dialog.button_ok.invoke() + self.assertEqual(dialog.result, None) + self.assertFalse(dialog.destroy.called) + + def test_click_cancel(self): + dialog = self.dialog + dialog.entry.insert(0, 'abc') + dialog.button_cancel.invoke() + self.assertEqual(dialog.result, None) + self.assertTrue(dialog.destroy.called) + + +class SectionnameGuiTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + + def test_click_section_name(self): + root = Tk() + root.withdraw() + dialog = query.SectionName(root, 'T', 't', {'abc'}, _utest=True) + Equal = self.assertEqual + self.assertEqual(dialog.used_names, {'abc'}) + dialog.entry.insert(0, 'okay') + dialog.button_ok.invoke() + self.assertEqual(dialog.result, 'okay') + root.destroy() + + +class ModulenameGuiTest(unittest.TestCase, ExtraAssertions): + + @classmethod + def setUpClass(cls): + requires('gui') + + def test_click_module_name(self): + root = Tk() + root.withdraw() + dialog = query.ModuleName(root, 'T', 't', 'idlelib', _utest=True) + self.assertEqual(dialog.text0, 'idlelib') + self.assertEqual(dialog.entry.get(), 'idlelib') + dialog.button_ok.invoke() + self.assertEndsWith(dialog.result, '__init__.py') + root.destroy() + + +class GotoGuiTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + + def test_click_module_name(self): + root = Tk() + root.withdraw() + dialog = query.Goto(root, 'T', 't', _utest=True) + dialog.entry.insert(0, '22') + dialog.button_ok.invoke() + self.assertEqual(dialog.result, 22) + root.destroy() + + +class HelpsourceGuiTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + + def test_click_help_source(self): + root = Tk() + root.withdraw() + dialog = query.HelpSource(root, 'T', menuitem='__test__', + filepath=__file__, _utest=True) + Equal = self.assertEqual + Equal(dialog.entry.get(), '__test__') + Equal(dialog.path.get(), __file__) + dialog.button_ok.invoke() + prefix = "file://" if sys.platform == 'darwin' else '' + Equal(dialog.result, ('__test__', prefix + __file__)) + root.destroy() + + +class CustomRunGuiTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + + def test_click_args(self): + root = Tk() + root.withdraw() + dialog = query.CustomRun(root, 'Title', + cli_args=['a', 'b=1'], _utest=True) + self.assertEqual(dialog.entry.get(), 'a b=1') + dialog.entry.insert(END, ' c') + dialog.button_ok.invoke() + self.assertEqual(dialog.result, (['a', 'b=1', 'c'], True)) + root.destroy() + + +if __name__ == '__main__': + unittest.main(verbosity=2, exit=False) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_redirector.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_redirector.py new file mode 100644 index 0000000000000000000000000000000000000000..7bd1116debc23827b46b461bac81aec57c071df8 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_redirector.py @@ -0,0 +1,123 @@ +"Test redirector, coverage 100%." + +from idlelib.redirector import WidgetRedirector +import unittest +from test.support import requires +from test.support.testcase import ExtraAssertions +from tkinter import Tk, Text, TclError +from idlelib.idle_test.mock_idle import Func + + +class InitCloseTest(unittest.TestCase, ExtraAssertions): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.text = Text(cls.root) + + @classmethod + def tearDownClass(cls): + del cls.text + cls.root.destroy() + del cls.root + + def test_init(self): + redir = WidgetRedirector(self.text) + self.assertEqual(redir.widget, self.text) + self.assertEqual(redir.tk, self.text.tk) + self.assertRaises(TclError, WidgetRedirector, self.text) + redir.close() # restore self.tk, self.text + + def test_close(self): + redir = WidgetRedirector(self.text) + redir.register('insert', Func) + redir.close() + self.assertEqual(redir._operations, {}) + self.assertNotHasAttr(self.text, 'widget') + + +class WidgetRedirectorTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.text = Text(cls.root) + + @classmethod + def tearDownClass(cls): + del cls.text + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def setUp(self): + self.redir = WidgetRedirector(self.text) + self.func = Func() + self.orig_insert = self.redir.register('insert', self.func) + self.text.insert('insert', 'asdf') # leaves self.text empty + + def tearDown(self): + self.text.delete('1.0', 'end') + self.redir.close() + + def test_repr(self): # partly for 100% coverage + self.assertIn('Redirector', repr(self.redir)) + self.assertIn('Original', repr(self.orig_insert)) + + def test_register(self): + self.assertEqual(self.text.get('1.0', 'end'), '\n') + self.assertEqual(self.func.args, ('insert', 'asdf')) + self.assertIn('insert', self.redir._operations) + self.assertIn('insert', self.text.__dict__) + self.assertEqual(self.text.insert, self.func) + + def test_original_command(self): + self.assertEqual(self.orig_insert.operation, 'insert') + self.assertEqual(self.orig_insert.tk_call, self.text.tk.call) + self.orig_insert('insert', 'asdf') + self.assertEqual(self.text.get('1.0', 'end'), 'asdf\n') + + def test_unregister(self): + self.assertIsNone(self.redir.unregister('invalid operation name')) + self.assertEqual(self.redir.unregister('insert'), self.func) + self.assertNotIn('insert', self.redir._operations) + self.assertNotIn('insert', self.text.__dict__) + + def test_unregister_no_attribute(self): + del self.text.insert + self.assertEqual(self.redir.unregister('insert'), self.func) + + def test_dispatch_intercept(self): + self.func.__init__(True) + self.assertTrue(self.redir.dispatch('insert', False)) + self.assertFalse(self.func.args[0]) + + def test_dispatch_bypass(self): + self.orig_insert('insert', 'asdf') + # tk.call returns '' where Python would return None + self.assertEqual(self.redir.dispatch('delete', '1.0', 'end'), '') + self.assertEqual(self.text.get('1.0', 'end'), '\n') + + def test_dispatch_error(self): + self.func.__init__(TclError()) + self.assertEqual(self.redir.dispatch('insert', False), '') + self.assertEqual(self.redir.dispatch('invalid'), '') + + def test_command_dispatch(self): + # Test that .__init__ causes redirection of tk calls + # through redir.dispatch + self.root.call(self.text._w, 'insert', 'hello') + self.assertEqual(self.func.args, ('hello',)) + self.assertEqual(self.text.get('1.0', 'end'), '\n') + # Ensure that called through redir .dispatch and not through + # self.text.insert by having mock raise TclError. + self.func.__init__(TclError()) + self.assertEqual(self.root.call(self.text._w, 'insert', 'boo'), '') + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_replace.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_replace.py new file mode 100644 index 0000000000000000000000000000000000000000..6c07389b29ad4558077353dd65eccb32c722dcba --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_replace.py @@ -0,0 +1,294 @@ +"Test replace, coverage 78%." + +from idlelib.replace import ReplaceDialog +import unittest +from test.support import requires +requires('gui') +from tkinter import Tk, Text + +from unittest.mock import Mock +from idlelib.idle_test.mock_tk import Mbox +import idlelib.searchengine as se + +orig_mbox = se.messagebox +showerror = Mbox.showerror + + +class ReplaceDialogTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + cls.root = Tk() + cls.root.withdraw() + se.messagebox = Mbox + cls.engine = se.SearchEngine(cls.root) + cls.dialog = ReplaceDialog(cls.root, cls.engine) + cls.dialog.bell = lambda: None + cls.dialog.ok = Mock() + cls.text = Text(cls.root) + cls.text.undo_block_start = Mock() + cls.text.undo_block_stop = Mock() + cls.dialog.text = cls.text + + @classmethod + def tearDownClass(cls): + se.messagebox = orig_mbox + del cls.text, cls.dialog, cls.engine + cls.root.destroy() + del cls.root + + def setUp(self): + self.text.insert('insert', 'This is a sample sTring') + + def tearDown(self): + self.engine.patvar.set('') + self.dialog.replvar.set('') + self.engine.wordvar.set(False) + self.engine.casevar.set(False) + self.engine.revar.set(False) + self.engine.wrapvar.set(True) + self.engine.backvar.set(False) + showerror.title = '' + showerror.message = '' + self.text.delete('1.0', 'end') + + def test_replace_simple(self): + # Test replace function with all options at default setting. + # Wrap around - True + # Regular Expression - False + # Match case - False + # Match word - False + # Direction - Forwards + text = self.text + equal = self.assertEqual + pv = self.engine.patvar + rv = self.dialog.replvar + replace = self.dialog.replace_it + + # test accessor method + self.engine.setpat('asdf') + equal(self.engine.getpat(), pv.get()) + + # text found and replaced + pv.set('a') + rv.set('asdf') + replace() + equal(text.get('1.8', '1.12'), 'asdf') + + # don't "match word" case + text.mark_set('insert', '1.0') + pv.set('is') + rv.set('hello') + replace() + equal(text.get('1.2', '1.7'), 'hello') + + # don't "match case" case + pv.set('string') + rv.set('world') + replace() + equal(text.get('1.23', '1.28'), 'world') + + # without "regular expression" case + text.mark_set('insert', 'end') + text.insert('insert', '\nline42:') + before_text = text.get('1.0', 'end') + pv.set(r'[a-z][\d]+') + replace() + after_text = text.get('1.0', 'end') + equal(before_text, after_text) + + # test with wrap around selected and complete a cycle + text.mark_set('insert', '1.9') + pv.set('i') + rv.set('j') + replace() + equal(text.get('1.8'), 'i') + equal(text.get('2.1'), 'j') + replace() + equal(text.get('2.1'), 'j') + equal(text.get('1.8'), 'j') + before_text = text.get('1.0', 'end') + replace() + after_text = text.get('1.0', 'end') + equal(before_text, after_text) + + # text not found + before_text = text.get('1.0', 'end') + pv.set('foobar') + replace() + after_text = text.get('1.0', 'end') + equal(before_text, after_text) + + # test access method + self.dialog.find_it(0) + + def test_replace_wrap_around(self): + text = self.text + equal = self.assertEqual + pv = self.engine.patvar + rv = self.dialog.replvar + replace = self.dialog.replace_it + self.engine.wrapvar.set(False) + + # replace candidate found both after and before 'insert' + text.mark_set('insert', '1.4') + pv.set('i') + rv.set('j') + replace() + equal(text.get('1.2'), 'i') + equal(text.get('1.5'), 'j') + replace() + equal(text.get('1.2'), 'i') + equal(text.get('1.20'), 'j') + replace() + equal(text.get('1.2'), 'i') + + # replace candidate found only before 'insert' + text.mark_set('insert', '1.8') + pv.set('is') + before_text = text.get('1.0', 'end') + replace() + after_text = text.get('1.0', 'end') + equal(before_text, after_text) + + def test_replace_whole_word(self): + text = self.text + equal = self.assertEqual + pv = self.engine.patvar + rv = self.dialog.replvar + replace = self.dialog.replace_it + self.engine.wordvar.set(True) + + pv.set('is') + rv.set('hello') + replace() + equal(text.get('1.0', '1.4'), 'This') + equal(text.get('1.5', '1.10'), 'hello') + + def test_replace_match_case(self): + equal = self.assertEqual + text = self.text + pv = self.engine.patvar + rv = self.dialog.replvar + replace = self.dialog.replace_it + self.engine.casevar.set(True) + + before_text = self.text.get('1.0', 'end') + pv.set('this') + rv.set('that') + replace() + after_text = self.text.get('1.0', 'end') + equal(before_text, after_text) + + pv.set('This') + replace() + equal(text.get('1.0', '1.4'), 'that') + + def test_replace_regex(self): + equal = self.assertEqual + text = self.text + pv = self.engine.patvar + rv = self.dialog.replvar + replace = self.dialog.replace_it + self.engine.revar.set(True) + + before_text = text.get('1.0', 'end') + pv.set(r'[a-z][\d]+') + rv.set('hello') + replace() + after_text = text.get('1.0', 'end') + equal(before_text, after_text) + + text.insert('insert', '\nline42') + replace() + equal(text.get('2.0', '2.8'), 'linhello') + + pv.set('') + replace() + self.assertIn('error', showerror.title) + self.assertIn('Empty', showerror.message) + + pv.set(r'[\d') + replace() + self.assertIn('error', showerror.title) + self.assertIn('Pattern', showerror.message) + + showerror.title = '' + showerror.message = '' + pv.set('[a]') + rv.set('test\\') + replace() + self.assertIn('error', showerror.title) + self.assertIn('Invalid Replace Expression', showerror.message) + + # test access method + self.engine.setcookedpat("?") + equal(pv.get(), "\\?") + + def test_replace_backwards(self): + equal = self.assertEqual + text = self.text + pv = self.engine.patvar + rv = self.dialog.replvar + replace = self.dialog.replace_it + self.engine.backvar.set(True) + + text.insert('insert', '\nis as ') + + pv.set('is') + rv.set('was') + replace() + equal(text.get('1.2', '1.4'), 'is') + equal(text.get('2.0', '2.3'), 'was') + replace() + equal(text.get('1.5', '1.8'), 'was') + replace() + equal(text.get('1.2', '1.5'), 'was') + + def test_replace_all(self): + text = self.text + pv = self.engine.patvar + rv = self.dialog.replvar + replace_all = self.dialog.replace_all + + text.insert('insert', '\n') + text.insert('insert', text.get('1.0', 'end')*100) + pv.set('is') + rv.set('was') + replace_all() + self.assertNotIn('is', text.get('1.0', 'end')) + + self.engine.revar.set(True) + pv.set('') + replace_all() + self.assertIn('error', showerror.title) + self.assertIn('Empty', showerror.message) + + pv.set('[s][T]') + rv.set('\\') + replace_all() + + self.engine.revar.set(False) + pv.set('text which is not present') + rv.set('foobar') + replace_all() + + def test_default_command(self): + text = self.text + pv = self.engine.patvar + rv = self.dialog.replvar + replace_find = self.dialog.default_command + equal = self.assertEqual + + pv.set('This') + rv.set('was') + replace_find() + equal(text.get('sel.first', 'sel.last'), 'was') + + self.engine.revar.set(True) + pv.set('') + replace_find() + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_rpc.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_rpc.py new file mode 100644 index 0000000000000000000000000000000000000000..81eff398c72f45b9cc25546513be2cb861e490b8 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_rpc.py @@ -0,0 +1,29 @@ +"Test rpc, coverage 20%." + +from idlelib import rpc +import unittest + + + +class CodePicklerTest(unittest.TestCase): + + def test_pickle_unpickle(self): + def f(): return a + b + c + func, (cbytes,) = rpc.pickle_code(f.__code__) + self.assertIs(func, rpc.unpickle_code) + self.assertIn(b'test_rpc.py', cbytes) + code = rpc.unpickle_code(cbytes) + self.assertEqual(code.co_names, ('a', 'b', 'c')) + + def test_code_pickler(self): + self.assertIn(type((lambda:None).__code__), + rpc.CodePickler.dispatch_table) + + def test_dumps(self): + def f(): pass + # The main test here is that pickling code does not raise. + self.assertIn(b'test_rpc.py', rpc.dumps(f.__code__)) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_run.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_run.py new file mode 100644 index 0000000000000000000000000000000000000000..83ecbffa2a197e7460ba98402f197a689bd43a4d --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_run.py @@ -0,0 +1,433 @@ +"Test run, coverage 54%." + +from idlelib import run +import io +import sys +from test.support import captured_output, captured_stderr +import unittest +from unittest import mock +import idlelib +from idlelib.idle_test.mock_idle import Func +from test.support import force_not_colorized + +idlelib.testing = True # Use {} for executing test user code. + + +class ExceptionTest(unittest.TestCase): + + def test_print_exception_unhashable(self): + class UnhashableException(Exception): + def __eq__(self, other): + return True + + ex1 = UnhashableException('ex1') + ex2 = UnhashableException('ex2') + try: + raise ex2 from ex1 + except UnhashableException: + try: + raise ex1 + except UnhashableException: + with captured_stderr() as output: + with mock.patch.object(run, 'cleanup_traceback') as ct: + ct.side_effect = lambda t, e: t + run.print_exception() + + tb = output.getvalue().strip().splitlines() + self.assertEqual(11, len(tb)) + self.assertIn('UnhashableException: ex2', tb[3]) + self.assertIn('UnhashableException: ex1', tb[10]) + + data = (('1/0', ZeroDivisionError, "division by zero\n"), + ('abc', NameError, "name 'abc' is not defined. " + "Did you mean: 'abs'? " + "Or did you forget to import 'abc'?\n"), + ('int.reel', AttributeError, + "type object 'int' has no attribute 'reel'. " + "Did you mean: 'real'?\n"), + ) + + @force_not_colorized + def test_get_message(self): + for code, exc, msg in self.data: + with self.subTest(code=code): + try: + eval(compile(code, '', 'eval')) + except exc: + typ, val, tb = sys.exc_info() + actual = run.get_message_lines(typ, val, tb)[0] + expect = f'{exc.__name__}: {msg}' + self.assertEqual(actual, expect) + + @force_not_colorized + @mock.patch.object(run, 'cleanup_traceback', + new_callable=lambda: (lambda t, e: None)) + def test_get_multiple_message(self, mock): + d = self.data + data2 = ((d[0], d[1]), (d[1], d[2]), (d[2], d[0])) + subtests = 0 + for (code1, exc1, msg1), (code2, exc2, msg2) in data2: + with self.subTest(codes=(code1,code2)): + try: + eval(compile(code1, '', 'eval')) + except exc1: + try: + eval(compile(code2, '', 'eval')) + except exc2: + with captured_stderr() as output: + run.print_exception() + actual = output.getvalue() + self.assertIn(msg1, actual) + self.assertIn(msg2, actual) + subtests += 1 + self.assertEqual(subtests, len(data2)) # All subtests ran? + +# StdioFile tests. + +class S(str): + def __str__(self): + return '%s:str' % type(self).__name__ + def __unicode__(self): + return '%s:unicode' % type(self).__name__ + def __len__(self): + return 3 + def __iter__(self): + return iter('abc') + def __getitem__(self, *args): + return '%s:item' % type(self).__name__ + def __getslice__(self, *args): + return '%s:slice' % type(self).__name__ + + +class MockShell: + def __init__(self): + self.reset() + def write(self, *args): + self.written.append(args) + def readline(self): + return self.lines.pop() + def close(self): + pass + def reset(self): + self.written = [] + def push(self, lines): + self.lines = list(lines)[::-1] + + +class StdInputFilesTest(unittest.TestCase): + + def test_misc(self): + shell = MockShell() + f = run.StdInputFile(shell, 'stdin') + self.assertIsInstance(f, io.TextIOBase) + self.assertEqual(f.encoding, 'utf-8') + self.assertEqual(f.errors, 'strict') + self.assertIsNone(f.newlines) + self.assertEqual(f.name, '') + self.assertFalse(f.closed) + self.assertTrue(f.isatty()) + self.assertTrue(f.readable()) + self.assertFalse(f.writable()) + self.assertFalse(f.seekable()) + + def test_unsupported(self): + shell = MockShell() + f = run.StdInputFile(shell, 'stdin') + self.assertRaises(OSError, f.fileno) + self.assertRaises(OSError, f.tell) + self.assertRaises(OSError, f.seek, 0) + self.assertRaises(OSError, f.write, 'x') + self.assertRaises(OSError, f.writelines, ['x']) + + def test_read(self): + shell = MockShell() + f = run.StdInputFile(shell, 'stdin') + shell.push(['one\n', 'two\n', '']) + self.assertEqual(f.read(), 'one\ntwo\n') + shell.push(['one\n', 'two\n', '']) + self.assertEqual(f.read(-1), 'one\ntwo\n') + shell.push(['one\n', 'two\n', '']) + self.assertEqual(f.read(None), 'one\ntwo\n') + shell.push(['one\n', 'two\n', 'three\n', '']) + self.assertEqual(f.read(2), 'on') + self.assertEqual(f.read(3), 'e\nt') + self.assertEqual(f.read(10), 'wo\nthree\n') + + shell.push(['one\n', 'two\n']) + self.assertEqual(f.read(0), '') + self.assertRaises(TypeError, f.read, 1.5) + self.assertRaises(TypeError, f.read, '1') + self.assertRaises(TypeError, f.read, 1, 1) + + def test_readline(self): + shell = MockShell() + f = run.StdInputFile(shell, 'stdin') + shell.push(['one\n', 'two\n', 'three\n', 'four\n']) + self.assertEqual(f.readline(), 'one\n') + self.assertEqual(f.readline(-1), 'two\n') + self.assertEqual(f.readline(None), 'three\n') + shell.push(['one\ntwo\n']) + self.assertEqual(f.readline(), 'one\n') + self.assertEqual(f.readline(), 'two\n') + shell.push(['one', 'two', 'three']) + self.assertEqual(f.readline(), 'one') + self.assertEqual(f.readline(), 'two') + shell.push(['one\n', 'two\n', 'three\n']) + self.assertEqual(f.readline(2), 'on') + self.assertEqual(f.readline(1), 'e') + self.assertEqual(f.readline(1), '\n') + self.assertEqual(f.readline(10), 'two\n') + + shell.push(['one\n', 'two\n']) + self.assertEqual(f.readline(0), '') + self.assertRaises(TypeError, f.readlines, 1.5) + self.assertRaises(TypeError, f.readlines, '1') + self.assertRaises(TypeError, f.readlines, 1, 1) + + def test_readlines(self): + shell = MockShell() + f = run.StdInputFile(shell, 'stdin') + shell.push(['one\n', 'two\n', '']) + self.assertEqual(f.readlines(), ['one\n', 'two\n']) + shell.push(['one\n', 'two\n', '']) + self.assertEqual(f.readlines(-1), ['one\n', 'two\n']) + shell.push(['one\n', 'two\n', '']) + self.assertEqual(f.readlines(None), ['one\n', 'two\n']) + shell.push(['one\n', 'two\n', '']) + self.assertEqual(f.readlines(0), ['one\n', 'two\n']) + shell.push(['one\n', 'two\n', '']) + self.assertEqual(f.readlines(3), ['one\n']) + shell.push(['one\n', 'two\n', '']) + self.assertEqual(f.readlines(4), ['one\n', 'two\n']) + + shell.push(['one\n', 'two\n', '']) + self.assertRaises(TypeError, f.readlines, 1.5) + self.assertRaises(TypeError, f.readlines, '1') + self.assertRaises(TypeError, f.readlines, 1, 1) + + def test_close(self): + shell = MockShell() + f = run.StdInputFile(shell, 'stdin') + shell.push(['one\n', 'two\n', '']) + self.assertFalse(f.closed) + self.assertEqual(f.readline(), 'one\n') + f.close() + self.assertFalse(f.closed) + self.assertEqual(f.readline(), 'two\n') + self.assertRaises(TypeError, f.close, 1) + + +class StdOutputFilesTest(unittest.TestCase): + + def test_misc(self): + shell = MockShell() + f = run.StdOutputFile(shell, 'stdout') + self.assertIsInstance(f, io.TextIOBase) + self.assertEqual(f.encoding, 'utf-8') + self.assertEqual(f.errors, 'strict') + self.assertIsNone(f.newlines) + self.assertEqual(f.name, '') + self.assertFalse(f.closed) + self.assertTrue(f.isatty()) + self.assertFalse(f.readable()) + self.assertTrue(f.writable()) + self.assertFalse(f.seekable()) + + def test_unsupported(self): + shell = MockShell() + f = run.StdOutputFile(shell, 'stdout') + self.assertRaises(OSError, f.fileno) + self.assertRaises(OSError, f.tell) + self.assertRaises(OSError, f.seek, 0) + self.assertRaises(OSError, f.read, 0) + self.assertRaises(OSError, f.readline, 0) + + def test_write(self): + shell = MockShell() + f = run.StdOutputFile(shell, 'stdout') + f.write('test') + self.assertEqual(shell.written, [('test', 'stdout')]) + shell.reset() + f.write('t\xe8\u015b\U0001d599') + self.assertEqual(shell.written, [('t\xe8\u015b\U0001d599', 'stdout')]) + shell.reset() + + f.write(S('t\xe8\u015b\U0001d599')) + self.assertEqual(shell.written, [('t\xe8\u015b\U0001d599', 'stdout')]) + self.assertEqual(type(shell.written[0][0]), str) + shell.reset() + + self.assertRaises(TypeError, f.write) + self.assertEqual(shell.written, []) + self.assertRaises(TypeError, f.write, b'test') + self.assertRaises(TypeError, f.write, 123) + self.assertEqual(shell.written, []) + self.assertRaises(TypeError, f.write, 'test', 'spam') + self.assertEqual(shell.written, []) + + def test_write_stderr_nonencodable(self): + shell = MockShell() + f = run.StdOutputFile(shell, 'stderr', 'iso-8859-15', 'backslashreplace') + f.write('t\xe8\u015b\U0001d599\xa4') + self.assertEqual(shell.written, [('t\xe8\\u015b\\U0001d599\\xa4', 'stderr')]) + shell.reset() + + f.write(S('t\xe8\u015b\U0001d599\xa4')) + self.assertEqual(shell.written, [('t\xe8\\u015b\\U0001d599\\xa4', 'stderr')]) + self.assertEqual(type(shell.written[0][0]), str) + shell.reset() + + self.assertRaises(TypeError, f.write) + self.assertEqual(shell.written, []) + self.assertRaises(TypeError, f.write, b'test') + self.assertRaises(TypeError, f.write, 123) + self.assertEqual(shell.written, []) + self.assertRaises(TypeError, f.write, 'test', 'spam') + self.assertEqual(shell.written, []) + + def test_writelines(self): + shell = MockShell() + f = run.StdOutputFile(shell, 'stdout') + f.writelines([]) + self.assertEqual(shell.written, []) + shell.reset() + f.writelines(['one\n', 'two']) + self.assertEqual(shell.written, + [('one\n', 'stdout'), ('two', 'stdout')]) + shell.reset() + f.writelines(['on\xe8\n', 'tw\xf2']) + self.assertEqual(shell.written, + [('on\xe8\n', 'stdout'), ('tw\xf2', 'stdout')]) + shell.reset() + + f.writelines([S('t\xe8st')]) + self.assertEqual(shell.written, [('t\xe8st', 'stdout')]) + self.assertEqual(type(shell.written[0][0]), str) + shell.reset() + + self.assertRaises(TypeError, f.writelines) + self.assertEqual(shell.written, []) + self.assertRaises(TypeError, f.writelines, 123) + self.assertEqual(shell.written, []) + self.assertRaises(TypeError, f.writelines, [b'test']) + self.assertRaises(TypeError, f.writelines, [123]) + self.assertEqual(shell.written, []) + self.assertRaises(TypeError, f.writelines, [], []) + self.assertEqual(shell.written, []) + + def test_close(self): + shell = MockShell() + f = run.StdOutputFile(shell, 'stdout') + self.assertFalse(f.closed) + f.write('test') + f.close() + self.assertTrue(f.closed) + self.assertRaises(ValueError, f.write, 'x') + self.assertEqual(shell.written, [('test', 'stdout')]) + f.close() + self.assertRaises(TypeError, f.close, 1) + + +class RecursionLimitTest(unittest.TestCase): + # Test (un)install_recursionlimit_wrappers and fixdoc. + + def test_bad_setrecursionlimit_calls(self): + run.install_recursionlimit_wrappers() + self.addCleanup(run.uninstall_recursionlimit_wrappers) + f = sys.setrecursionlimit + self.assertRaises(TypeError, f, limit=100) + self.assertRaises(TypeError, f, 100, 1000) + self.assertRaises(ValueError, f, 0) + + def test_roundtrip(self): + run.install_recursionlimit_wrappers() + self.addCleanup(run.uninstall_recursionlimit_wrappers) + + # Check that setting the recursion limit works. + orig_reclimit = sys.getrecursionlimit() + self.addCleanup(sys.setrecursionlimit, orig_reclimit) + sys.setrecursionlimit(orig_reclimit + 3) + + # Check that the new limit is returned by sys.getrecursionlimit(). + new_reclimit = sys.getrecursionlimit() + self.assertEqual(new_reclimit, orig_reclimit + 3) + + def test_default_recursion_limit_preserved(self): + orig_reclimit = sys.getrecursionlimit() + run.install_recursionlimit_wrappers() + self.addCleanup(run.uninstall_recursionlimit_wrappers) + new_reclimit = sys.getrecursionlimit() + self.assertEqual(new_reclimit, orig_reclimit) + + def test_fixdoc(self): + # Put here until better place for miscellaneous test. + def func(): "docstring" + run.fixdoc(func, "more") + self.assertEqual(func.__doc__, "docstring\n\nmore") + func.__doc__ = None + run.fixdoc(func, "more") + self.assertEqual(func.__doc__, "more") + + +class HandleErrorTest(unittest.TestCase): + # Method of MyRPCServer + def test_fatal_error(self): + eq = self.assertEqual + with captured_output('__stderr__') as err,\ + mock.patch('idlelib.run.thread.interrupt_main', + new_callable=Func) as func: + try: + raise EOFError + except EOFError: + run.MyRPCServer.handle_error(None, 'abc', '123') + eq(run.exit_now, True) + run.exit_now = False + eq(err.getvalue(), '') + + try: + raise IndexError + except IndexError: + run.MyRPCServer.handle_error(None, 'abc', '123') + eq(run.quitting, True) + run.quitting = False + msg = err.getvalue() + self.assertIn('abc', msg) + self.assertIn('123', msg) + self.assertIn('IndexError', msg) + eq(func.called, 2) + + +class ExecRuncodeTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + cls.addClassCleanup(setattr,run,'print_exception',run.print_exception) + cls.prt = Func() # Need reference. + run.print_exception = cls.prt + mockrpc = mock.Mock() + mockrpc.console.getvar = Func(result=False) + cls.ex = run.Executive(mockrpc) + + @classmethod + def tearDownClass(cls): + assert sys.excepthook == sys.__excepthook__ + + def test_exceptions(self): + ex = self.ex + ex.runcode('1/0') + self.assertIs(ex.user_exc_info[0], ZeroDivisionError) + + self.addCleanup(setattr, sys, 'excepthook', sys.__excepthook__) + sys.excepthook = lambda t, e, tb: run.print_exception(t) + ex.runcode('1/0') + self.assertIs(self.prt.args[0], ZeroDivisionError) + + sys.excepthook = lambda: None + ex.runcode('1/0') + t, e, tb = ex.user_exc_info + self.assertIs(t, TypeError) + self.assertTrue(isinstance(e.__context__, ZeroDivisionError)) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_runscript.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_runscript.py new file mode 100644 index 0000000000000000000000000000000000000000..5fc60185a663e8f33d5fd10591df989190e038f8 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_runscript.py @@ -0,0 +1,33 @@ +"Test runscript, coverage 16%." + +from idlelib import runscript +import unittest +from test.support import requires +from tkinter import Tk +from idlelib.editor import EditorWindow + + +class ScriptBindingTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + + @classmethod + def tearDownClass(cls): + cls.root.update_idletasks() + for id in cls.root.tk.call('after', 'info'): + cls.root.after_cancel(id) # Need for EditorWindow. + cls.root.destroy() + del cls.root + + def test_init(self): + ew = EditorWindow(root=self.root) + sb = runscript.ScriptBinding(ew) + ew._close() + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_scrolledlist.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_scrolledlist.py new file mode 100644 index 0000000000000000000000000000000000000000..2f819fda025ba3d453e081327a05ffc2fd7cf972 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_scrolledlist.py @@ -0,0 +1,27 @@ +"Test scrolledlist, coverage 38%." + +from idlelib.scrolledlist import ScrolledList +import unittest +from test.support import requires +requires('gui') +from tkinter import Tk + + +class ScrolledListTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + cls.root = Tk() + + @classmethod + def tearDownClass(cls): + cls.root.destroy() + del cls.root + + + def test_init(self): + ScrolledList(self.root) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_search.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_search.py new file mode 100644 index 0000000000000000000000000000000000000000..de703c195cd22900b92f3b239018f805bbf373da --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_search.py @@ -0,0 +1,80 @@ +"Test search, coverage 69%." + +from idlelib import search +import unittest +from test.support import requires +requires('gui') +from tkinter import Tk, Text, BooleanVar +from idlelib import searchengine + +# Does not currently test the event handler wrappers. +# A usage test should simulate clicks and check highlighting. +# Tests need to be coordinated with SearchDialogBase tests +# to avoid duplication. + + +class SearchDialogTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + cls.root = Tk() + + @classmethod + def tearDownClass(cls): + cls.root.destroy() + del cls.root + + def setUp(self): + self.engine = searchengine.SearchEngine(self.root) + self.dialog = search.SearchDialog(self.root, self.engine) + self.dialog.bell = lambda: None + self.text = Text(self.root) + self.text.insert('1.0', 'Hello World!') + + def test_find_again(self): + # Search for various expressions + text = self.text + + self.engine.setpat('') + self.assertFalse(self.dialog.find_again(text)) + self.dialog.bell = lambda: None + + self.engine.setpat('Hello') + self.assertTrue(self.dialog.find_again(text)) + + self.engine.setpat('Goodbye') + self.assertFalse(self.dialog.find_again(text)) + + self.engine.setpat('World!') + self.assertTrue(self.dialog.find_again(text)) + + self.engine.setpat('Hello World!') + self.assertTrue(self.dialog.find_again(text)) + + # Regular expression + self.engine.revar = BooleanVar(self.root, True) + self.engine.setpat('W[aeiouy]r') + self.assertTrue(self.dialog.find_again(text)) + + def test_find_selection(self): + # Select some text and make sure it's found + text = self.text + # Add additional line to find + self.text.insert('2.0', 'Hello World!') + + text.tag_add('sel', '1.0', '1.4') # Select 'Hello' + self.assertTrue(self.dialog.find_selection(text)) + + text.tag_remove('sel', '1.0', 'end') + text.tag_add('sel', '1.6', '1.11') # Select 'World!' + self.assertTrue(self.dialog.find_selection(text)) + + text.tag_remove('sel', '1.0', 'end') + text.tag_add('sel', '1.0', '1.11') # Select 'Hello World!' + self.assertTrue(self.dialog.find_selection(text)) + + # Remove additional line + text.delete('2.0', 'end') + +if __name__ == '__main__': + unittest.main(verbosity=2, exit=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_searchbase.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_searchbase.py new file mode 100644 index 0000000000000000000000000000000000000000..8c9c410ebaf47c0626655cffe0fda4db83960819 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_searchbase.py @@ -0,0 +1,160 @@ +"Test searchbase, coverage 98%." +# The only thing not covered is inconsequential -- +# testing skipping of suite when self.needwrapbutton is false. + +import unittest +from test.support import requires +from tkinter import Text, Tk, Toplevel +from tkinter.ttk import Frame +from idlelib import searchengine as se +from idlelib import searchbase as sdb +from idlelib.idle_test.mock_idle import Func +## from idlelib.idle_test.mock_tk import Var + +# The ## imports above & following could help make some tests gui-free. +# However, they currently make radiobutton tests fail. +##def setUpModule(): +## # Replace tk objects used to initialize se.SearchEngine. +## se.BooleanVar = Var +## se.StringVar = Var +## +##def tearDownModule(): +## se.BooleanVar = BooleanVar +## se.StringVar = StringVar + + +class SearchDialogBaseTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + + @classmethod + def tearDownClass(cls): + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def setUp(self): + self.engine = se.SearchEngine(self.root) # None also seems to work + self.dialog = sdb.SearchDialogBase(root=self.root, engine=self.engine) + + def tearDown(self): + self.dialog.close() + + def test_open_and_close(self): + # open calls create_widgets, which needs default_command + self.dialog.default_command = None + + toplevel = Toplevel(self.root) + text = Text(toplevel) + self.dialog.open(text) + self.assertEqual(self.dialog.top.state(), 'normal') + self.dialog.close() + self.assertEqual(self.dialog.top.state(), 'withdrawn') + + self.dialog.open(text, searchphrase="hello") + self.assertEqual(self.dialog.ent.get(), 'hello') + toplevel.update_idletasks() + toplevel.destroy() + + def test_create_widgets(self): + self.dialog.create_entries = Func() + self.dialog.create_option_buttons = Func() + self.dialog.create_other_buttons = Func() + self.dialog.create_command_buttons = Func() + + self.dialog.default_command = None + self.dialog.create_widgets() + + self.assertTrue(self.dialog.create_entries.called) + self.assertTrue(self.dialog.create_option_buttons.called) + self.assertTrue(self.dialog.create_other_buttons.called) + self.assertTrue(self.dialog.create_command_buttons.called) + + def test_make_entry(self): + equal = self.assertEqual + self.dialog.row = 0 + self.dialog.frame = Frame(self.root) + entry, label = self.dialog.make_entry("Test:", 'hello') + equal(label['text'], 'Test:') + + self.assertIn(entry.get(), 'hello') + egi = entry.grid_info() + equal(int(egi['row']), 0) + equal(int(egi['column']), 1) + equal(int(egi['rowspan']), 1) + equal(int(egi['columnspan']), 1) + equal(self.dialog.row, 1) + + def test_create_entries(self): + self.dialog.frame = Frame(self.root) + self.dialog.row = 0 + self.engine.setpat('hello') + self.dialog.create_entries() + self.assertIn(self.dialog.ent.get(), 'hello') + + def test_make_frame(self): + self.dialog.row = 0 + self.dialog.frame = Frame(self.root) + frame, label = self.dialog.make_frame() + self.assertEqual(label, '') + self.assertEqual(str(type(frame)), "") + # self.assertIsInstance(frame, Frame) fails when test is run by + # test_idle not run from IDLE editor. See issue 33987 PR. + + frame, label = self.dialog.make_frame('testlabel') + self.assertEqual(label['text'], 'testlabel') + + def btn_test_setup(self, meth): + self.dialog.frame = Frame(self.root) + self.dialog.row = 0 + return meth() + + def test_create_option_buttons(self): + e = self.engine + for state in (0, 1): + for var in (e.revar, e.casevar, e.wordvar, e.wrapvar): + var.set(state) + frame, options = self.btn_test_setup( + self.dialog.create_option_buttons) + for spec, button in zip (options, frame.pack_slaves()): + var, label = spec + self.assertEqual(button['text'], label) + self.assertEqual(var.get(), state) + + def test_create_other_buttons(self): + for state in (False, True): + var = self.engine.backvar + var.set(state) + frame, others = self.btn_test_setup( + self.dialog.create_other_buttons) + buttons = frame.pack_slaves() + for spec, button in zip(others, buttons): + val, label = spec + self.assertEqual(button['text'], label) + if val == state: + # hit other button, then this one + # indexes depend on button order + self.assertEqual(var.get(), state) + + def test_make_button(self): + self.dialog.frame = Frame(self.root) + self.dialog.buttonframe = Frame(self.dialog.frame) + btn = self.dialog.make_button('Test', self.dialog.close) + self.assertEqual(btn['text'], 'Test') + + def test_create_command_buttons(self): + self.dialog.frame = Frame(self.root) + self.dialog.create_command_buttons() + # Look for close button command in buttonframe + closebuttoncommand = '' + for child in self.dialog.buttonframe.winfo_children(): + if child['text'] == 'Close': + closebuttoncommand = child['command'] + self.assertIn('close', closebuttoncommand) + + +if __name__ == '__main__': + unittest.main(verbosity=2, exit=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_searchengine.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_searchengine.py new file mode 100644 index 0000000000000000000000000000000000000000..9d97983941958606af154d8a4f8bb70bf9695d00 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_searchengine.py @@ -0,0 +1,332 @@ +"Test searchengine, coverage 99%." + +from idlelib import searchengine as se +import unittest +# from test.support import requires +from tkinter import BooleanVar, StringVar, TclError # ,Tk, Text +from tkinter import messagebox +from idlelib.idle_test.mock_tk import Var, Mbox +from idlelib.idle_test.mock_tk import Text as mockText +import re + +# With mock replacements, the module does not use any gui widgets. +# The use of tk.Text is avoided (for now, until mock Text is improved) +# by patching instances with an index function returning what is needed. +# This works because mock Text.get does not use .index. +# The tkinter imports are used to restore searchengine. + +def setUpModule(): + # Replace s-e module tkinter imports other than non-gui TclError. + se.BooleanVar = Var + se.StringVar = Var + se.messagebox = Mbox + +def tearDownModule(): + # Restore 'just in case', though other tests should also replace. + se.BooleanVar = BooleanVar + se.StringVar = StringVar + se.messagebox = messagebox + + +class Mock: + def __init__(self, *args, **kwargs): pass + +class GetTest(unittest.TestCase): + # SearchEngine.get returns singleton created & saved on first call. + def test_get(self): + saved_Engine = se.SearchEngine + se.SearchEngine = Mock # monkey-patch class + try: + root = Mock() + engine = se.get(root) + self.assertIsInstance(engine, se.SearchEngine) + self.assertIs(root._searchengine, engine) + self.assertIs(se.get(root), engine) + finally: + se.SearchEngine = saved_Engine # restore class to module + +class GetLineColTest(unittest.TestCase): + # Test simple text-independent helper function + def test_get_line_col(self): + self.assertEqual(se.get_line_col('1.0'), (1, 0)) + self.assertEqual(se.get_line_col('1.11'), (1, 11)) + + self.assertRaises(ValueError, se.get_line_col, ('1.0 lineend')) + self.assertRaises(ValueError, se.get_line_col, ('end')) + +class GetSelectionTest(unittest.TestCase): + # Test text-dependent helper function. +## # Need gui for text.index('sel.first/sel.last/insert'). +## @classmethod +## def setUpClass(cls): +## requires('gui') +## cls.root = Tk() +## +## @classmethod +## def tearDownClass(cls): +## cls.root.destroy() +## del cls.root + + def test_get_selection(self): + # text = Text(master=self.root) + text = mockText() + text.insert('1.0', 'Hello World!') + + # fix text.index result when called in get_selection + def sel(s): + # select entire text, cursor irrelevant + if s == 'sel.first': return '1.0' + if s == 'sel.last': return '1.12' + raise TclError + text.index = sel # replaces .tag_add('sel', '1.0, '1.12') + self.assertEqual(se.get_selection(text), ('1.0', '1.12')) + + def mark(s): + # no selection, cursor after 'Hello' + if s == 'insert': return '1.5' + raise TclError + text.index = mark # replaces .mark_set('insert', '1.5') + self.assertEqual(se.get_selection(text), ('1.5', '1.5')) + + +class ReverseSearchTest(unittest.TestCase): + # Test helper function that searches backwards within a line. + def test_search_reverse(self): + Equal = self.assertEqual + line = "Here is an 'is' test text." + prog = re.compile('is') + Equal(se.search_reverse(prog, line, len(line)).span(), (12, 14)) + Equal(se.search_reverse(prog, line, 14).span(), (12, 14)) + Equal(se.search_reverse(prog, line, 13).span(), (5, 7)) + Equal(se.search_reverse(prog, line, 7).span(), (5, 7)) + Equal(se.search_reverse(prog, line, 6), None) + + +class SearchEngineTest(unittest.TestCase): + # Test class methods that do not use Text widget. + + def setUp(self): + self.engine = se.SearchEngine(root=None) + # Engine.root is only used to create error message boxes. + # The mock replacement ignores the root argument. + + def test_is_get(self): + engine = self.engine + Equal = self.assertEqual + + Equal(engine.getpat(), '') + engine.setpat('hello') + Equal(engine.getpat(), 'hello') + + Equal(engine.isre(), False) + engine.revar.set(1) + Equal(engine.isre(), True) + + Equal(engine.iscase(), False) + engine.casevar.set(1) + Equal(engine.iscase(), True) + + Equal(engine.isword(), False) + engine.wordvar.set(1) + Equal(engine.isword(), True) + + Equal(engine.iswrap(), True) + engine.wrapvar.set(0) + Equal(engine.iswrap(), False) + + Equal(engine.isback(), False) + engine.backvar.set(1) + Equal(engine.isback(), True) + + def test_setcookedpat(self): + engine = self.engine + engine.setcookedpat(r'\s') + self.assertEqual(engine.getpat(), r'\s') + engine.revar.set(1) + engine.setcookedpat(r'\s') + self.assertEqual(engine.getpat(), r'\\s') + + def test_getcookedpat(self): + engine = self.engine + Equal = self.assertEqual + + Equal(engine.getcookedpat(), '') + engine.setpat('hello') + Equal(engine.getcookedpat(), 'hello') + engine.wordvar.set(True) + Equal(engine.getcookedpat(), r'\bhello\b') + engine.wordvar.set(False) + + engine.setpat(r'\s') + Equal(engine.getcookedpat(), r'\\s') + engine.revar.set(True) + Equal(engine.getcookedpat(), r'\s') + + def test_getprog(self): + engine = self.engine + Equal = self.assertEqual + + engine.setpat('Hello') + temppat = engine.getprog() + Equal(temppat.pattern, re.compile('Hello', re.IGNORECASE).pattern) + engine.casevar.set(1) + temppat = engine.getprog() + Equal(temppat.pattern, re.compile('Hello').pattern, 0) + + engine.setpat('') + Equal(engine.getprog(), None) + Equal(Mbox.showerror.message, + 'Error: Empty regular expression') + engine.setpat('+') + engine.revar.set(1) + Equal(engine.getprog(), None) + Equal(Mbox.showerror.message, + 'Error: nothing to repeat\nPattern: +\nOffset: 0') + + def test_report_error(self): + showerror = Mbox.showerror + Equal = self.assertEqual + pat = '[a-z' + msg = 'unexpected end of regular expression' + + Equal(self.engine.report_error(pat, msg), None) + Equal(showerror.title, 'Regular expression error') + expected_message = ("Error: " + msg + "\nPattern: [a-z") + Equal(showerror.message, expected_message) + + Equal(self.engine.report_error(pat, msg, 5), None) + Equal(showerror.title, 'Regular expression error') + expected_message += "\nOffset: 5" + Equal(showerror.message, expected_message) + + +class SearchTest(unittest.TestCase): + # Test that search_text makes right call to right method. + + @classmethod + def setUpClass(cls): +## requires('gui') +## cls.root = Tk() +## cls.text = Text(master=cls.root) + cls.text = mockText() + test_text = ( + 'First line\n' + 'Line with target\n' + 'Last line\n') + cls.text.insert('1.0', test_text) + cls.pat = re.compile('target') + + cls.engine = se.SearchEngine(None) + cls.engine.search_forward = lambda *args: ('f', args) + cls.engine.search_backward = lambda *args: ('b', args) + +## @classmethod +## def tearDownClass(cls): +## cls.root.destroy() +## del cls.root + + def test_search(self): + Equal = self.assertEqual + engine = self.engine + search = engine.search_text + text = self.text + pat = self.pat + + engine.patvar.set(None) + #engine.revar.set(pat) + Equal(search(text), None) + + def mark(s): + # no selection, cursor after 'Hello' + if s == 'insert': return '1.5' + raise TclError + text.index = mark + Equal(search(text, pat), ('f', (text, pat, 1, 5, True, False))) + engine.wrapvar.set(False) + Equal(search(text, pat), ('f', (text, pat, 1, 5, False, False))) + engine.wrapvar.set(True) + engine.backvar.set(True) + Equal(search(text, pat), ('b', (text, pat, 1, 5, True, False))) + engine.backvar.set(False) + + def sel(s): + if s == 'sel.first': return '2.10' + if s == 'sel.last': return '2.16' + raise TclError + text.index = sel + Equal(search(text, pat), ('f', (text, pat, 2, 16, True, False))) + Equal(search(text, pat, True), ('f', (text, pat, 2, 10, True, True))) + engine.backvar.set(True) + Equal(search(text, pat), ('b', (text, pat, 2, 10, True, False))) + Equal(search(text, pat, True), ('b', (text, pat, 2, 16, True, True))) + + +class ForwardBackwardTest(unittest.TestCase): + # Test that search_forward method finds the target. +## @classmethod +## def tearDownClass(cls): +## cls.root.destroy() +## del cls.root + + @classmethod + def setUpClass(cls): + cls.engine = se.SearchEngine(None) +## requires('gui') +## cls.root = Tk() +## cls.text = Text(master=cls.root) + cls.text = mockText() + # search_backward calls index('end-1c') + cls.text.index = lambda index: '4.0' + test_text = ( + 'First line\n' + 'Line with target\n' + 'Last line\n') + cls.text.insert('1.0', test_text) + cls.pat = re.compile('target') + cls.res = (2, (10, 16)) # line, slice indexes of 'target' + cls.failpat = re.compile('xyz') # not in text + cls.emptypat = re.compile(r'\w*') # empty match possible + + def make_search(self, func): + def search(pat, line, col, wrap, ok=0): + res = func(self.text, pat, line, col, wrap, ok) + # res is (line, matchobject) or None + return (res[0], res[1].span()) if res else res + return search + + def test_search_forward(self): + # search for non-empty match + Equal = self.assertEqual + forward = self.make_search(self.engine.search_forward) + pat = self.pat + Equal(forward(pat, 1, 0, True), self.res) + Equal(forward(pat, 3, 0, True), self.res) # wrap + Equal(forward(pat, 3, 0, False), None) # no wrap + Equal(forward(pat, 2, 10, False), self.res) + + Equal(forward(self.failpat, 1, 0, True), None) + Equal(forward(self.emptypat, 2, 9, True, ok=True), (2, (9, 9))) + #Equal(forward(self.emptypat, 2, 9, True), self.res) + # While the initial empty match is correctly ignored, skipping + # the rest of the line and returning (3, (0,4)) seems buggy - tjr. + Equal(forward(self.emptypat, 2, 10, True), self.res) + + def test_search_backward(self): + # search for non-empty match + Equal = self.assertEqual + backward = self.make_search(self.engine.search_backward) + pat = self.pat + Equal(backward(pat, 3, 5, True), self.res) + Equal(backward(pat, 2, 0, True), self.res) # wrap + Equal(backward(pat, 2, 0, False), None) # no wrap + Equal(backward(pat, 2, 16, False), self.res) + + Equal(backward(self.failpat, 3, 9, True), None) + Equal(backward(self.emptypat, 2, 10, True, ok=True), (2, (9,9))) + # Accepted because 9 < 10, not because ok=True. + # It is not clear that ok=True is useful going back - tjr + Equal(backward(self.emptypat, 2, 9, True), (2, (5, 9))) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_sidebar.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_sidebar.py new file mode 100644 index 0000000000000000000000000000000000000000..3e854561a0f5b97055212876cafe979c8f5364b3 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_sidebar.py @@ -0,0 +1,775 @@ +"""Test sidebar, coverage 85%""" +from textwrap import dedent +import sys + +from itertools import chain +import unittest +import unittest.mock +from test.support import adjust_int_max_str_digits, requires, swap_attr +from test.support.testcase import ExtraAssertions +import tkinter as tk +from idlelib.idle_test.tkinter_testing_utils import run_in_tk_mainloop + +from idlelib.delegator import Delegator +from idlelib.editor import fixwordbreaks +from idlelib.percolator import Percolator +import idlelib.pyshell +from idlelib.pyshell import fix_x11_paste, PyShell, PyShellFileList +from idlelib.run import fix_scaling +import idlelib.sidebar +from idlelib.sidebar import get_end_linenumber, get_lineno + + +class Dummy_editwin: + def __init__(self, text): + self.text = text + self.text_frame = self.text.master + self.per = Percolator(text) + self.undo = Delegator() + self.per.insertfilter(self.undo) + + def setvar(self, name, value): + pass + + def getlineno(self, index): + return int(float(self.text.index(index))) + + +class LineNumbersTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = tk.Tk() + cls.root.withdraw() + + cls.text_frame = tk.Frame(cls.root) + cls.text_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True) + cls.text_frame.rowconfigure(1, weight=1) + cls.text_frame.columnconfigure(1, weight=1) + + cls.text = tk.Text(cls.text_frame, width=80, height=24, wrap=tk.NONE) + cls.text.grid(row=1, column=1, sticky=tk.NSEW) + + cls.editwin = Dummy_editwin(cls.text) + cls.editwin.vbar = tk.Scrollbar(cls.text_frame) + + @classmethod + def tearDownClass(cls): + cls.editwin.per.close() + cls.root.update_idletasks() + cls.root.destroy() + del cls.text, cls.text_frame, cls.editwin, cls.root + + def setUp(self): + self.linenumber = idlelib.sidebar.LineNumbers(self.editwin) + + self.highlight_cfg = {"background": '#abcdef', + "foreground": '#123456'} + orig_idleConf_GetHighlight = idlelib.sidebar.idleConf.GetHighlight + def mock_idleconf_GetHighlight(theme, element): + if element == 'linenumber': + return self.highlight_cfg + return orig_idleConf_GetHighlight(theme, element) + GetHighlight_patcher = unittest.mock.patch.object( + idlelib.sidebar.idleConf, 'GetHighlight', mock_idleconf_GetHighlight) + GetHighlight_patcher.start() + self.addCleanup(GetHighlight_patcher.stop) + + self.font_override = 'TkFixedFont' + def mock_idleconf_GetFont(root, configType, section): + return self.font_override + GetFont_patcher = unittest.mock.patch.object( + idlelib.sidebar.idleConf, 'GetFont', mock_idleconf_GetFont) + GetFont_patcher.start() + self.addCleanup(GetFont_patcher.stop) + + def tearDown(self): + self.text.delete('1.0', 'end') + + def get_selection(self): + return tuple(map(str, self.text.tag_ranges('sel'))) + + def get_line_screen_position(self, line): + bbox = self.linenumber.sidebar_text.bbox(f'{line}.end -1c') + x = bbox[0] + 2 + y = bbox[1] + 2 + return x, y + + def assert_state_disabled(self): + state = self.linenumber.sidebar_text.config()['state'] + self.assertEqual(state[-1], tk.DISABLED) + + def get_sidebar_text_contents(self): + return self.linenumber.sidebar_text.get('1.0', tk.END) + + def assert_sidebar_n_lines(self, n_lines): + expected = '\n'.join(chain(map(str, range(1, n_lines + 1)), [''])) + self.assertEqual(self.get_sidebar_text_contents(), expected) + + def assert_text_equals(self, expected): + return self.assertEqual(self.text.get('1.0', 'end'), expected) + + def test_init_empty(self): + self.assert_sidebar_n_lines(1) + + def test_init_not_empty(self): + self.text.insert('insert', 'foo bar\n'*3) + self.assert_text_equals('foo bar\n'*3 + '\n') + self.assert_sidebar_n_lines(4) + + def test_toggle_linenumbering(self): + self.assertEqual(self.linenumber.is_shown, False) + self.linenumber.show_sidebar() + self.assertEqual(self.linenumber.is_shown, True) + self.linenumber.hide_sidebar() + self.assertEqual(self.linenumber.is_shown, False) + self.linenumber.hide_sidebar() + self.assertEqual(self.linenumber.is_shown, False) + self.linenumber.show_sidebar() + self.assertEqual(self.linenumber.is_shown, True) + self.linenumber.show_sidebar() + self.assertEqual(self.linenumber.is_shown, True) + + def test_insert(self): + self.text.insert('insert', 'foobar') + self.assert_text_equals('foobar\n') + self.assert_sidebar_n_lines(1) + self.assert_state_disabled() + + self.text.insert('insert', '\nfoo') + self.assert_text_equals('foobar\nfoo\n') + self.assert_sidebar_n_lines(2) + self.assert_state_disabled() + + self.text.insert('insert', 'hello\n'*2) + self.assert_text_equals('foobar\nfoohello\nhello\n\n') + self.assert_sidebar_n_lines(4) + self.assert_state_disabled() + + self.text.insert('insert', '\nworld') + self.assert_text_equals('foobar\nfoohello\nhello\n\nworld\n') + self.assert_sidebar_n_lines(5) + self.assert_state_disabled() + + def test_delete(self): + self.text.insert('insert', 'foobar') + self.assert_text_equals('foobar\n') + self.text.delete('1.1', '1.3') + self.assert_text_equals('fbar\n') + self.assert_sidebar_n_lines(1) + self.assert_state_disabled() + + self.text.insert('insert', 'foo\n'*2) + self.assert_text_equals('fbarfoo\nfoo\n\n') + self.assert_sidebar_n_lines(3) + self.assert_state_disabled() + + # Deleting up to "2.end" doesn't delete the final newline. + self.text.delete('2.0', '2.end') + self.assert_text_equals('fbarfoo\n\n\n') + self.assert_sidebar_n_lines(3) + self.assert_state_disabled() + + self.text.delete('1.3', 'end') + self.assert_text_equals('fba\n') + self.assert_sidebar_n_lines(1) + self.assert_state_disabled() + + # Text widgets always keep a single '\n' character at the end. + self.text.delete('1.0', 'end') + self.assert_text_equals('\n') + self.assert_sidebar_n_lines(1) + self.assert_state_disabled() + + def test_sidebar_text_width(self): + """ + Test that linenumber text widget is always at the minimum + width + """ + def get_width(): + return self.linenumber.sidebar_text.config()['width'][-1] + + self.assert_sidebar_n_lines(1) + self.assertEqual(get_width(), 1) + + self.text.insert('insert', 'foo') + self.assert_sidebar_n_lines(1) + self.assertEqual(get_width(), 1) + + self.text.insert('insert', 'foo\n'*8) + self.assert_sidebar_n_lines(9) + self.assertEqual(get_width(), 1) + + self.text.insert('insert', 'foo\n') + self.assert_sidebar_n_lines(10) + self.assertEqual(get_width(), 2) + + self.text.insert('insert', 'foo\n') + self.assert_sidebar_n_lines(11) + self.assertEqual(get_width(), 2) + + self.text.delete('insert -1l linestart', 'insert linestart') + self.assert_sidebar_n_lines(10) + self.assertEqual(get_width(), 2) + + self.text.delete('insert -1l linestart', 'insert linestart') + self.assert_sidebar_n_lines(9) + self.assertEqual(get_width(), 1) + + self.text.insert('insert', 'foo\n'*90) + self.assert_sidebar_n_lines(99) + self.assertEqual(get_width(), 2) + + self.text.insert('insert', 'foo\n') + self.assert_sidebar_n_lines(100) + self.assertEqual(get_width(), 3) + + self.text.insert('insert', 'foo\n') + self.assert_sidebar_n_lines(101) + self.assertEqual(get_width(), 3) + + self.text.delete('insert -1l linestart', 'insert linestart') + self.assert_sidebar_n_lines(100) + self.assertEqual(get_width(), 3) + + self.text.delete('insert -1l linestart', 'insert linestart') + self.assert_sidebar_n_lines(99) + self.assertEqual(get_width(), 2) + + self.text.delete('50.0 -1c', 'end -1c') + self.assert_sidebar_n_lines(49) + self.assertEqual(get_width(), 2) + + self.text.delete('5.0 -1c', 'end -1c') + self.assert_sidebar_n_lines(4) + self.assertEqual(get_width(), 1) + + # Text widgets always keep a single '\n' character at the end. + self.text.delete('1.0', 'end -1c') + self.assert_sidebar_n_lines(1) + self.assertEqual(get_width(), 1) + + # The following tests are temporarily disabled due to relying on + # simulated user input and inspecting which text is selected, which + # are fragile and can fail when several GUI tests are run in parallel + # or when the windows created by the test lose focus. + # + # TODO: Re-work these tests or remove them from the test suite. + + @unittest.skip('test disabled') + def test_click_selection(self): + self.linenumber.show_sidebar() + self.text.insert('1.0', 'one\ntwo\nthree\nfour\n') + self.root.update() + + # Click on the second line. + x, y = self.get_line_screen_position(2) + self.linenumber.sidebar_text.event_generate('', x=x, y=y) + self.linenumber.sidebar_text.update() + self.root.update() + + self.assertEqual(self.get_selection(), ('2.0', '3.0')) + + def simulate_drag(self, start_line, end_line): + start_x, start_y = self.get_line_screen_position(start_line) + end_x, end_y = self.get_line_screen_position(end_line) + + self.linenumber.sidebar_text.event_generate('', + x=start_x, y=start_y) + self.root.update() + + def lerp(a, b, steps): + """linearly interpolate from a to b (inclusive) in equal steps""" + last_step = steps - 1 + for i in range(steps): + yield ((last_step - i) / last_step) * a + (i / last_step) * b + + for x, y in zip( + map(int, lerp(start_x, end_x, steps=11)), + map(int, lerp(start_y, end_y, steps=11)), + ): + self.linenumber.sidebar_text.event_generate('', x=x, y=y) + self.root.update() + + self.linenumber.sidebar_text.event_generate('', + x=end_x, y=end_y) + self.root.update() + + @unittest.skip('test disabled') + def test_drag_selection_down(self): + self.linenumber.show_sidebar() + self.text.insert('1.0', 'one\ntwo\nthree\nfour\nfive\n') + self.root.update() + + # Drag from the second line to the fourth line. + self.simulate_drag(2, 4) + self.assertEqual(self.get_selection(), ('2.0', '5.0')) + + @unittest.skip('test disabled') + def test_drag_selection_up(self): + self.linenumber.show_sidebar() + self.text.insert('1.0', 'one\ntwo\nthree\nfour\nfive\n') + self.root.update() + + # Drag from the fourth line to the second line. + self.simulate_drag(4, 2) + self.assertEqual(self.get_selection(), ('2.0', '5.0')) + + def test_scroll(self): + self.linenumber.show_sidebar() + self.text.insert('1.0', 'line\n' * 100) + self.root.update() + + # Scroll down 10 lines. + self.text.yview_scroll(10, 'unit') + self.root.update() + self.assertEqual(self.text.index('@0,0'), '11.0') + self.assertEqual(self.linenumber.sidebar_text.index('@0,0'), '11.0') + + # Generate a mouse-wheel event and make sure it scrolled up or down. + # The meaning of the "delta" is OS-dependent, so this just checks for + # any change. + self.linenumber.sidebar_text.event_generate('', + x=0, y=0, + delta=10) + self.root.update() + self.assertNotEqual(self.text.index('@0,0'), '11.0') + self.assertNotEqual(self.linenumber.sidebar_text.index('@0,0'), '11.0') + + def test_font(self): + ln = self.linenumber + + orig_font = ln.sidebar_text['font'] + test_font = 'TkTextFont' + self.assertNotEqual(orig_font, test_font) + + # Ensure line numbers aren't shown. + ln.hide_sidebar() + + self.font_override = test_font + # Nothing breaks when line numbers aren't shown. + ln.update_font() + + # Activate line numbers, previous font change is immediately effective. + ln.show_sidebar() + self.assertEqual(ln.sidebar_text['font'], test_font) + + # Call the font update with line numbers shown, change is picked up. + self.font_override = orig_font + ln.update_font() + self.assertEqual(ln.sidebar_text['font'], orig_font) + + def test_highlight_colors(self): + ln = self.linenumber + + orig_colors = dict(self.highlight_cfg) + test_colors = {'background': '#222222', 'foreground': '#ffff00'} + + def assert_colors_are_equal(colors): + self.assertEqual(ln.sidebar_text['background'], colors['background']) + self.assertEqual(ln.sidebar_text['foreground'], colors['foreground']) + + # Ensure line numbers aren't shown. + ln.hide_sidebar() + + self.highlight_cfg = test_colors + # Nothing breaks with inactive line numbers. + ln.update_colors() + + # Show line numbers, previous colors change is immediately effective. + ln.show_sidebar() + assert_colors_are_equal(test_colors) + + # Call colors update with no change to the configured colors. + ln.update_colors() + assert_colors_are_equal(test_colors) + + # Call the colors update with line numbers shown, change is picked up. + self.highlight_cfg = orig_colors + ln.update_colors() + assert_colors_are_equal(orig_colors) + + +class ShellSidebarTest(unittest.TestCase, ExtraAssertions): + root: tk.Tk = None + shell: PyShell = None + + @classmethod + def setUpClass(cls): + requires('gui') + + cls.root = root = tk.Tk() + root.withdraw() + + fix_scaling(root) + fixwordbreaks(root) + fix_x11_paste(root) + + cls.flist = flist = PyShellFileList(root) + # See #43981 about macosx.setupApp(root, flist) causing failure. + root.update_idletasks() + + cls.init_shell() + + @classmethod + def tearDownClass(cls): + if cls.shell is not None: + cls.shell.executing = False + cls.shell.close() + cls.shell = None + cls.flist = None + cls.root.update_idletasks() + cls.root.destroy() + cls.root = None + + @classmethod + def init_shell(cls): + cls.shell = cls.flist.open_shell() + cls.shell.pollinterval = 10 + cls.root.update() + cls.n_preface_lines = get_lineno(cls.shell.text, 'end-1c') - 1 + + @classmethod + def reset_shell(cls): + cls.shell.per.bottom.delete(f'{cls.n_preface_lines+1}.0', 'end-1c') + cls.shell.shell_sidebar.update_sidebar() + cls.root.update() + + def setUp(self): + # In some test environments, e.g. Azure Pipelines (as of + # Apr. 2021), sys.stdout is changed between tests. However, + # PyShell relies on overriding sys.stdout when run without a + # sub-process (as done here; see setUpClass). + self._saved_stdout = None + if sys.stdout != self.shell.stdout: + self._saved_stdout = sys.stdout + sys.stdout = self.shell.stdout + + self.reset_shell() + + def tearDown(self): + if self._saved_stdout is not None: + sys.stdout = self._saved_stdout + + def get_sidebar_lines(self): + canvas = self.shell.shell_sidebar.canvas + texts = list(canvas.find(tk.ALL)) + texts_by_y_coords = { + canvas.bbox(text)[1]: canvas.itemcget(text, 'text') + for text in texts + } + line_y_coords = self.get_shell_line_y_coords() + return [texts_by_y_coords.get(y, None) for y in line_y_coords] + + def assert_sidebar_lines_end_with(self, expected_lines): + self.shell.shell_sidebar.update_sidebar() + self.assertEqual( + self.get_sidebar_lines()[-len(expected_lines):], + expected_lines, + ) + + def get_shell_line_y_coords(self): + text = self.shell.text + y_coords = [] + index = text.index("@0,0") + if index.split('.', 1)[1] != '0': + index = text.index(f"{index} +1line linestart") + while (lineinfo := text.dlineinfo(index)) is not None: + y_coords.append(lineinfo[1]) + index = text.index(f"{index} +1line") + return y_coords + + def get_sidebar_line_y_coords(self): + canvas = self.shell.shell_sidebar.canvas + texts = list(canvas.find(tk.ALL)) + texts.sort(key=lambda text: canvas.bbox(text)[1]) + return [canvas.bbox(text)[1] for text in texts] + + def assert_sidebar_lines_synced(self): + self.assertLessEqual( + set(self.get_sidebar_line_y_coords()), + set(self.get_shell_line_y_coords()), + ) + + def do_input(self, input): + shell = self.shell + text = shell.text + for line_index, line in enumerate(input.split('\n')): + if line_index > 0: + text.event_generate('<>') + text.insert('insert', line, 'stdin') + + def test_initial_state(self): + sidebar_lines = self.get_sidebar_lines() + self.assertEqual( + sidebar_lines, + [None] * (len(sidebar_lines) - 1) + ['>>>'], + ) + self.assert_sidebar_lines_synced() + + @run_in_tk_mainloop() + def test_single_empty_input(self): + self.do_input('\n') + yield + self.assert_sidebar_lines_end_with(['>>>', '>>>']) + + @run_in_tk_mainloop() + def test_single_line_statement(self): + self.do_input('1\n') + yield + self.assert_sidebar_lines_end_with(['>>>', None, '>>>']) + + @run_in_tk_mainloop() + def test_multi_line_statement(self): + # Block statements are not indented because IDLE auto-indents. + self.do_input(dedent('''\ + if True: + print(1) + + ''')) + yield + self.assert_sidebar_lines_end_with([ + '>>>', + '...', + '...', + '...', + None, + '>>>', + ]) + + @run_in_tk_mainloop() + def test_single_long_line_wraps(self): + self.do_input('1' * 200 + '\n') + yield + self.assert_sidebar_lines_end_with(['>>>', None, '>>>']) + self.assert_sidebar_lines_synced() + + @run_in_tk_mainloop() + def test_squeeze_multi_line_output(self): + shell = self.shell + text = shell.text + + self.do_input('print("a\\nb\\nc")\n') + yield + self.assert_sidebar_lines_end_with(['>>>', None, None, None, '>>>']) + + text.mark_set('insert', f'insert -1line linestart') + text.event_generate('<>') + yield + self.assert_sidebar_lines_end_with(['>>>', None, '>>>']) + self.assert_sidebar_lines_synced() + + shell.squeezer.expandingbuttons[0].expand() + yield + self.assert_sidebar_lines_end_with(['>>>', None, None, None, '>>>']) + self.assert_sidebar_lines_synced() + + @run_in_tk_mainloop() + def test_interrupt_recall_undo_redo(self): + text = self.shell.text + # Block statements are not indented because IDLE auto-indents. + initial_sidebar_lines = self.get_sidebar_lines() + + self.do_input(dedent('''\ + if True: + print(1) + ''')) + yield + self.assert_sidebar_lines_end_with(['>>>', '...', '...']) + with_block_sidebar_lines = self.get_sidebar_lines() + self.assertNotEqual(with_block_sidebar_lines, initial_sidebar_lines) + + # Control-C + text.event_generate('<>') + yield + self.assert_sidebar_lines_end_with(['>>>', '...', '...', None, '>>>']) + + # Recall previous via history + text.event_generate('<>') + text.event_generate('<>') + yield + self.assert_sidebar_lines_end_with(['>>>', '...', None, '>>>']) + + # Recall previous via recall + text.mark_set('insert', text.index('insert -2l')) + text.event_generate('<>') + yield + + text.event_generate('<>') + yield + self.assert_sidebar_lines_end_with(['>>>']) + + text.event_generate('<>') + yield + self.assert_sidebar_lines_end_with(['>>>', '...']) + + text.event_generate('<>') + text.event_generate('<>') + yield + self.assert_sidebar_lines_end_with( + ['>>>', '...', '...', '...', None, '>>>'] + ) + + @run_in_tk_mainloop() + def test_very_long_wrapped_line(self): + with adjust_int_max_str_digits(11_111), \ + swap_attr(self.shell, 'squeezer', None): + self.do_input('x = ' + '1'*10_000 + '\n') + yield + self.assertEqual(self.get_sidebar_lines(), ['>>>']) + + def test_font(self): + sidebar = self.shell.shell_sidebar + + test_font = 'TkTextFont' + + def mock_idleconf_GetFont(root, configType, section): + return test_font + GetFont_patcher = unittest.mock.patch.object( + idlelib.sidebar.idleConf, 'GetFont', mock_idleconf_GetFont) + GetFont_patcher.start() + def cleanup(): + GetFont_patcher.stop() + sidebar.update_font() + self.addCleanup(cleanup) + + def get_sidebar_font(): + canvas = sidebar.canvas + texts = list(canvas.find(tk.ALL)) + fonts = {canvas.itemcget(text, 'font') for text in texts} + self.assertEqual(len(fonts), 1) + return next(iter(fonts)) + + self.assertNotEqual(get_sidebar_font(), test_font) + sidebar.update_font() + self.assertEqual(get_sidebar_font(), test_font) + + def test_highlight_colors(self): + sidebar = self.shell.shell_sidebar + + test_colors = {"background": '#abcdef', "foreground": '#123456'} + + orig_idleConf_GetHighlight = idlelib.sidebar.idleConf.GetHighlight + def mock_idleconf_GetHighlight(theme, element): + if element in ['linenumber', 'console']: + return test_colors + return orig_idleConf_GetHighlight(theme, element) + GetHighlight_patcher = unittest.mock.patch.object( + idlelib.sidebar.idleConf, 'GetHighlight', + mock_idleconf_GetHighlight) + GetHighlight_patcher.start() + def cleanup(): + GetHighlight_patcher.stop() + sidebar.update_colors() + self.addCleanup(cleanup) + + def get_sidebar_colors(): + canvas = sidebar.canvas + texts = list(canvas.find(tk.ALL)) + fgs = {canvas.itemcget(text, 'fill') for text in texts} + self.assertEqual(len(fgs), 1) + fg = next(iter(fgs)) + bg = canvas.cget('background') + return {"background": bg, "foreground": fg} + + self.assertNotEqual(get_sidebar_colors(), test_colors) + sidebar.update_colors() + self.assertEqual(get_sidebar_colors(), test_colors) + + @run_in_tk_mainloop() + def test_mousewheel(self): + sidebar = self.shell.shell_sidebar + text = self.shell.text + + # Enter a 100-line string to scroll the shell screen down. + self.do_input('x = """' + '\n'*100 + '"""\n') + yield + self.assertGreater(get_lineno(text, '@0,0'), 1) + + last_lineno = get_end_linenumber(text) + self.assertIsNotNone(text.dlineinfo(text.index(f'{last_lineno}.0'))) + + # Delta for , whose meaning is platform-dependent. + delta = 1 if sidebar.canvas._windowingsystem == 'aqua' else 120 + + # Scroll up. + if sidebar.canvas._windowingsystem == 'x11': + sidebar.canvas.event_generate('', x=0, y=0) + else: + sidebar.canvas.event_generate('', x=0, y=0, delta=delta) + yield + self.assertIsNone(text.dlineinfo(text.index(f'{last_lineno}.0'))) + + # Scroll back down. + if sidebar.canvas._windowingsystem == 'x11': + sidebar.canvas.event_generate('', x=0, y=0) + else: + sidebar.canvas.event_generate('', x=0, y=0, delta=-delta) + yield + self.assertIsNotNone(text.dlineinfo(text.index(f'{last_lineno}.0'))) + + @run_in_tk_mainloop() + def test_copy(self): + sidebar = self.shell.shell_sidebar + text = self.shell.text + + first_line = get_end_linenumber(text) + + self.do_input(dedent('''\ + if True: + print(1) + + ''')) + yield + + text.tag_add('sel', f'{first_line}.0', 'end-1c') + selected_text = text.get('sel.first', 'sel.last') + self.assertStartsWith(selected_text, 'if True:\n') + self.assertIn('\n1\n', selected_text) + + text.event_generate('<>') + self.addCleanup(text.clipboard_clear) + + copied_text = text.clipboard_get() + self.assertEqual(copied_text, selected_text) + + @run_in_tk_mainloop() + def test_copy_with_prompts(self): + sidebar = self.shell.shell_sidebar + text = self.shell.text + + first_line = get_end_linenumber(text) + self.do_input(dedent('''\ + if True: + print(1) + + ''')) + yield + + text.tag_add('sel', f'{first_line}.3', 'end-1c') + selected_text = text.get('sel.first', 'sel.last') + self.assertStartsWith(selected_text, 'True:\n') + + selected_lines_text = text.get('sel.first linestart', 'sel.last') + selected_lines = selected_lines_text.split('\n') + selected_lines.pop() # Final '' is a split artifact, not a line. + # Expect a block of input and a single output line. + expected_prompts = \ + ['>>>'] + ['...'] * (len(selected_lines) - 2) + [None] + selected_text_with_prompts = '\n'.join( + line if prompt is None else prompt + ' ' + line + for prompt, line in zip(expected_prompts, + selected_lines, + strict=True) + ) + '\n' + + text.event_generate('<>') + self.addCleanup(text.clipboard_clear) + + copied_text = text.clipboard_get() + self.assertEqual(copied_text, selected_text_with_prompts) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_squeezer.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_squeezer.py new file mode 100644 index 0000000000000000000000000000000000000000..86c5d41b6297192ff56f7ec07fcb28e136b9a3a8 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_squeezer.py @@ -0,0 +1,466 @@ +"Test squeezer, coverage 95%" + +from textwrap import dedent +from tkinter import Text, Tk +import unittest +from unittest.mock import Mock, NonCallableMagicMock, patch, sentinel, ANY +from test.support import requires + +from idlelib.config import idleConf +from idlelib.percolator import Percolator +from idlelib.squeezer import count_lines_with_wrapping, ExpandingButton, \ + Squeezer +from idlelib import macosx +from idlelib.textview import view_text +from idlelib.tooltip import Hovertip + +SENTINEL_VALUE = sentinel.SENTINEL_VALUE + + +def get_test_tk_root(test_instance): + """Helper for tests: Create a root Tk object.""" + requires('gui') + root = Tk() + root.withdraw() + + def cleanup_root(): + root.update_idletasks() + root.destroy() + test_instance.addCleanup(cleanup_root) + + return root + + +class CountLinesTest(unittest.TestCase): + """Tests for the count_lines_with_wrapping function.""" + def check(self, expected, text, linewidth): + return self.assertEqual( + expected, + count_lines_with_wrapping(text, linewidth), + ) + + def test_count_empty(self): + """Test with an empty string.""" + self.assertEqual(count_lines_with_wrapping(""), 0) + + def test_count_begins_with_empty_line(self): + """Test with a string which begins with a newline.""" + self.assertEqual(count_lines_with_wrapping("\ntext"), 2) + + def test_count_ends_with_empty_line(self): + """Test with a string which ends with a newline.""" + self.assertEqual(count_lines_with_wrapping("text\n"), 1) + + def test_count_several_lines(self): + """Test with several lines of text.""" + self.assertEqual(count_lines_with_wrapping("1\n2\n3\n"), 3) + + def test_empty_lines(self): + self.check(expected=1, text='\n', linewidth=80) + self.check(expected=2, text='\n\n', linewidth=80) + self.check(expected=10, text='\n' * 10, linewidth=80) + + def test_long_line(self): + self.check(expected=3, text='a' * 200, linewidth=80) + self.check(expected=3, text='a' * 200 + '\n', linewidth=80) + + def test_several_lines_different_lengths(self): + text = dedent("""\ + 13 characters + 43 is the number of characters on this line + + 7 chars + 13 characters""") + self.check(expected=5, text=text, linewidth=80) + self.check(expected=5, text=text + '\n', linewidth=80) + self.check(expected=6, text=text, linewidth=40) + self.check(expected=7, text=text, linewidth=20) + self.check(expected=11, text=text, linewidth=10) + + +class SqueezerTest(unittest.TestCase): + """Tests for the Squeezer class.""" + def make_mock_editor_window(self, with_text_widget=False): + """Create a mock EditorWindow instance.""" + editwin = NonCallableMagicMock() + editwin.width = 80 + + if with_text_widget: + editwin.root = get_test_tk_root(self) + text_widget = self.make_text_widget(root=editwin.root) + editwin.text = editwin.per.bottom = text_widget + + return editwin + + def make_squeezer_instance(self, editor_window=None): + """Create an actual Squeezer instance with a mock EditorWindow.""" + if editor_window is None: + editor_window = self.make_mock_editor_window() + squeezer = Squeezer(editor_window) + return squeezer + + def make_text_widget(self, root=None): + if root is None: + root = get_test_tk_root(self) + text_widget = Text(root) + text_widget["font"] = ('Courier', 10) + text_widget.mark_set("iomark", "1.0") + return text_widget + + def set_idleconf_option_with_cleanup(self, configType, section, option, value): + prev_val = idleConf.GetOption(configType, section, option) + idleConf.SetOption(configType, section, option, value) + self.addCleanup(idleConf.SetOption, + configType, section, option, prev_val) + + def test_count_lines(self): + """Test Squeezer.count_lines() with various inputs.""" + editwin = self.make_mock_editor_window() + squeezer = self.make_squeezer_instance(editwin) + + for text_code, line_width, expected in [ + (r"'\n'", 80, 1), + (r"'\n' * 3", 80, 3), + (r"'a' * 40 + '\n'", 80, 1), + (r"'a' * 80 + '\n'", 80, 1), + (r"'a' * 200 + '\n'", 80, 3), + (r"'aa\t' * 20", 80, 2), + (r"'aa\t' * 21", 80, 3), + (r"'aa\t' * 20", 40, 4), + ]: + with self.subTest(text_code=text_code, + line_width=line_width, + expected=expected): + text = eval(text_code) + with patch.object(editwin, 'width', line_width): + self.assertEqual(squeezer.count_lines(text), expected) + + def test_init(self): + """Test the creation of Squeezer instances.""" + editwin = self.make_mock_editor_window() + squeezer = self.make_squeezer_instance(editwin) + self.assertIs(squeezer.editwin, editwin) + self.assertEqual(squeezer.expandingbuttons, []) + + def test_write_no_tags(self): + """Test Squeezer's overriding of the EditorWindow's write() method.""" + editwin = self.make_mock_editor_window() + for text in ['', 'TEXT', 'LONG TEXT' * 1000, 'MANY_LINES\n' * 100]: + editwin.write = orig_write = Mock(return_value=SENTINEL_VALUE) + squeezer = self.make_squeezer_instance(editwin) + + self.assertEqual(squeezer.editwin.write(text, ()), SENTINEL_VALUE) + self.assertEqual(orig_write.call_count, 1) + orig_write.assert_called_with(text, ()) + self.assertEqual(len(squeezer.expandingbuttons), 0) + + def test_write_not_stdout(self): + """Test Squeezer's overriding of the EditorWindow's write() method.""" + for text in ['', 'TEXT', 'LONG TEXT' * 1000, 'MANY_LINES\n' * 100]: + editwin = self.make_mock_editor_window() + editwin.write.return_value = SENTINEL_VALUE + orig_write = editwin.write + squeezer = self.make_squeezer_instance(editwin) + + self.assertEqual(squeezer.editwin.write(text, "stderr"), + SENTINEL_VALUE) + self.assertEqual(orig_write.call_count, 1) + orig_write.assert_called_with(text, "stderr") + self.assertEqual(len(squeezer.expandingbuttons), 0) + + def test_write_stdout(self): + """Test Squeezer's overriding of the EditorWindow's write() method.""" + editwin = self.make_mock_editor_window() + + for text in ['', 'TEXT']: + editwin.write = orig_write = Mock(return_value=SENTINEL_VALUE) + squeezer = self.make_squeezer_instance(editwin) + squeezer.auto_squeeze_min_lines = 50 + + self.assertEqual(squeezer.editwin.write(text, "stdout"), + SENTINEL_VALUE) + self.assertEqual(orig_write.call_count, 1) + orig_write.assert_called_with(text, "stdout") + self.assertEqual(len(squeezer.expandingbuttons), 0) + + for text in ['LONG TEXT' * 1000, 'MANY_LINES\n' * 100]: + editwin.write = orig_write = Mock(return_value=SENTINEL_VALUE) + squeezer = self.make_squeezer_instance(editwin) + squeezer.auto_squeeze_min_lines = 50 + + self.assertEqual(squeezer.editwin.write(text, "stdout"), None) + self.assertEqual(orig_write.call_count, 0) + self.assertEqual(len(squeezer.expandingbuttons), 1) + + def test_auto_squeeze(self): + """Test that the auto-squeezing creates an ExpandingButton properly.""" + editwin = self.make_mock_editor_window(with_text_widget=True) + text_widget = editwin.text + squeezer = self.make_squeezer_instance(editwin) + squeezer.auto_squeeze_min_lines = 5 + squeezer.count_lines = Mock(return_value=6) + + editwin.write('TEXT\n'*6, "stdout") + self.assertEqual(text_widget.get('1.0', 'end'), '\n') + self.assertEqual(len(squeezer.expandingbuttons), 1) + + def test_squeeze_current_text(self): + """Test the squeeze_current_text method.""" + # Squeezing text should work for both stdout and stderr. + for tag_name in ["stdout", "stderr"]: + editwin = self.make_mock_editor_window(with_text_widget=True) + text_widget = editwin.text + squeezer = self.make_squeezer_instance(editwin) + squeezer.count_lines = Mock(return_value=6) + + # Prepare some text in the Text widget. + text_widget.insert("1.0", "SOME\nTEXT\n", tag_name) + text_widget.mark_set("insert", "1.0") + self.assertEqual(text_widget.get('1.0', 'end'), 'SOME\nTEXT\n\n') + + self.assertEqual(len(squeezer.expandingbuttons), 0) + + # Test squeezing the current text. + retval = squeezer.squeeze_current_text() + self.assertEqual(retval, "break") + self.assertEqual(text_widget.get('1.0', 'end'), '\n\n') + self.assertEqual(len(squeezer.expandingbuttons), 1) + self.assertEqual(squeezer.expandingbuttons[0].s, 'SOME\nTEXT') + + # Test that expanding the squeezed text works and afterwards + # the Text widget contains the original text. + squeezer.expandingbuttons[0].expand() + self.assertEqual(text_widget.get('1.0', 'end'), 'SOME\nTEXT\n\n') + self.assertEqual(len(squeezer.expandingbuttons), 0) + + def test_squeeze_current_text_no_allowed_tags(self): + """Test that the event doesn't squeeze text without a relevant tag.""" + editwin = self.make_mock_editor_window(with_text_widget=True) + text_widget = editwin.text + squeezer = self.make_squeezer_instance(editwin) + squeezer.count_lines = Mock(return_value=6) + + # Prepare some text in the Text widget. + text_widget.insert("1.0", "SOME\nTEXT\n", "TAG") + text_widget.mark_set("insert", "1.0") + self.assertEqual(text_widget.get('1.0', 'end'), 'SOME\nTEXT\n\n') + + self.assertEqual(len(squeezer.expandingbuttons), 0) + + # Test squeezing the current text. + retval = squeezer.squeeze_current_text() + self.assertEqual(retval, "break") + self.assertEqual(text_widget.get('1.0', 'end'), 'SOME\nTEXT\n\n') + self.assertEqual(len(squeezer.expandingbuttons), 0) + + def test_squeeze_text_before_existing_squeezed_text(self): + """Test squeezing text before existing squeezed text.""" + editwin = self.make_mock_editor_window(with_text_widget=True) + text_widget = editwin.text + squeezer = self.make_squeezer_instance(editwin) + squeezer.count_lines = Mock(return_value=6) + + # Prepare some text in the Text widget and squeeze it. + text_widget.insert("1.0", "SOME\nTEXT\n", "stdout") + text_widget.mark_set("insert", "1.0") + squeezer.squeeze_current_text() + self.assertEqual(len(squeezer.expandingbuttons), 1) + + # Test squeezing the current text. + text_widget.insert("1.0", "MORE\nSTUFF\n", "stdout") + text_widget.mark_set("insert", "1.0") + retval = squeezer.squeeze_current_text() + self.assertEqual(retval, "break") + self.assertEqual(text_widget.get('1.0', 'end'), '\n\n\n') + self.assertEqual(len(squeezer.expandingbuttons), 2) + self.assertTrue(text_widget.compare( + squeezer.expandingbuttons[0], + '<', + squeezer.expandingbuttons[1], + )) + + def test_reload(self): + """Test the reload() class-method.""" + editwin = self.make_mock_editor_window(with_text_widget=True) + squeezer = self.make_squeezer_instance(editwin) + + orig_auto_squeeze_min_lines = squeezer.auto_squeeze_min_lines + + # Increase auto-squeeze-min-lines. + new_auto_squeeze_min_lines = orig_auto_squeeze_min_lines + 10 + self.set_idleconf_option_with_cleanup( + 'main', 'PyShell', 'auto-squeeze-min-lines', + str(new_auto_squeeze_min_lines)) + + Squeezer.reload() + self.assertEqual(squeezer.auto_squeeze_min_lines, + new_auto_squeeze_min_lines) + + def test_reload_no_squeezer_instances(self): + """Test that Squeezer.reload() runs without any instances existing.""" + Squeezer.reload() + + +class ExpandingButtonTest(unittest.TestCase): + """Tests for the ExpandingButton class.""" + # In these tests the squeezer instance is a mock, but actual tkinter + # Text and Button instances are created. + def make_mock_squeezer(self): + """Helper for tests: Create a mock Squeezer object.""" + root = get_test_tk_root(self) + squeezer = Mock() + squeezer.editwin.text = Text(root) + squeezer.editwin.per = Percolator(squeezer.editwin.text) + self.addCleanup(squeezer.editwin.per.close) + + # Set default values for the configuration settings. + squeezer.auto_squeeze_min_lines = 50 + return squeezer + + @patch('idlelib.squeezer.Hovertip', autospec=Hovertip) + def test_init(self, MockHovertip): + """Test the simplest creation of an ExpandingButton.""" + squeezer = self.make_mock_squeezer() + text_widget = squeezer.editwin.text + + expandingbutton = ExpandingButton('TEXT', 'TAGS', 50, squeezer) + self.assertEqual(expandingbutton.s, 'TEXT') + + # Check that the underlying tkinter.Button is properly configured. + self.assertEqual(expandingbutton.master, text_widget) + self.assertTrue('50 lines' in expandingbutton.cget('text')) + + # Check that the text widget still contains no text. + self.assertEqual(text_widget.get('1.0', 'end'), '\n') + + # Check that the mouse events are bound. + self.assertIn('', expandingbutton.bind()) + right_button_code = '' % ('2' if macosx.isAquaTk() else '3') + self.assertIn(right_button_code, expandingbutton.bind()) + + # Check that ToolTip was called once, with appropriate values. + self.assertEqual(MockHovertip.call_count, 1) + MockHovertip.assert_called_with(expandingbutton, ANY, hover_delay=ANY) + + # Check that 'right-click' appears in the tooltip text. + tooltip_text = MockHovertip.call_args[0][1] + self.assertIn('right-click', tooltip_text.lower()) + + def test_expand(self): + """Test the expand event.""" + squeezer = self.make_mock_squeezer() + expandingbutton = ExpandingButton('TEXT', 'TAGS', 50, squeezer) + + # Insert the button into the text widget + # (this is normally done by the Squeezer class). + text_widget = squeezer.editwin.text + text_widget.window_create("1.0", window=expandingbutton) + + # trigger the expand event + retval = expandingbutton.expand(event=Mock()) + self.assertEqual(retval, None) + + # Check that the text was inserted into the text widget. + self.assertEqual(text_widget.get('1.0', 'end'), 'TEXT\n') + + # Check that the 'TAGS' tag was set on the inserted text. + text_end_index = text_widget.index('end-1c') + self.assertEqual(text_widget.get('1.0', text_end_index), 'TEXT') + self.assertEqual(text_widget.tag_nextrange('TAGS', '1.0'), + ('1.0', text_end_index)) + + # Check that the button removed itself from squeezer.expandingbuttons. + self.assertEqual(squeezer.expandingbuttons.remove.call_count, 1) + squeezer.expandingbuttons.remove.assert_called_with(expandingbutton) + + def test_expand_dangerous_oupput(self): + """Test that expanding very long output asks user for confirmation.""" + squeezer = self.make_mock_squeezer() + text = 'a' * 10**5 + expandingbutton = ExpandingButton(text, 'TAGS', 50, squeezer) + expandingbutton.set_is_dangerous() + self.assertTrue(expandingbutton.is_dangerous) + + # Insert the button into the text widget + # (this is normally done by the Squeezer class). + text_widget = expandingbutton.text + text_widget.window_create("1.0", window=expandingbutton) + + # Patch the message box module to always return False. + with patch('idlelib.squeezer.messagebox') as mock_msgbox: + mock_msgbox.askokcancel.return_value = False + mock_msgbox.askyesno.return_value = False + # Trigger the expand event. + retval = expandingbutton.expand(event=Mock()) + + # Check that the event chain was broken and no text was inserted. + self.assertEqual(retval, 'break') + self.assertEqual(expandingbutton.text.get('1.0', 'end-1c'), '') + + # Patch the message box module to always return True. + with patch('idlelib.squeezer.messagebox') as mock_msgbox: + mock_msgbox.askokcancel.return_value = True + mock_msgbox.askyesno.return_value = True + # Trigger the expand event. + retval = expandingbutton.expand(event=Mock()) + + # Check that the event chain wasn't broken and the text was inserted. + self.assertEqual(retval, None) + self.assertEqual(expandingbutton.text.get('1.0', 'end-1c'), text) + + def test_copy(self): + """Test the copy event.""" + # Testing with the actual clipboard proved problematic, so this + # test replaces the clipboard manipulation functions with mocks + # and checks that they are called appropriately. + squeezer = self.make_mock_squeezer() + expandingbutton = ExpandingButton('TEXT', 'TAGS', 50, squeezer) + expandingbutton.clipboard_clear = Mock() + expandingbutton.clipboard_append = Mock() + + # Trigger the copy event. + retval = expandingbutton.copy(event=Mock()) + self.assertEqual(retval, None) + + # Vheck that the expanding button called clipboard_clear() and + # clipboard_append('TEXT') once each. + self.assertEqual(expandingbutton.clipboard_clear.call_count, 1) + self.assertEqual(expandingbutton.clipboard_append.call_count, 1) + expandingbutton.clipboard_append.assert_called_with('TEXT') + + def test_view(self): + """Test the view event.""" + squeezer = self.make_mock_squeezer() + expandingbutton = ExpandingButton('TEXT', 'TAGS', 50, squeezer) + expandingbutton.selection_own = Mock() + + with patch('idlelib.squeezer.view_text', autospec=view_text)\ + as mock_view_text: + # Trigger the view event. + expandingbutton.view(event=Mock()) + + # Check that the expanding button called view_text. + self.assertEqual(mock_view_text.call_count, 1) + + # Check that the proper text was passed. + self.assertEqual(mock_view_text.call_args[0][2], 'TEXT') + + def test_rmenu(self): + """Test the context menu.""" + squeezer = self.make_mock_squeezer() + expandingbutton = ExpandingButton('TEXT', 'TAGS', 50, squeezer) + with patch('tkinter.Menu') as mock_Menu: + mock_menu = Mock() + mock_Menu.return_value = mock_menu + mock_event = Mock() + mock_event.x = 10 + mock_event.y = 10 + expandingbutton.context_menu_event(event=mock_event) + self.assertEqual(mock_menu.add_command.call_count, + len(expandingbutton.rmenu_specs)) + for label, *data in expandingbutton.rmenu_specs: + mock_menu.add_command.assert_any_call(label=label, command=ANY) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_stackviewer.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_stackviewer.py new file mode 100644 index 0000000000000000000000000000000000000000..55f510382bf4c3699ab3baff416af72068660fc7 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_stackviewer.py @@ -0,0 +1,41 @@ +"Test stackviewer, coverage 63%." + +from idlelib import stackviewer +import unittest +from test.support import requires +from tkinter import Tk + +from idlelib.tree import TreeNode, ScrolledCanvas + + +class StackBrowserTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + + requires('gui') + cls.root = Tk() + cls.root.withdraw() + + @classmethod + def tearDownClass(cls): + + cls.root.update_idletasks() +## for id in cls.root.tk.call('after', 'info'): +## cls.root.after_cancel(id) # Need for EditorWindow. + cls.root.destroy() + del cls.root + + def test_init(self): + try: + abc + except NameError as exc: + sb = stackviewer.StackBrowser(self.root, exc) + isi = self.assertIsInstance + isi(stackviewer.sc, ScrolledCanvas) + isi(stackviewer.item, stackviewer.StackTreeItem) + isi(stackviewer.node, TreeNode) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_statusbar.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_statusbar.py new file mode 100644 index 0000000000000000000000000000000000000000..203a57db89ca6a7df608cc7d24c4301299d222d8 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_statusbar.py @@ -0,0 +1,41 @@ +"Test statusbar, coverage 100%." + +from idlelib import statusbar +import unittest +from test.support import requires +from tkinter import Tk + + +class Test(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + + @classmethod + def tearDownClass(cls): + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def test_init(self): + bar = statusbar.MultiStatusBar(self.root) + self.assertEqual(bar.labels, {}) + + def test_set_label(self): + bar = statusbar.MultiStatusBar(self.root) + bar.set_label('left', text='sometext', width=10) + self.assertIn('left', bar.labels) + left = bar.labels['left'] + self.assertEqual(left['text'], 'sometext') + self.assertEqual(left['width'], 10) + bar.set_label('left', text='revised text') + self.assertEqual(left['text'], 'revised text') + bar.set_label('right', text='correct text') + self.assertEqual(bar.labels['right']['text'], 'correct text') + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_text.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_text.py new file mode 100644 index 0000000000000000000000000000000000000000..43a9ba02c3d3c9a8739ec85e4780fc03743ef29c --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_text.py @@ -0,0 +1,236 @@ +''' Test mock_tk.Text class against tkinter.Text class + +Run same tests with both by creating a mixin class. +''' +import unittest +from test.support import requires +from _tkinter import TclError + +class TextTest: + "Define items common to both sets of tests." + + hw = 'hello\nworld' # Several tests insert this after initialization. + hwn = hw+'\n' # \n present at initialization, before insert + + # setUpClass defines cls.Text and maybe cls.root. + # setUp defines self.text from Text and maybe root. + + def test_init(self): + self.assertEqual(self.text.get('1.0'), '\n') + self.assertEqual(self.text.get('end'), '') + + def test_index_empty(self): + index = self.text.index + + for dex in (-1.0, 0.3, '1.-1', '1.0', '1.0 lineend', '1.end', '1.33', + 'insert'): + self.assertEqual(index(dex), '1.0') + + for dex in 'end', 2.0, '2.1', '33.44': + self.assertEqual(index(dex), '2.0') + + def test_index_data(self): + index = self.text.index + self.text.insert('1.0', self.hw) + + for dex in -1.0, 0.3, '1.-1', '1.0': + self.assertEqual(index(dex), '1.0') + + for dex in '1.0 lineend', '1.end', '1.33': + self.assertEqual(index(dex), '1.5') + + for dex in 'end', '33.44': + self.assertEqual(index(dex), '3.0') + + def test_get(self): + get = self.text.get + Equal = self.assertEqual + self.text.insert('1.0', self.hw) + + Equal(get('end'), '') + Equal(get('end', 'end'), '') + Equal(get('1.0'), 'h') + Equal(get('1.0', '1.1'), 'h') + Equal(get('1.0', '1.3'), 'hel') + Equal(get('1.1', '1.3'), 'el') + Equal(get('1.0', '1.0 lineend'), 'hello') + Equal(get('1.0', '1.10'), 'hello') + Equal(get('1.0 lineend'), '\n') + Equal(get('1.1', '2.3'), 'ello\nwor') + Equal(get('1.0', '2.5'), self.hw) + Equal(get('1.0', 'end'), self.hwn) + Equal(get('0.0', '5.0'), self.hwn) + + def test_insert(self): + insert = self.text.insert + get = self.text.get + Equal = self.assertEqual + + insert('1.0', self.hw) + Equal(get('1.0', 'end'), self.hwn) + + insert('1.0', '') # nothing + Equal(get('1.0', 'end'), self.hwn) + + insert('1.0', '*') + Equal(get('1.0', 'end'), '*hello\nworld\n') + + insert('1.0 lineend', '*') + Equal(get('1.0', 'end'), '*hello*\nworld\n') + + insert('2.3', '*') + Equal(get('1.0', 'end'), '*hello*\nwor*ld\n') + + insert('end', 'x') + Equal(get('1.0', 'end'), '*hello*\nwor*ldx\n') + + insert('1.4', 'x\n') + Equal(get('1.0', 'end'), '*helx\nlo*\nwor*ldx\n') + + def test_no_delete(self): + # if index1 == 'insert' or 'end' or >= end, there is no deletion + delete = self.text.delete + get = self.text.get + Equal = self.assertEqual + self.text.insert('1.0', self.hw) + + delete('insert') + Equal(get('1.0', 'end'), self.hwn) + + delete('end') + Equal(get('1.0', 'end'), self.hwn) + + delete('insert', 'end') + Equal(get('1.0', 'end'), self.hwn) + + delete('insert', '5.5') + Equal(get('1.0', 'end'), self.hwn) + + delete('1.4', '1.0') + Equal(get('1.0', 'end'), self.hwn) + + delete('1.4', '1.4') + Equal(get('1.0', 'end'), self.hwn) + + def test_delete_char(self): + delete = self.text.delete + get = self.text.get + Equal = self.assertEqual + self.text.insert('1.0', self.hw) + + delete('1.0') + Equal(get('1.0', '1.end'), 'ello') + + delete('1.0', '1.1') + Equal(get('1.0', '1.end'), 'llo') + + # delete \n and combine 2 lines into 1 + delete('1.end') + Equal(get('1.0', '1.end'), 'lloworld') + + self.text.insert('1.3', '\n') + delete('1.10') + Equal(get('1.0', '1.end'), 'lloworld') + + self.text.insert('1.3', '\n') + delete('1.3', '2.0') + Equal(get('1.0', '1.end'), 'lloworld') + + def test_delete_slice(self): + delete = self.text.delete + get = self.text.get + Equal = self.assertEqual + self.text.insert('1.0', self.hw) + + delete('1.0', '1.0 lineend') + Equal(get('1.0', 'end'), '\nworld\n') + + delete('1.0', 'end') + Equal(get('1.0', 'end'), '\n') + + self.text.insert('1.0', self.hw) + delete('1.0', '2.0') + Equal(get('1.0', 'end'), 'world\n') + + delete('1.0', 'end') + Equal(get('1.0', 'end'), '\n') + + self.text.insert('1.0', self.hw) + delete('1.2', '2.3') + Equal(get('1.0', 'end'), 'held\n') + + def test_multiple_lines(self): # insert and delete + self.text.insert('1.0', 'hello') + + self.text.insert('1.3', '1\n2\n3\n4\n5') + self.assertEqual(self.text.get('1.0', 'end'), 'hel1\n2\n3\n4\n5lo\n') + + self.text.delete('1.3', '5.1') + self.assertEqual(self.text.get('1.0', 'end'), 'hello\n') + + def test_compare(self): + compare = self.text.compare + Equal = self.assertEqual + # need data so indexes not squished to 1,0 + self.text.insert('1.0', 'First\nSecond\nThird\n') + + self.assertRaises(TclError, compare, '2.2', 'op', '2.2') + + for op, less1, less0, equal, greater0, greater1 in ( + ('<', True, True, False, False, False), + ('<=', True, True, True, False, False), + ('>', False, False, False, True, True), + ('>=', False, False, True, True, True), + ('==', False, False, True, False, False), + ('!=', True, True, False, True, True), + ): + Equal(compare('1.1', op, '2.2'), less1, op) + Equal(compare('2.1', op, '2.2'), less0, op) + Equal(compare('2.2', op, '2.2'), equal, op) + Equal(compare('2.3', op, '2.2'), greater0, op) + Equal(compare('3.3', op, '2.2'), greater1, op) + + +class MockTextTest(TextTest, unittest.TestCase): + + @classmethod + def setUpClass(cls): + from idlelib.idle_test.mock_tk import Text + cls.Text = Text + + def setUp(self): + self.text = self.Text() + + + def test_decode(self): + # test endflags (-1, 0) not tested by test_index (which uses +1) + decode = self.text._decode + Equal = self.assertEqual + self.text.insert('1.0', self.hw) + + Equal(decode('end', -1), (2, 5)) + Equal(decode('3.1', -1), (2, 5)) + Equal(decode('end', 0), (2, 6)) + Equal(decode('3.1', 0), (2, 6)) + + +class TkTextTest(TextTest, unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + from tkinter import Tk, Text + cls.Text = Text + cls.root = Tk() + + @classmethod + def tearDownClass(cls): + cls.root.destroy() + del cls.root + + def setUp(self): + self.text = self.Text(self.root) + + +if __name__ == '__main__': + unittest.main(verbosity=2, exit=False) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_textview.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_textview.py new file mode 100644 index 0000000000000000000000000000000000000000..7189378ab3dd615e04cf17c2869e1fd611cb4eb1 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_textview.py @@ -0,0 +1,233 @@ +"""Test textview, coverage 100%. + +Since all methods and functions create (or destroy) a ViewWindow, which +is a widget containing a widget, etcetera, all tests must be gui tests. +Using mock Text would not change this. Other mocks are used to retrieve +information about calls. +""" +from idlelib import textview as tv +from test.support import requires +requires('gui') + +import os +import unittest +from tkinter import Tk, TclError, CHAR, NONE, WORD +from tkinter.ttk import Button +from idlelib.idle_test.mock_idle import Func +from idlelib.idle_test.mock_tk import Mbox_func + +def setUpModule(): + global root + root = Tk() + root.withdraw() + +def tearDownModule(): + global root + root.update_idletasks() + root.destroy() + del root + +# If we call ViewWindow or wrapper functions with defaults +# modal=True, _utest=False, test hangs on call to wait_window. +# Have also gotten tk error 'can't invoke "event" command'. + + +class VW(tv.ViewWindow): # Used in ViewWindowTest. + transient = Func() + grab_set = Func() + wait_window = Func() + + +# Call wrapper class VW with mock wait_window. +class ViewWindowTest(unittest.TestCase): + + def setUp(self): + VW.transient.__init__() + VW.grab_set.__init__() + VW.wait_window.__init__() + + def test_init_modal(self): + view = VW(root, 'Title', 'test text') + self.assertTrue(VW.transient.called) + self.assertTrue(VW.grab_set.called) + self.assertTrue(VW.wait_window.called) + view.ok() + + def test_init_nonmodal(self): + view = VW(root, 'Title', 'test text', modal=False) + self.assertFalse(VW.transient.called) + self.assertFalse(VW.grab_set.called) + self.assertFalse(VW.wait_window.called) + view.ok() + + def test_ok(self): + view = VW(root, 'Title', 'test text', modal=False) + view.destroy = Func() + view.ok() + self.assertTrue(view.destroy.called) + del view.destroy # Unmask real function. + view.destroy() + + +class AutoHideScrollbarTest(unittest.TestCase): + # Method set is tested in ScrollableTextFrameTest + def test_forbidden_geometry(self): + scroll = tv.AutoHideScrollbar(root) + self.assertRaises(TclError, scroll.pack) + self.assertRaises(TclError, scroll.place) + + +class ScrollableTextFrameTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + cls.root = root = Tk() + root.withdraw() + + @classmethod + def tearDownClass(cls): + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def make_frame(self, wrap=NONE, **kwargs): + frame = tv.ScrollableTextFrame(self.root, wrap=wrap, **kwargs) + def cleanup_frame(): + frame.update_idletasks() + frame.destroy() + self.addCleanup(cleanup_frame) + return frame + + def test_line1(self): + frame = self.make_frame() + frame.text.insert('1.0', 'test text') + self.assertEqual(frame.text.get('1.0', '1.end'), 'test text') + + def test_horiz_scrollbar(self): + # The horizontal scrollbar should be shown/hidden according to + # the 'wrap' setting: It should only be shown when 'wrap' is + # set to NONE. + + # wrap = NONE -> with horizontal scrolling + frame = self.make_frame(wrap=NONE) + self.assertEqual(frame.text.cget('wrap'), NONE) + self.assertIsNotNone(frame.xscroll) + + # wrap != NONE -> no horizontal scrolling + for wrap in [CHAR, WORD]: + with self.subTest(wrap=wrap): + frame = self.make_frame(wrap=wrap) + self.assertEqual(frame.text.cget('wrap'), wrap) + self.assertIsNone(frame.xscroll) + + +class ViewFrameTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + cls.root = root = Tk() + root.withdraw() + cls.frame = tv.ViewFrame(root, 'test text') + + @classmethod + def tearDownClass(cls): + del cls.frame + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def test_line1(self): + get = self.frame.text.get + self.assertEqual(get('1.0', '1.end'), 'test text') + + +# Call ViewWindow with modal=False. +class ViewFunctionTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + cls.orig_error = tv.showerror + tv.showerror = Mbox_func() + + @classmethod + def tearDownClass(cls): + tv.showerror = cls.orig_error + del cls.orig_error + + def test_view_text(self): + view = tv.view_text(root, 'Title', 'test text', modal=False) + self.assertIsInstance(view, tv.ViewWindow) + self.assertIsInstance(view.viewframe, tv.ViewFrame) + view.viewframe.ok() + + def test_view_file(self): + view = tv.view_file(root, 'Title', __file__, 'ascii', modal=False) + self.assertIsInstance(view, tv.ViewWindow) + self.assertIsInstance(view.viewframe, tv.ViewFrame) + get = view.viewframe.textframe.text.get + self.assertIn('Test', get('1.0', '1.end')) + view.ok() + + def test_bad_file(self): + # Mock showerror will be used; view_file will return None. + view = tv.view_file(root, 'Title', 'abc.xyz', 'ascii', modal=False) + self.assertIsNone(view) + self.assertEqual(tv.showerror.title, 'File Load Error') + + def test_bad_encoding(self): + p = os.path + fn = p.abspath(p.join(p.dirname(__file__), '..', 'CREDITS.txt')) + view = tv.view_file(root, 'Title', fn, 'ascii', modal=False) + self.assertIsNone(view) + self.assertEqual(tv.showerror.title, 'Unicode Decode Error') + + def test_nowrap(self): + view = tv.view_text(root, 'Title', 'test', modal=False, wrap='none') + text_widget = view.viewframe.textframe.text + self.assertEqual(text_widget.cget('wrap'), 'none') + + +# Call ViewWindow with _utest=True. +class ButtonClickTest(unittest.TestCase): + + def setUp(self): + self.view = None + self.called = False + + def tearDown(self): + if self.view: + self.view.destroy() + + def test_view_text_bind_with_button(self): + def _command(): + self.called = True + self.view = tv.view_text(root, 'TITLE_TEXT', 'COMMAND', _utest=True) + button = Button(root, text='BUTTON', command=_command) + button.invoke() + self.addCleanup(button.destroy) + + self.assertEqual(self.called, True) + self.assertEqual(self.view.title(), 'TITLE_TEXT') + self.assertEqual(self.view.viewframe.textframe.text.get('1.0', '1.end'), + 'COMMAND') + + def test_view_file_bind_with_button(self): + def _command(): + self.called = True + self.view = tv.view_file(root, 'TITLE_FILE', __file__, + encoding='ascii', _utest=True) + button = Button(root, text='BUTTON', command=_command) + button.invoke() + self.addCleanup(button.destroy) + + self.assertEqual(self.called, True) + self.assertEqual(self.view.title(), 'TITLE_FILE') + get = self.view.viewframe.textframe.text.get + with open(__file__) as f: + self.assertEqual(get('1.0', '1.end'), f.readline().strip()) + f.readline() + self.assertEqual(get('3.0', '3.end'), f.readline().strip()) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_tooltip.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_tooltip.py new file mode 100644 index 0000000000000000000000000000000000000000..c616d4fde3b6d30433c0e163206059c1c55f1ea2 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_tooltip.py @@ -0,0 +1,161 @@ +"""Test tooltip, coverage 100%. + +Coverage is 100% after excluding 6 lines with "# pragma: no cover". +They involve TclErrors that either should or should not happen in a +particular situation, and which are 'pass'ed if they do. +""" + +from idlelib.tooltip import TooltipBase, Hovertip +from test.support import requires +requires('gui') + +from functools import wraps +import time +from tkinter import Button, Tk, Toplevel +import unittest + + +def setUpModule(): + global root + root = Tk() + +def tearDownModule(): + global root + root.update_idletasks() + root.destroy() + del root + + +def add_call_counting(func): + @wraps(func) + def wrapped_func(*args, **kwargs): + wrapped_func.call_args_list.append((args, kwargs)) + return func(*args, **kwargs) + wrapped_func.call_args_list = [] + return wrapped_func + + +def _make_top_and_button(testobj): + global root + top = Toplevel(root) + testobj.addCleanup(top.destroy) + top.title("Test tooltip") + button = Button(top, text='ToolTip test button') + button.pack() + testobj.addCleanup(button.destroy) + top.lift() + return top, button + + +class ToolTipBaseTest(unittest.TestCase): + def setUp(self): + self.top, self.button = _make_top_and_button(self) + + def test_base_class_is_unusable(self): + global root + top = Toplevel(root) + self.addCleanup(top.destroy) + + button = Button(top, text='ToolTip test button') + button.pack() + self.addCleanup(button.destroy) + + with self.assertRaises(NotImplementedError): + tooltip = TooltipBase(button) + tooltip.showtip() + + +class HovertipTest(unittest.TestCase): + def setUp(self): + self.top, self.button = _make_top_and_button(self) + + def is_tipwindow_shown(self, tooltip): + return tooltip.tipwindow and tooltip.tipwindow.winfo_viewable() + + def test_showtip(self): + tooltip = Hovertip(self.button, 'ToolTip text') + self.addCleanup(tooltip.hidetip) + self.assertFalse(self.is_tipwindow_shown(tooltip)) + tooltip.showtip() + self.assertTrue(self.is_tipwindow_shown(tooltip)) + + def test_showtip_twice(self): + tooltip = Hovertip(self.button, 'ToolTip text') + self.addCleanup(tooltip.hidetip) + self.assertFalse(self.is_tipwindow_shown(tooltip)) + tooltip.showtip() + self.assertTrue(self.is_tipwindow_shown(tooltip)) + orig_tipwindow = tooltip.tipwindow + tooltip.showtip() + self.assertTrue(self.is_tipwindow_shown(tooltip)) + self.assertIs(tooltip.tipwindow, orig_tipwindow) + + def test_hidetip(self): + tooltip = Hovertip(self.button, 'ToolTip text') + self.addCleanup(tooltip.hidetip) + tooltip.showtip() + tooltip.hidetip() + self.assertFalse(self.is_tipwindow_shown(tooltip)) + + def test_showtip_on_mouse_enter_no_delay(self): + tooltip = Hovertip(self.button, 'ToolTip text', hover_delay=None) + self.addCleanup(tooltip.hidetip) + tooltip.showtip = add_call_counting(tooltip.showtip) + root.update() + self.assertFalse(self.is_tipwindow_shown(tooltip)) + self.button.event_generate('', x=0, y=0) + root.update() + self.assertTrue(self.is_tipwindow_shown(tooltip)) + self.assertGreater(len(tooltip.showtip.call_args_list), 0) + + def test_hover_with_delay(self): + # Run multiple tests requiring an actual delay simultaneously. + + # Test #1: A hover tip with a non-zero delay appears after the delay. + tooltip1 = Hovertip(self.button, 'ToolTip text', hover_delay=100) + self.addCleanup(tooltip1.hidetip) + tooltip1.showtip = add_call_counting(tooltip1.showtip) + root.update() + self.assertFalse(self.is_tipwindow_shown(tooltip1)) + self.button.event_generate('', x=0, y=0) + root.update() + self.assertFalse(self.is_tipwindow_shown(tooltip1)) + + # Test #2: A hover tip with a non-zero delay doesn't appear when + # the mouse stops hovering over the base widget before the delay + # expires. + tooltip2 = Hovertip(self.button, 'ToolTip text', hover_delay=100) + self.addCleanup(tooltip2.hidetip) + tooltip2.showtip = add_call_counting(tooltip2.showtip) + root.update() + self.button.event_generate('', x=0, y=0) + root.update() + self.button.event_generate('', x=0, y=0) + root.update() + + time.sleep(0.15) + root.update() + + # Test #1 assertions. + self.assertTrue(self.is_tipwindow_shown(tooltip1)) + self.assertGreater(len(tooltip1.showtip.call_args_list), 0) + + # Test #2 assertions. + self.assertFalse(self.is_tipwindow_shown(tooltip2)) + self.assertEqual(tooltip2.showtip.call_args_list, []) + + def test_hidetip_on_mouse_leave(self): + tooltip = Hovertip(self.button, 'ToolTip text', hover_delay=None) + self.addCleanup(tooltip.hidetip) + tooltip.showtip = add_call_counting(tooltip.showtip) + root.update() + self.button.event_generate('', x=0, y=0) + root.update() + self.button.event_generate('', x=0, y=0) + root.update() + self.assertFalse(self.is_tipwindow_shown(tooltip)) + self.assertGreater(len(tooltip.showtip.call_args_list), 0) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_tree.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_tree.py new file mode 100644 index 0000000000000000000000000000000000000000..b3e4c10cf9e38e7efc183352f6de98673841d9fd --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_tree.py @@ -0,0 +1,60 @@ +"Test tree. coverage 56%." + +from idlelib import tree +import unittest +from test.support import requires +requires('gui') +from tkinter import Tk, EventType, SCROLL + + +class TreeTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + cls.root = Tk() + cls.root.withdraw() + + @classmethod + def tearDownClass(cls): + cls.root.destroy() + del cls.root + + def test_init(self): + # Start with code slightly adapted from htest. + sc = tree.ScrolledCanvas( + self.root, bg="white", highlightthickness=0, takefocus=1) + sc.frame.pack(expand=1, fill="both", side='left') + item = tree.FileTreeItem(tree.ICONDIR) + node = tree.TreeNode(sc.canvas, None, item) + node.expand() + + +class TestScrollEvent(unittest.TestCase): + + def test_wheel_event(self): + # Fake widget class containing `yview` only. + class _Widget: + def __init__(widget, *expected): + widget.expected = expected + def yview(widget, *args): + self.assertTupleEqual(widget.expected, args) + # Fake event class + class _Event: + pass + # (type, delta, num, amount) + tests = ((EventType.MouseWheel, 120, -1, -5), + (EventType.MouseWheel, -120, -1, 5), + (EventType.ButtonPress, -1, 4, -5), + (EventType.ButtonPress, -1, 5, 5)) + + event = _Event() + for ty, delta, num, amount in tests: + event.type = ty + event.delta = delta + event.num = num + res = tree.wheel_event(event, _Widget(SCROLL, amount, "units")) + self.assertEqual(res, "break") + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_undo.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_undo.py new file mode 100644 index 0000000000000000000000000000000000000000..beb5b582039f8844dd179561c7bb939606184375 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_undo.py @@ -0,0 +1,135 @@ +"Test undo, coverage 77%." +# Only test UndoDelegator so far. + +from idlelib.undo import UndoDelegator +import unittest +from test.support import requires +requires('gui') + +from unittest.mock import Mock +from tkinter import Text, Tk +from idlelib.percolator import Percolator + + +class UndoDelegatorTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + cls.root = Tk() + cls.text = Text(cls.root) + cls.percolator = Percolator(cls.text) + + @classmethod + def tearDownClass(cls): + cls.percolator.redir.close() + del cls.percolator, cls.text + cls.root.destroy() + del cls.root + + def setUp(self): + self.delegator = UndoDelegator() + self.delegator.bell = Mock() + self.percolator.insertfilter(self.delegator) + + def tearDown(self): + self.percolator.removefilter(self.delegator) + self.text.delete('1.0', 'end') + self.delegator.resetcache() + + def test_undo_event(self): + text = self.text + + text.insert('insert', 'foobar') + text.insert('insert', 'h') + text.event_generate('<>') + self.assertEqual(text.get('1.0', 'end'), '\n') + + text.insert('insert', 'foo') + text.insert('insert', 'bar') + text.delete('1.2', '1.4') + text.insert('insert', 'hello') + text.event_generate('<>') + self.assertEqual(text.get('1.0', '1.4'), 'foar') + text.event_generate('<>') + self.assertEqual(text.get('1.0', '1.6'), 'foobar') + text.event_generate('<>') + self.assertEqual(text.get('1.0', '1.3'), 'foo') + text.event_generate('<>') + self.delegator.undo_event('event') + self.assertTrue(self.delegator.bell.called) + + def test_redo_event(self): + text = self.text + + text.insert('insert', 'foo') + text.insert('insert', 'bar') + text.delete('1.0', '1.3') + text.event_generate('<>') + text.event_generate('<>') + self.assertEqual(text.get('1.0', '1.3'), 'bar') + text.event_generate('<>') + self.assertTrue(self.delegator.bell.called) + + def test_dump_event(self): + """ + Dump_event cannot be tested directly without changing + environment variables. So, test statements in dump_event + indirectly + """ + text = self.text + d = self.delegator + + text.insert('insert', 'foo') + text.insert('insert', 'bar') + text.delete('1.2', '1.4') + self.assertTupleEqual((d.pointer, d.can_merge), (3, True)) + text.event_generate('<>') + self.assertTupleEqual((d.pointer, d.can_merge), (2, False)) + + def test_get_set_saved(self): + # test the getter method get_saved + # test the setter method set_saved + # indirectly test check_saved + d = self.delegator + + self.assertTrue(d.get_saved()) + self.text.insert('insert', 'a') + self.assertFalse(d.get_saved()) + d.saved_change_hook = Mock() + + d.set_saved(True) + self.assertEqual(d.pointer, d.saved) + self.assertTrue(d.saved_change_hook.called) + + d.set_saved(False) + self.assertEqual(d.saved, -1) + self.assertTrue(d.saved_change_hook.called) + + def test_undo_start_stop(self): + # test the undo_block_start and undo_block_stop methods + text = self.text + + text.insert('insert', 'foo') + self.delegator.undo_block_start() + text.insert('insert', 'bar') + text.insert('insert', 'bar') + self.delegator.undo_block_stop() + self.assertEqual(text.get('1.0', '1.3'), 'foo') + + # test another code path + self.delegator.undo_block_start() + text.insert('insert', 'bar') + self.delegator.undo_block_stop() + self.assertEqual(text.get('1.0', '1.3'), 'foo') + + def test_addcmd(self): + text = self.text + # when number of undo operations exceeds max_undo + self.delegator.max_undo = max_undo = 10 + for i in range(max_undo + 10): + text.insert('insert', 'foo') + self.assertLessEqual(len(self.delegator.undolist), max_undo) + + +if __name__ == '__main__': + unittest.main(verbosity=2, exit=False) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_util.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_util.py new file mode 100644 index 0000000000000000000000000000000000000000..20721fe980c784e1497ef96c7e52d11f834d9740 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_util.py @@ -0,0 +1,14 @@ +"""Test util, coverage 100%""" + +import unittest +from idlelib import util + + +class UtilTest(unittest.TestCase): + def test_extensions(self): + for extension in {'.pyi', '.py', '.pyw'}: + self.assertIn(extension, util.py_extensions) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_warning.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_warning.py new file mode 100644 index 0000000000000000000000000000000000000000..221068c5885fcbad118283b6c1702a1c55896ec7 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_warning.py @@ -0,0 +1,73 @@ +'''Test warnings replacement in pyshell.py and run.py. + +This file could be expanded to include traceback overrides +(in same two modules). If so, change name. +Revise if output destination changes (http://bugs.python.org/issue18318). +Make sure warnings module is left unaltered (http://bugs.python.org/issue18081). +''' +from idlelib import run +from idlelib import pyshell as shell +import unittest +from test.support import captured_stderr +import warnings + +# Try to capture default showwarning before Idle modules are imported. +showwarning = warnings.showwarning +# But if we run this file within idle, we are in the middle of the run.main loop +# and default showwarnings has already been replaced. +running_in_idle = 'idle' in showwarning.__name__ + +# The following was generated from pyshell.idle_formatwarning +# and checked as matching expectation. +idlemsg = ''' +Warning (from warnings module): + File "test_warning.py", line 99 + Line of code +UserWarning: Test +''' +shellmsg = idlemsg + ">>> " + + +class RunWarnTest(unittest.TestCase): + + @unittest.skipIf(running_in_idle, "Does not work when run within Idle.") + def test_showwarnings(self): + self.assertIs(warnings.showwarning, showwarning) + run.capture_warnings(True) + self.assertIs(warnings.showwarning, run.idle_showwarning_subproc) + run.capture_warnings(False) + self.assertIs(warnings.showwarning, showwarning) + + def test_run_show(self): + with captured_stderr() as f: + run.idle_showwarning_subproc( + 'Test', UserWarning, 'test_warning.py', 99, f, 'Line of code') + # The following uses .splitlines to erase line-ending differences + self.assertEqual(idlemsg.splitlines(), f.getvalue().splitlines()) + + +class ShellWarnTest(unittest.TestCase): + + @unittest.skipIf(running_in_idle, "Does not work when run within Idle.") + def test_showwarnings(self): + self.assertIs(warnings.showwarning, showwarning) + shell.capture_warnings(True) + self.assertIs(warnings.showwarning, shell.idle_showwarning) + shell.capture_warnings(False) + self.assertIs(warnings.showwarning, showwarning) + + def test_idle_formatter(self): + # Will fail if format changed without regenerating idlemsg + s = shell.idle_formatwarning( + 'Test', UserWarning, 'test_warning.py', 99, 'Line of code') + self.assertEqual(idlemsg, s) + + def test_shell_show(self): + with captured_stderr() as f: + shell.idle_showwarning( + 'Test', UserWarning, 'test_warning.py', 99, f, 'Line of code') + self.assertEqual(shellmsg.splitlines(), f.getvalue().splitlines()) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_window.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_window.py new file mode 100644 index 0000000000000000000000000000000000000000..5a2645b9cc27dcee4ceea7e8443dad8e9e0d80c7 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_window.py @@ -0,0 +1,45 @@ +"Test window, coverage 47%." + +from idlelib import window +import unittest +from test.support import requires +from tkinter import Tk + + +class WindowListTest(unittest.TestCase): + + def test_init(self): + wl = window.WindowList() + self.assertEqual(wl.dict, {}) + self.assertEqual(wl.callbacks, []) + + # Further tests need mock Window. + + +class ListedToplevelTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + window.registry = set() + requires('gui') + cls.root = Tk() + cls.root.withdraw() + + @classmethod + def tearDownClass(cls): + window.registry = window.WindowList() + cls.root.update_idletasks() +## for id in cls.root.tk.call('after', 'info'): +## cls.root.after_cancel(id) # Need for EditorWindow. + cls.root.destroy() + del cls.root + + def test_init(self): + + win = window.ListedToplevel(self.root) + self.assertIn(win, window.registry) + self.assertEqual(win.focused_widget, win) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_zoomheight.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_zoomheight.py new file mode 100644 index 0000000000000000000000000000000000000000..aa5bdfb4fbd4c62f97d04669e9e8de667cbce0aa --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_zoomheight.py @@ -0,0 +1,39 @@ +"Test zoomheight, coverage 66%." +# Some code is system dependent. + +from idlelib import zoomheight +import unittest +from test.support import requires +from tkinter import Tk +from idlelib.editor import EditorWindow + + +class Test(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.editwin = EditorWindow(root=cls.root) + + @classmethod + def tearDownClass(cls): + cls.editwin._close() + cls.root.update_idletasks() + for id in cls.root.tk.call('after', 'info'): + cls.root.after_cancel(id) # Need for EditorWindow. + cls.root.destroy() + del cls.root + + def test_init(self): + zoom = zoomheight.ZoomHeight(self.editwin) + self.assertIs(zoom.editwin, self.editwin) + + def test_zoom_height_event(self): + zoom = zoomheight.ZoomHeight(self.editwin) + zoom.zoom_height_event() + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/test_zzdummy.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_zzdummy.py new file mode 100644 index 0000000000000000000000000000000000000000..209d8564da06641f38e352846a24592636186c77 --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/test_zzdummy.py @@ -0,0 +1,152 @@ +"Test zzdummy, coverage 100%." + +from idlelib import zzdummy +import unittest +from test.support import requires +from tkinter import Tk, Text +from unittest import mock +from idlelib import config +from idlelib import editor +from idlelib import format + + +usercfg = zzdummy.idleConf.userCfg +testcfg = { + 'main': config.IdleUserConfParser(''), + 'highlight': config.IdleUserConfParser(''), + 'keys': config.IdleUserConfParser(''), + 'extensions': config.IdleUserConfParser(''), +} +code_sample = """\ + +class C1: + # Class comment. + def __init__(self, a, b): + self.a = a + self.b = b +""" + + +class DummyEditwin: + get_selection_indices = editor.EditorWindow.get_selection_indices + def __init__(self, root, text): + self.root = root + self.top = root + self.text = text + self.fregion = format.FormatRegion(self) + self.text.undo_block_start = mock.Mock() + self.text.undo_block_stop = mock.Mock() + + +class ZZDummyTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + root = cls.root = Tk() + root.withdraw() + text = cls.text = Text(cls.root) + cls.editor = DummyEditwin(root, text) + zzdummy.idleConf.userCfg = testcfg + + @classmethod + def tearDownClass(cls): + zzdummy.idleConf.userCfg = usercfg + del cls.editor, cls.text + cls.root.update_idletasks() + for id in cls.root.tk.call('after', 'info'): + cls.root.after_cancel(id) # Need for EditorWindow. + cls.root.destroy() + del cls.root + + def setUp(self): + text = self.text + text.insert('1.0', code_sample) + text.undo_block_start.reset_mock() + text.undo_block_stop.reset_mock() + zz = self.zz = zzdummy.ZzDummy(self.editor) + zzdummy.ZzDummy.ztext = '# ignore #' + + def tearDown(self): + self.text.delete('1.0', 'end') + del self.zz + + def checklines(self, text, value): + # Verify that there are lines being checked. + end_line = int(float(text.index('end'))) + + # Check each line for the starting text. + actual = [] + for line in range(1, end_line): + txt = text.get(f'{line}.0', f'{line}.end') + actual.append(txt.startswith(value)) + return actual + + def test_init(self): + zz = self.zz + self.assertEqual(zz.editwin, self.editor) + self.assertEqual(zz.text, self.editor.text) + + def test_reload(self): + self.assertEqual(self.zz.ztext, '# ignore #') + testcfg['extensions'].SetOption('ZzDummy', 'z-text', 'spam') + zzdummy.ZzDummy.reload() + self.assertEqual(self.zz.ztext, 'spam') + + def test_z_in_event(self): + eq = self.assertEqual + zz = self.zz + text = zz.text + eq(self.zz.ztext, '# ignore #') + + # No lines have the leading text. + expected = [False, False, False, False, False, False, False] + actual = self.checklines(text, zz.ztext) + eq(expected, actual) + + text.tag_add('sel', '2.0', '4.end') + eq(zz.z_in_event(), 'break') + expected = [False, True, True, True, False, False, False] + actual = self.checklines(text, zz.ztext) + eq(expected, actual) + + text.undo_block_start.assert_called_once() + text.undo_block_stop.assert_called_once() + + def test_z_out_event(self): + eq = self.assertEqual + zz = self.zz + text = zz.text + eq(self.zz.ztext, '# ignore #') + + # Prepend text. + text.tag_add('sel', '2.0', '5.end') + zz.z_in_event() + text.undo_block_start.reset_mock() + text.undo_block_stop.reset_mock() + + # Select a few lines to remove text. + text.tag_remove('sel', '1.0', 'end') + text.tag_add('sel', '3.0', '4.end') + eq(zz.z_out_event(), 'break') + expected = [False, True, False, False, True, False, False] + actual = self.checklines(text, zz.ztext) + eq(expected, actual) + + text.undo_block_start.assert_called_once() + text.undo_block_stop.assert_called_once() + + def test_roundtrip(self): + # Insert and remove to all code should give back original text. + zz = self.zz + text = zz.text + + text.tag_add('sel', '1.0', 'end-1c') + zz.z_in_event() + zz.z_out_event() + + self.assertEqual(text.get('1.0', 'end-1c'), code_sample) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/data/miniconda3/lib/python3.13/idlelib/idle_test/tkinter_testing_utils.py b/data/miniconda3/lib/python3.13/idlelib/idle_test/tkinter_testing_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a89839bbe38add465aa20b89b327a5732d50f9fd --- /dev/null +++ b/data/miniconda3/lib/python3.13/idlelib/idle_test/tkinter_testing_utils.py @@ -0,0 +1,62 @@ +"""Utilities for testing with Tkinter""" +import functools + + +def run_in_tk_mainloop(delay=1): + """Decorator for running a test method with a real Tk mainloop. + + This starts a Tk mainloop before running the test, and stops it + at the end. This is faster and more robust than the common + alternative method of calling .update() and/or .update_idletasks(). + + Test methods using this must be written as generator functions, + using "yield" to allow the mainloop to process events and "after" + callbacks, and then continue the test from that point. + + The delay argument is passed into root.after(...) calls as the number + of ms to wait before passing execution back to the generator function. + + This also assumes that the test class has a .root attribute, + which is a tkinter.Tk object. + + For example (from test_sidebar.py): + + @run_test_with_tk_mainloop() + def test_single_empty_input(self): + self.do_input('\n') + yield + self.assert_sidebar_lines_end_with(['>>>', '>>>']) + """ + def decorator(test_method): + @functools.wraps(test_method) + def new_test_method(self): + test_generator = test_method(self) + root = self.root + # Exceptions raised by self.assert...() need to be raised + # outside of the after() callback in order for the test + # harness to capture them. + exception = None + def after_callback(): + nonlocal exception + try: + next(test_generator) + except StopIteration: + root.quit() + except Exception as exc: + exception = exc + root.quit() + else: + # Schedule the Tk mainloop to call this function again, + # using a robust method of ensuring that it gets a + # chance to process queued events before doing so. + # See: https://stackoverflow.com/q/18499082#comment65004099_38817470 + root.after(delay, root.after_idle, after_callback) + root.after(0, root.after_idle, after_callback) + root.mainloop() + + if exception: + raise exception + + return new_test_method + + return decorator diff --git a/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f6efc0eb5cc84bf4464a6d2b919d0a6b98cb2ea6 Binary files /dev/null and b/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/connection.cpython-313.pyc b/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/connection.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd8205d38f50502298b65f9e49c755a46f4fd946 Binary files /dev/null and b/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/connection.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/context.cpython-313.pyc b/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/context.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a3caa34580b64aae8eb136954452c80362c6e8b Binary files /dev/null and b/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/context.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/forkserver.cpython-313.pyc b/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/forkserver.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71c71d6e9b9e1c3ac351aff32c60b881ec943eb1 Binary files /dev/null and b/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/forkserver.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/heap.cpython-313.pyc b/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/heap.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3602750b9e2aa395fededb4c9c54893d83518f04 Binary files /dev/null and b/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/heap.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/managers.cpython-313.pyc b/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/managers.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c45da91b16a5c1e83015eddd81466d7f4bb60a6 Binary files /dev/null and b/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/managers.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/pool.cpython-313.pyc b/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/pool.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9fe3455e205220d0f02d32f41602a595acc4267a Binary files /dev/null and b/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/pool.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/popen_fork.cpython-313.pyc b/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/popen_fork.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..15dc82d21033cdd5e1c47fcd2f753266cfb26532 Binary files /dev/null and b/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/popen_fork.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/popen_forkserver.cpython-313.pyc b/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/popen_forkserver.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49878eb55b368a751729be3ac2f3a178cef45a65 Binary files /dev/null and b/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/popen_forkserver.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/popen_spawn_posix.cpython-313.pyc b/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/popen_spawn_posix.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..10322907715551c41c56f439feb633c09998a279 Binary files /dev/null and b/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/popen_spawn_posix.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/popen_spawn_win32.cpython-313.pyc b/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/popen_spawn_win32.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bbd2cae93760f333936ea7c38051809f78243915 Binary files /dev/null and b/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/popen_spawn_win32.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/process.cpython-313.pyc b/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/process.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c534cfe63b0a6aa2906e1340ba8c0741c11eece Binary files /dev/null and b/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/process.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/queues.cpython-313.pyc b/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/queues.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0af92ff8d4478939bb27cbd480a6ca6247343755 Binary files /dev/null and b/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/queues.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/reduction.cpython-313.pyc b/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/reduction.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..41318112ca8f249bdd15c482456506f86303c743 Binary files /dev/null and b/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/reduction.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/resource_sharer.cpython-313.pyc b/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/resource_sharer.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac2c89a5a97e4a525fc1c0a4a86e5398efdc7327 Binary files /dev/null and b/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/resource_sharer.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/resource_tracker.cpython-313.pyc b/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/resource_tracker.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ddb70a8c945a67c69a20fae7a2c2d986a3abbc66 Binary files /dev/null and b/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/resource_tracker.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/shared_memory.cpython-313.pyc b/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/shared_memory.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c7f3759f92d1a94cb78c5619250514dfac73601 Binary files /dev/null and b/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/shared_memory.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/sharedctypes.cpython-313.pyc b/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/sharedctypes.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..08597935ab22cc2c593d7cb1efe9c2f9352a66fe Binary files /dev/null and b/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/sharedctypes.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/spawn.cpython-313.pyc b/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/spawn.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..979b683ced97c5fff85df64890bd0126eafb6912 Binary files /dev/null and b/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/spawn.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/synchronize.cpython-313.pyc b/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/synchronize.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a79324f515cbc7c13eec99b015dd31cf5b22dbe2 Binary files /dev/null and b/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/synchronize.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/util.cpython-313.pyc b/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/util.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..14cdd98c9be7aaa1880ccb32d9c8bd4e3d06bba5 Binary files /dev/null and b/data/miniconda3/lib/python3.13/multiprocessing/__pycache__/util.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/multiprocessing/dummy/__init__.py b/data/miniconda3/lib/python3.13/multiprocessing/dummy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6a1468609e347b3a0b9281e5c9e6ec311fcb37e5 --- /dev/null +++ b/data/miniconda3/lib/python3.13/multiprocessing/dummy/__init__.py @@ -0,0 +1,126 @@ +# +# Support for the API of the multiprocessing package using threads +# +# multiprocessing/dummy/__init__.py +# +# Copyright (c) 2006-2008, R Oudkerk +# Licensed to PSF under a Contributor Agreement. +# + +__all__ = [ + 'Process', 'current_process', 'active_children', 'freeze_support', + 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Condition', + 'Event', 'Barrier', 'Queue', 'Manager', 'Pipe', 'Pool', 'JoinableQueue' + ] + +# +# Imports +# + +import threading +import sys +import weakref +import array + +from .connection import Pipe +from threading import Lock, RLock, Semaphore, BoundedSemaphore +from threading import Event, Condition, Barrier +from queue import Queue + +# +# +# + +class DummyProcess(threading.Thread): + + def __init__(self, group=None, target=None, name=None, args=(), kwargs={}): + threading.Thread.__init__(self, group, target, name, args, kwargs) + self._pid = None + self._children = weakref.WeakKeyDictionary() + self._start_called = False + self._parent = current_process() + + def start(self): + if self._parent is not current_process(): + raise RuntimeError( + "Parent is {0!r} but current_process is {1!r}".format( + self._parent, current_process())) + self._start_called = True + if hasattr(self._parent, '_children'): + self._parent._children[self] = None + threading.Thread.start(self) + + @property + def exitcode(self): + if self._start_called and not self.is_alive(): + return 0 + else: + return None + +# +# +# + +Process = DummyProcess +current_process = threading.current_thread +current_process()._children = weakref.WeakKeyDictionary() + +def active_children(): + children = current_process()._children + for p in list(children): + if not p.is_alive(): + children.pop(p, None) + return list(children) + +def freeze_support(): + pass + +# +# +# + +class Namespace(object): + def __init__(self, /, **kwds): + self.__dict__.update(kwds) + def __repr__(self): + items = list(self.__dict__.items()) + temp = [] + for name, value in items: + if not name.startswith('_'): + temp.append('%s=%r' % (name, value)) + temp.sort() + return '%s(%s)' % (self.__class__.__name__, ', '.join(temp)) + +dict = dict +list = list + +def Array(typecode, sequence, lock=True): + return array.array(typecode, sequence) + +class Value(object): + def __init__(self, typecode, value, lock=True): + self._typecode = typecode + self._value = value + + @property + def value(self): + return self._value + + @value.setter + def value(self, value): + self._value = value + + def __repr__(self): + return '<%s(%r, %r)>'%(type(self).__name__,self._typecode,self._value) + +def Manager(): + return sys.modules[__name__] + +def shutdown(): + pass + +def Pool(processes=None, initializer=None, initargs=()): + from ..pool import ThreadPool + return ThreadPool(processes, initializer, initargs) + +JoinableQueue = Queue diff --git a/data/miniconda3/lib/python3.13/multiprocessing/dummy/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/multiprocessing/dummy/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aafc2dd0569b256c23b1c71811cdd997697e643f Binary files /dev/null and b/data/miniconda3/lib/python3.13/multiprocessing/dummy/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/multiprocessing/dummy/__pycache__/connection.cpython-313.pyc b/data/miniconda3/lib/python3.13/multiprocessing/dummy/__pycache__/connection.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ace69f7988e76f8a2ca1e19bb5bb84cc6bf32a0 Binary files /dev/null and b/data/miniconda3/lib/python3.13/multiprocessing/dummy/__pycache__/connection.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/multiprocessing/dummy/connection.py b/data/miniconda3/lib/python3.13/multiprocessing/dummy/connection.py new file mode 100644 index 0000000000000000000000000000000000000000..f0ce320fcf514083f3a6477e87abf40e9719285a --- /dev/null +++ b/data/miniconda3/lib/python3.13/multiprocessing/dummy/connection.py @@ -0,0 +1,75 @@ +# +# Analogue of `multiprocessing.connection` which uses queues instead of sockets +# +# multiprocessing/dummy/connection.py +# +# Copyright (c) 2006-2008, R Oudkerk +# Licensed to PSF under a Contributor Agreement. +# + +__all__ = [ 'Client', 'Listener', 'Pipe' ] + +from queue import Queue + + +families = [None] + + +class Listener(object): + + def __init__(self, address=None, family=None, backlog=1): + self._backlog_queue = Queue(backlog) + + def accept(self): + return Connection(*self._backlog_queue.get()) + + def close(self): + self._backlog_queue = None + + @property + def address(self): + return self._backlog_queue + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, exc_tb): + self.close() + + +def Client(address): + _in, _out = Queue(), Queue() + address.put((_out, _in)) + return Connection(_in, _out) + + +def Pipe(duplex=True): + a, b = Queue(), Queue() + return Connection(a, b), Connection(b, a) + + +class Connection(object): + + def __init__(self, _in, _out): + self._out = _out + self._in = _in + self.send = self.send_bytes = _out.put + self.recv = self.recv_bytes = _in.get + + def poll(self, timeout=0.0): + if self._in.qsize() > 0: + return True + if timeout <= 0.0: + return False + with self._in.not_empty: + self._in.not_empty.wait(timeout) + return self._in.qsize() > 0 + + def close(self): + pass + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, exc_tb): + self.close() diff --git a/data/miniconda3/lib/python3.13/pathlib/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/pathlib/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b58ce2ce6d012fea229e2e388b23ed7f52c0729c Binary files /dev/null and b/data/miniconda3/lib/python3.13/pathlib/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/pathlib/__pycache__/_abc.cpython-313.pyc b/data/miniconda3/lib/python3.13/pathlib/__pycache__/_abc.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f669bbb061d2719520b101d2386482023a26aa7f Binary files /dev/null and b/data/miniconda3/lib/python3.13/pathlib/__pycache__/_abc.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/pathlib/__pycache__/_local.cpython-313.pyc b/data/miniconda3/lib/python3.13/pathlib/__pycache__/_local.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d67799d35300d6c4e39e14156e1d082c703597c Binary files /dev/null and b/data/miniconda3/lib/python3.13/pathlib/__pycache__/_local.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/__pycache__/example.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/__pycache__/example.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f6a5a0152a0b6b3cde0d55cbce19ae760f02db1a Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/__pycache__/example.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/__pycache__/jsonpatch.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/__pycache__/jsonpatch.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4512096c961997df2159510081bf91f36f60ae59 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/__pycache__/jsonpatch.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/__pycache__/jsonpointer.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/__pycache__/jsonpointer.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c08e4a00aff6c7ff4d9122da571700676205be9 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/__pycache__/jsonpointer.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/__pycache__/pylab.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/__pycache__/pylab.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..39fa13d9de11bafa8f6ec398186ab3a961c1458a Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/__pycache__/pylab.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/__pycache__/six.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/__pycache__/six.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd3986b5cdbcac3315080baf0b597c69c2a724c4 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/__pycache__/six.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/__pycache__/socks.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/__pycache__/socks.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4366a40c38f68cf5889af0ca323f30d6ec8c7204 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/__pycache__/socks.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/__pycache__/sockshandler.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/__pycache__/sockshandler.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..120a0791f54440dab7e2fe7d7cb270fc08296ff5 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/__pycache__/sockshandler.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/__pycache__/test_pycosat.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/__pycache__/test_pycosat.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..022f32078b0437da26b50e8b45e17b4ffc35f3b4 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/__pycache__/test_pycosat.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage-0.7.5.dist-info/INSTALLER b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage-0.7.5.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..f79e4cb9aaf0b2d9e8ba78861e2071317b2384b3 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage-0.7.5.dist-info/INSTALLER @@ -0,0 +1 @@ +conda \ No newline at end of file diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage-0.7.5.dist-info/LICENSE b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage-0.7.5.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b3ab6e6ca30ede6826cc0743c928ba985eced7b1 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage-0.7.5.dist-info/LICENSE @@ -0,0 +1,28 @@ +BSD 3-Clause License + +Copyright (c) 2023, Anaconda-Platform + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage-0.7.5.dist-info/METADATA b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage-0.7.5.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..95e4ff5335b1c5fd305324354f64f8fb0c3e6508 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage-0.7.5.dist-info/METADATA @@ -0,0 +1,19 @@ +Metadata-Version: 2.1 +Name: anaconda-anon-usage +Version: 0.7.5 +Summary: basic anonymous telemetry for conda +Home-page: https://github.com/Anaconda-Platform/anaconda-anon-usage +Author: Michael C. Grant +Author-email: mgrant@anaconda.com +License: BSD +Keywords: anaconda-anon-usage +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +License-File: LICENSE +Requires-Dist: conda + diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage-0.7.5.dist-info/RECORD b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage-0.7.5.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..f34f06736c330127db2c630c9d46269343d084d0 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage-0.7.5.dist-info/RECORD @@ -0,0 +1,25 @@ +anaconda_anon_usage-0.7.5.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +anaconda_anon_usage-0.7.5.dist-info/LICENSE,sha256=7m8sKzw2HzaMUsdX01Gt8dgptqsbPnjf_WUiFhKAZzY,1504 +anaconda_anon_usage-0.7.5.dist-info/METADATA,sha256=Fm1AIE6-1mhlragvUEykxOoh_QSGFlu6F-H2PdQlz4E,673 +anaconda_anon_usage-0.7.5.dist-info/RECORD,, +anaconda_anon_usage-0.7.5.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +anaconda_anon_usage-0.7.5.dist-info/WHEEL,sha256=AHX6tWk3qWuce7vKLrj7lnulVHEdWoltgauo8bgCXgU,109 +anaconda_anon_usage-0.7.5.dist-info/direct_url.json,sha256=lK5WXSzx6D73wxae8AsRl-fg6LsahNjCW8cfKOXd0Eo,98 +anaconda_anon_usage-0.7.5.dist-info/entry_points.txt,sha256=BounSqBUl0KtMq-iqr4g7_IIyhlo5_PAiwnY2KAiNmU,64 +anaconda_anon_usage-0.7.5.dist-info/top_level.txt,sha256=8L-7p0_HHpqMNVCZl2mDgrLfssfZrYcCZpNiWguXpPM,20 +anaconda_anon_usage/__init__.py,sha256=t9KZdp_DIvv91kyAlbqfXkrky_63qicYujvE-nd8xlM,93 +anaconda_anon_usage/__pycache__/__init__.cpython-38.pyc,, +anaconda_anon_usage/__pycache__/_version.cpython-38.pyc,, +anaconda_anon_usage/__pycache__/heartbeat.cpython-38.pyc,, +anaconda_anon_usage/__pycache__/install.cpython-38.pyc,, +anaconda_anon_usage/__pycache__/patch.cpython-38.pyc,, +anaconda_anon_usage/__pycache__/plugin.cpython-38.pyc,, +anaconda_anon_usage/__pycache__/tokens.cpython-38.pyc,, +anaconda_anon_usage/__pycache__/utils.cpython-38.pyc,, +anaconda_anon_usage/_version.py,sha256=C5h_EAtMeInaw1_O31kdDts_zJga4FdLU6UNce0aCAQ,497 +anaconda_anon_usage/heartbeat.py,sha256=-Q8FA3fvBJBalpvphBlWlLTCM3sUW8NdXYSteAqfUZQ,6160 +anaconda_anon_usage/install.py,sha256=4G-fpa1INLRI1x9CQOmifNONirzxw11UFYskDlVFlsM,6299 +anaconda_anon_usage/patch.py,sha256=tGmqIhR0g4ugEmyPwRnKMhS-HKv-VdRSItfJFEOF5d8,5718 +anaconda_anon_usage/plugin.py,sha256=_I3CT51RSkvuxiaRqozkFP0_pQ2S_D4skGYWCkT9Jjo,629 +anaconda_anon_usage/tokens.py,sha256=WXxN-pfB9cmy91KUrXJ9kctBd0eX6ipuYXc56yVAKhA,10522 +anaconda_anon_usage/utils.py,sha256=vJdSoE---EBQQ0esS7nK1j1-M9O8oqAvIMWqvuHK1SI,10245 diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage-0.7.5.dist-info/REQUESTED b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage-0.7.5.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage-0.7.5.dist-info/WHEEL b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage-0.7.5.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..f57cfecfdc58e780f923025a37560f3f039480a2 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage-0.7.5.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: setuptools (75.1.0) +Root-Is-Purelib: true +Tag: py2-none-any +Tag: py3-none-any + diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage-0.7.5.dist-info/direct_url.json b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage-0.7.5.dist-info/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..9aadf4dbcd9f6e451ba29ace275e80289e0a8dee --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage-0.7.5.dist-info/direct_url.json @@ -0,0 +1 @@ +{"dir_info": {}, "url": "file:///opt/miniconda3/conda-bld/anaconda-anon-usage_1764636648062/work"} \ No newline at end of file diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage-0.7.5.dist-info/entry_points.txt b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage-0.7.5.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..009ffb75501d91b0d6f895e97d4f612a3aa4e4ea --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage-0.7.5.dist-info/entry_points.txt @@ -0,0 +1,2 @@ +[conda] +anaconda-anon-usage-plugin = anaconda_anon_usage.plugin diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage-0.7.5.dist-info/top_level.txt b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage-0.7.5.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..41316b7fd830f98fd45d7a1ec07afb88aee8ae00 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage-0.7.5.dist-info/top_level.txt @@ -0,0 +1 @@ +anaconda_anon_usage diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/__init__.py b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..80edaf050d4b41e4c2ccd37127ac865f556ce875 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/__init__.py @@ -0,0 +1,4 @@ +from ._version import get_versions + +__version__ = get_versions()["version"] +del get_versions diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/_version.py b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..0246b061ac20e31aa6d91f2d0b853b40d1d7ce9d --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/_version.py @@ -0,0 +1,21 @@ + +# This file was generated by 'versioneer.py' (0.29) from +# revision-control system data, or from the parent directory name of an +# unpacked source archive. Distribution tarballs contain a pre-generated copy +# of this file. + +import json + +version_json = ''' +{ + "date": "2025-11-27T16:08:14-0600", + "dirty": false, + "error": null, + "full-revisionid": "744e7d68d7d500d0be8727242eb436de32f9bdae", + "version": "0.7.5" +} +''' # END VERSION_JSON + + +def get_versions(): + return json.loads(version_json) diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/heartbeat.py b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/heartbeat.py new file mode 100644 index 0000000000000000000000000000000000000000..5d8a0b7f0d02b0acce1f7918bffc60720e08064f --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/heartbeat.py @@ -0,0 +1,193 @@ +""" +This module implements a heartbeat function that sends a simple +HEAD request to an upstream repository. It can be configured to +trigger upon environment activation, but it is off by default. +The intended use case is for organizations to enable it through +system configuration for better usage tracking. +""" + +import argparse +import os +import sys +import time +from threading import Thread +from urllib.parse import urljoin + +from conda.base.context import Context, context, locate_prefix_by_name +from conda.gateways.connection.session import get_session +from conda.models.channel import Channel +from requests.exceptions import RequestException +from urllib3.exceptions import HTTPError + +from . import utils + +VERBOSE = False +STANDALONE = False + +CLD_REPO = "https://repo.anaconda.cloud/" +ORG_REPO = "https://conda.anaconda.org/" +COM_REPO = "https://repo.anaconda.com/pkgs/" +REPOS = (CLD_REPO, COM_REPO, ORG_REPO) +HEARTBEAT_PATH = "noarch/activate-0.0.0-0.conda" + +# How long to attempt the connection. When a connection to our +# repository is blocked or slow, a long timeout would lead to +# a slow activation and a poor user experience. This is a total +# timeout value, inclusive of all retries. +TIMEOUT = 0.75 # seconds +ATTEMPTS = 3 + + +def _print(msg, *args, error=False): + global VERBOSE + global STANDALONE + if not (VERBOSE or utils.DEBUG or error): + return + # It is very important that these messages are printed to stderr + # when called from within the activate script. Otherwise they + # will insert themselves into the activation command set + ofile = sys.stdout if STANDALONE and not (error or utils.DEBUG) else sys.stderr + print(msg % args, file=ofile) + + +def _ping(session, url, timeout): + try: + # A short timeout is necessary here so that the activation + # is not unduly delayed by a blocked internet connection + start_time = time.perf_counter() + response = session.head(url, proxies=session.proxies, timeout=timeout) + delta = time.perf_counter() - start_time + _print( + "Success after %.3fs; code (expect 404): %d", delta, response.status_code + ) + except Exception as exc: + delta = time.perf_counter() - start_time + + # Check if this is an expected network-related exception + # Requests exceptions cover most cases, urllib3 for lower-level errors, + # and standard library for fallback + if isinstance(exc, (RequestException, HTTPError, OSError, TimeoutError)): + _print("Heartbeat failed after %.3fs: %s", delta, type(exc).__name__) + else: + # Truly unexpected error - log even in non-debug mode + _print("Unexpected heartbeat error after %.3fs: %s", delta, exc, error=True) + + +def attempt_heartbeat(prefix=None, dry_run=False, channel=None, path=None): + if not hasattr(context, "_aau_initialized"): + from . import patch + + patch.main() + + if channel and "/" in channel: + url = channel + else: + # Silences the defaults deprecation error + if not context._channels: + context._channels = ["defaults"] + urls = [u for c in context.channels for u in Channel(c).urls()] + urls.extend(u.rstrip("/") for u in context.channel_alias.urls()) + for base in REPOS: + if any(u.startswith(base) for u in urls): + break + else: + _print("No valid heartbeat channel") + return + url = urljoin(base, channel or "main") + "/" + if path is None: + path = HEARTBEAT_PATH + url = urljoin(url, path) + + _print("Heartbeat url: %s", url) + if prefix: + Context.checked_prefix = prefix + _print("Prefix: %s", prefix) + _print("User agent: %s", context.user_agent) + + if dry_run: + _print("Dry run selected, not sending heartbeat.") + return + + # Build and configure the session object + timeout = TIMEOUT / ATTEMPTS + context.remote_max_retries = ATTEMPTS - 1 + # No backoff between attempts + context.remote_backoff_factor = 0 + session = get_session(url) + + # Run in the background so we can proceed with the rest of the + # activation tasks while the request fires. The process will wait + # to terminate until the thread is complete. + t = Thread(target=_ping, args=(session, url, timeout), daemon=False) + t.start() + if STANDALONE: + t.join() + + +def main(): + global VERBOSE + global STANDALONE + STANDALONE = True + VERBOSE = "--quiet" not in sys.argv and "-q" not in sys.argv + + line = "-----------------------------" + _print(line) + _print("anaconda-anon-usage heartbeat") + _print(line) + + def environment_path(s): + assert os.path.isdir(s) + return s + + def environment_name(s): + return locate_prefix_by_name(s) + + p = argparse.ArgumentParser() + g = p.add_mutually_exclusive_group() + g.add_argument( + "-n", + "--name", + type=environment_name, + default=None, + help="Environment name; defaults to the current environment.", + ) + g.add_argument( + "-p", + "--prefix", + type=environment_path, + default=None, + help="Environment prefix; defaults to the current environment.", + ) + p.add_argument( + "-d", + "--dry-run", + action="store_true", + help="Do not send the heartbeat; just show the steps.", + ) + p.add_argument("-q", "--quiet", action="store_true", help="Suppress console logs.") + p.add_argument( + "--channel", + default=None, + help="(advanced) The full URL to a custom repository channel. By default, an " + "Anaconda-hosted channel listed in the user's channel configuration is used.", + ) + p.add_argument( + "--path", + default=None, + help="(advanced) A custom path to append to the channel URL.", + ) + + try: + args = p.parse_args() + attempt_heartbeat( + prefix=args.prefix or args.name, + dry_run=args.dry_run, + channel=args.channel, + path=args.path, + ) + finally: + _print(line) + + +if __name__ == "__main__": + main() diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/patch.py b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/patch.py new file mode 100644 index 0000000000000000000000000000000000000000..9f88053dcd1847f7570e56abc065b2a1d4641e3b --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/patch.py @@ -0,0 +1,179 @@ +# This module implements the changes to conda's context class +# needed to deploy the additional anonymous user data. It pulls +# the token management functions themselves from the api module. + +import os +import re +import sys + +from conda.auxlib.decorators import memoizedproperty +from conda.base.context import ( + Context, + ParameterLoader, + PrimitiveParameter, + context, + locate_prefix_by_name, +) + +from .tokens import token_string +from .utils import _debug + + +def _new_user_agent(ctx): + result = ctx._old_user_agent + prefix = ( + getattr(Context, "checked_prefix", None) or context.target_prefix or sys.prefix + ) + try: + token = token_string(prefix, context.anaconda_anon_usage) + if token: + result += " " + token + except Exception: # pragma: nocover + pass + return result + + +def _new_check_prefix(prefix, json=False): + Context.checked_prefix = prefix + Context._old_check_prefix(prefix, json) + + +def _new_get_main_info_str(info_dict): + ua = info_dict["user_agent"] + if " aau/" in ua: + ua_redact = re.sub(r" ([a-z]/)([^ ]+)", r" \1.", ua) + info_dict["user_agent"] = ua_redact + return Context._old_get_main_info_str(info_dict) + + +def _new_activate(self): + hb = context.anaconda_heartbeat + if not hb: + return self._old_activate() + try: + from .heartbeat import attempt_heartbeat + + channel, path = None, None + env = self.env_name_or_prefix + if env and os.sep not in env: + env = locate_prefix_by_name(env) + if isinstance(hb, str): + channel, path = hb, "" + attempt_heartbeat(env or sys.prefix, channel=channel, path=path) + except Exception as exc: + _debug("Failed to attempt heartbeat: %s", exc, error=True) + finally: + return self._old_activate() + + +def _patch_check_prefix(): + if hasattr(Context, "_old_check_prefix"): + return + _debug("Applying anaconda_anon_usage cli.install patch") + + from conda.cli import install as cli_install + + Context._old_check_prefix = cli_install.check_prefix + cli_install.check_prefix = _new_check_prefix + context._aau_initialized = True + + +def _patch_conda_info(): + if hasattr(Context, "_old_get_main_info_str"): + return + _debug("Applying anaconda_anon_usage conda info patch") + + from conda.cli import main_info + + if hasattr(main_info, "get_main_info_display"): + Context._old_get_main_info_str = main_info.get_main_info_display + main_info.get_main_info_display = _new_get_main_info_str + elif hasattr(main_info, "get_main_info_str"): + Context._old_get_main_info_str = main_info.get_main_info_str + main_info.get_main_info_str = _new_get_main_info_str + else: + _debug("Cannot apply anaconda_anon_usage conda info patch") + + +def _patch_activate(): + _debug("Applying anaconda_anon_usage activate patch") + from conda import activate + + if hasattr(activate, "_Activator"): + _Activator = activate._Activator + if hasattr(_Activator, "activate"): + _Activator._old_activate = _Activator.activate + _Activator.activate = _new_activate + return + _debug("Cannot apply anaconda_anon_usage activate patch") + + +def _heartbeat_validate(value): + if isinstance(value, str): + from urllib import parse + + parts = parse.urlsplit(value) + if not (parts.scheme and parts.netloc): + return "Must be a booelan or a full URL" + + +def main(plugin=False, command=None): + if getattr(context, "_aau_initialized", None) is not None: + _debug("anaconda_anon_usage already active") + return False + _debug("Applying anaconda_anon_usage context patch") + + # conda.base.context.Context.user_agent + # Adds the ident tokens to the user agent string + Context._old_user_agent = Context.user_agent + # Using a different name ensures that this is stored + # in the cache in a different place than the original + Context.user_agent = memoizedproperty(_new_user_agent) + + # conda.base.context.Context.anaconda_anon_usage + # Adds the anaconda_anon_usage toggle, defaulting to true + _param = ParameterLoader(PrimitiveParameter(True)) + Context.anaconda_anon_usage = _param + Context.parameter_names += (_param._set_name("anaconda_anon_usage"),) + + # conda.base.context.Context + # Adds the anaconda_heartbeat toggle, defaulting to false + _param = ParameterLoader( + PrimitiveParameter( + False, element_type=(str, bool), validation=_heartbeat_validate + ) + ) + Context.anaconda_heartbeat = _param + Context.parameter_names += (_param._set_name("anaconda_heartbeat"),) + + # conda.base.context.checked_prefix + # Saves the prefix used in a conda install command + Context.checked_prefix = None + + # conda.base.context._aau_initialized + # This helps us determine if the patching is comlpete + context._aau_initialized = False + + if plugin: + # The pre-command plugin avoids the circular import + # of conda.cli.install, so we can apply the patch now + _patch_conda_info() + if command == "activate": + _patch_activate() + if command == "info": + _patch_check_prefix() + else: + # We need to delay further. Schedule the patch for the + # next time context.__init__ is called. + _debug("Deferring anaconda_anon_usage cli.install patch") + _old__init__ = context.__init__ + + def _new_init(*args, **kwargs): + _patch_conda_info() + _patch_check_prefix() + context.__init__ = _old__init__ + _old__init__(*args, **kwargs) + + context.__init__ = _new_init + + return True diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/plugin.py b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/plugin.py new file mode 100644 index 0000000000000000000000000000000000000000..6a172ce118bc14f1d19d914e6303e0768e7e6bf5 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/plugin.py @@ -0,0 +1,26 @@ +from conda import plugins + + +def pre_command_patcher(command): + try: + from . import patch # noqa + + patch.main(plugin=True, command=command) + except Exception as exc: # pragma: nocover + print("Error loading anaconda-anon-usage:", exc) + + +class AlwaysContains: + def __contains__(self, item): + return True + + +@plugins.hookimpl +def conda_pre_commands(): + yield plugins.CondaPreCommand( + name="anaconda-anon-usage", + action=pre_command_patcher, + # This ensures the plugin is run no matter what + # conda command is being called + run_for=AlwaysContains(), + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/tokens.py b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/tokens.py new file mode 100644 index 0000000000000000000000000000000000000000..e831c0afbcfa798ef238fd5270bc320e24a166a4 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/tokens.py @@ -0,0 +1,323 @@ +# This module provides functions for reading and writing the +# anonymous token set. It has been designed to rely only on the +# Python standard library. In particular, hard dependencies on +# conda must be avoided so that this package can be used in +# child environments. + +import base64 +import datetime as dt +import json +import re +import sys +import uuid +from collections import namedtuple +from os import environ +from os.path import expanduser, isdir, isfile, join + +from . import __version__ +from .utils import _debug, _random_token, _read_file, _saved_token, cached + +Tokens = namedtuple( + "Tokens", + ( + "version", + "client", + "session", + "environment", + "anaconda_cloud", + "installer", + "organization", + "machine", + ), +) +CONFIG_DIR = expanduser("~/.conda") +ANACONDA_DIR = expanduser("~/.anaconda") +ORG_TOKEN_NAME = "org_token" +INSTALLER_TOKEN_NAME = "installer_token" +MACHINE_TOKEN_NAME = "machine_token" + +# System tokens may consist of only letters, numbers, +# underscores, and dashes, with no more than 36 characters. +VALID_TOKEN_RE = r"^(?:[A-Za-z0-9]|_|-){1,36}$" + + +@cached +def version_token(): + """ + Returns the version token, which is just the + version string itself. + """ + return __version__ + + +@cached +def _search_path(): + """ + Returns the search path for system tokens. + """ + try: + # Do not import SEARCH_PATH directly since we need to + # temporarily patch it for testing + from conda.base import constants as c_constants + + search_path = c_constants.SEARCH_PATH + except ImportError: + # Because this module was designed to be used even in + # environments that do not include conda, we need a + # fallback in case conda.base.constants.SEARCH_PATH + # is not available. This is a pruned version of the + # constructed value of this path as of 2024-12-13. + _debug("conda not installed in this environment") + if sys.platform == "win32": + search_path = ("C:/ProgramData/conda/.condarc",) + else: + search_path = ("/etc/conda/.condarc", "/var/lib/conda/.condarc") + search_path += ( + "$XDG_CONFIG_HOME/conda/.condarc", + "~/.config/conda/.condarc", + "~/.conda/.condarc", + "~/.condarc", + "$CONDARC", + ) + result = [] + home = expanduser("~") + for path in search_path: + # Only consider directories where + # .condarc could also be found + if not path.endswith("/.condarc"): + continue + parts = path.split("/")[:-1] + if parts[0] == "~": + parts[0] = home + elif parts[0].startswith("$"): + parts[0] = environ.get(parts[0][1:]) + if not parts[0]: + continue + path = "/".join(parts) + if isdir(path) and path != home: + result.append(path) + return result + + +def _system_tokens(fname, what): + """ + Returns an organization or machine token installed somewhere + in the conda path. Unlike most tokens, these will typically + be installed by system administrators, often by mobile device + management software. There can also be multiple tokens present + along the path, in which case we combine them + """ + tokens = [] + env_name = "ANACONDA_ANON_USAGE_" + fname.upper() + t_token = environ.get(env_name) + if t_token: + _debug("Found %s token in environment: %s", what, t_token) + tokens.append(t_token) + for path in _search_path(): + for pfx in ("", "."): + fpath = join(path, pfx + fname) + if isfile(fpath): + t_token = _read_file(fpath, what + " token", single_line=True) + tokens.append(t_token) + # Deduplicate while preserving order + tokens = list(dict.fromkeys(t for t in tokens if t)) + if not tokens: + _debug("No %s tokens found", what) + # Make sure the tokens we omit have only valid characters, so any + # server-side token parsing is not frustrated. + valid = [t for t in tokens if re.match(VALID_TOKEN_RE, t)] + if len(valid) < len(tokens): + invalid = ", ".join(t for t in tokens if t not in valid) + _debug("One or more invalid %s tokens discarded: %s", what, invalid) + return valid + + +@cached +def installer_tokens(): + """ + Returns the list of installer tokens. + """ + return _system_tokens(INSTALLER_TOKEN_NAME, "installer") + + +@cached +def organization_tokens(): + """ + Returns the list of organization tokens. + """ + return _system_tokens(ORG_TOKEN_NAME, "organization") + + +@cached +def machine_tokens(): + """ + Returns the list of machine tokens. + """ + return _system_tokens(MACHINE_TOKEN_NAME, "machine") + + +@cached +def client_token(): + """ + Returns the client token. If a token has not yet + been generated, an attempt is made to do so. If + that fails, an empty string is returned. + """ + fpath = join(CONFIG_DIR, "aau_token") + return _saved_token(fpath, "client", node_tie=True) + + +@cached +def session_token(): + """ + Returns the session token, generated randomly for each + execution of the process. + """ + return _random_token("session") + + +@cached +def environment_token(prefix=None): + """ + Returns the environment token for the given prefix, or + sys.prefix if one is not supplied. If a token has not + yet been generated, an attempt is made to do so. If that + fails, an empty string is returned. + """ + if prefix is None: + prefix = sys.prefix + fpath = join(prefix, "etc", "aau_token") + return _saved_token(fpath, "environment", prefix) + + +def _jwt_to_token(s): + """Unpacks an Anaconda auth token and returns the encoded user ID for + potential inclusion in the user agent, along with its expiration. + + The Anaconda API key takes the form of a standard OAuth2 access token, + with the additional requirement that the "sub" field is a UUID string. + This code perorms a basic set of integrity checks to confirm that this + is the case. If the checks pass, the function returns an encoded form + of "sub" as well as the "exp" value to enable sorting by expiration. + If the checks fail, the function returns (None, 0). + + The signature is not fully validated as part of the check; only that it + is a base64-encoded value. Validation is left to anaconda-auth. + + Returns: + token: the token if valid; None otherwise + exp: the expiration time + """ + if not s: + return + try: + # The JWT should have three parts separated by periods + parts = s.split(".") + assert len(parts) == 3 and all(parts), "3 parts expected" + # Each part should be base64 encoded + parts = list(map(lambda x: base64.urlsafe_b64decode(x + "==="), parts)) + # The header and payload should be json dictionaries + parts = list(map(json.loads, parts[:2])) + assert isinstance(parts[0], dict), "Invalid header" + assert parts[0].get("typ") == "JWT", "Invalid header" + assert isinstance(parts[1], dict), "Invalid payload" + # The payload should have a positive integer expiration + exp = parts[1].get("exp") + assert isinstance(exp, int) and exp > 0, "Invalid expiration" + now = dt.datetime.now(tz=dt.timezone.utc).timestamp() + if exp < now: + _debug("API key expired %ds ago", int(now - exp)) + return + # The subscriber should be a non-empty UUID string + sub = parts[1].get("sub") + assert sub, "Invalid subscriber" + # This is an Anaconda requirement, not a JWT requirement + sub = uuid.UUID(sub).bytes + token = base64.urlsafe_b64encode(sub).decode("ascii").strip("=") + return token + except Exception as exc: + _debug("Unexpected %s parsing API key: %s", type(exc), exc) + + +@cached +def anaconda_auth_token(): + """Returns the base64-encoded uid corresponding to the logged + in Anaconda Cloud user, if one is present. + Returns: + str: Base64-encoded token, or None if no valid token found. + """ + try: + from anaconda_auth.token import TokenInfo, TokenNotFoundError + + _debug("Module anaconda_auth loaded") + tinfo = TokenInfo.load(domain="anaconda.com") + if tinfo.api_key: + token = _jwt_to_token(tinfo.api_key) + _debug("Retrieved Anaconda auth token: %s", token) + return token + except ImportError: + _debug("Module anaconda_auth not available") + except TokenNotFoundError: + pass + except Exception as exc: + _debug("Unexpected error retrieving token using anaconda_auth: %s", exc) + _debug("No Anaconda API token found") + + +@cached +def all_tokens(prefix=None): + """ + Returns the token set, in the form of a Tokens namedtuple. + Fields: version, client, session, environment + """ + return Tokens( + version_token(), + client_token(), + session_token(), + environment_token(prefix), + anaconda_auth_token(), + installer_tokens(), + organization_tokens(), + machine_tokens(), + ) + + +@cached +def token_string(prefix=None, enabled=True): + """ + Returns the token set, formatted into the string that is + appended to the conda user agent. + """ + parts = ["aau/" + __version__] + if enabled: + values = all_tokens(prefix) + if values.client: + parts.append("c/" + values.client) + if values.session: + parts.append("s/" + values.session) + if values.environment: + parts.append("e/" + values.environment) + if values.anaconda_cloud: + parts.append("a/" + values.anaconda_cloud) + # System tokens can potentially be multi-valued, and this + # is rendered in the user agent string as multiple instances + # separated by spaces. This was chosen to facilitate easier + # filtering & search + if values.installer: + parts.extend("i/" + t for t in values.installer) + if values.organization: + parts.extend("o/" + t for t in values.organization) + if values.machine: + parts.extend("m/" + t for t in values.machine) + else: + _debug("anaconda_anon_usage disabled by config") + result = " ".join(parts) + _debug("Full aau token string: %s", result) + return result + + +if __name__ == "__main__": + if "--random" in sys.argv: + print(_random_token()) + else: + print(token_string()) diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/utils.py b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2fb1bd8cd7ce23768f8a46d68301e7e9a2856f7e --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/utils.py @@ -0,0 +1,278 @@ +import atexit +import base64 +import errno +import os +import sys +import uuid +from os.path import dirname, isdir, isfile +from threading import RLock +from typing import List, Optional + +DPREFIX = os.environ.get("ANACONDA_ANON_USAGE_DEBUG_PREFIX") or "" +DEBUG = bool(os.environ.get("ANACONDA_ANON_USAGE_DEBUG")) or DPREFIX + +# When creating a new environment, the environment token will be +# created in advance of the action creation of the standard conda +# directory structure. If we write the token to its location and +# then the creation is interrupted, the directory will now be in +# a state where conda is unwilling to install into it, thinking +# it is a non-empty non-conda directory. +DEFERRED = [] + +# While lru_cache is thread safe, it does not prevent two threads +# from beginning the same computation. This simple cache mechanism +# uses a lock to ensure that only one thread even attempts. +CACHE = {} +LOCK = RLock() + +# Causes tokens reads to fail (for testing). The string should contain +# the token types that should fail; e.g., c, s, e +READ_CHAOS = os.environ.get("ANACONDA_ANON_USAGE_READ_CHAOS") or "" +# Causes token writes to fail (for testing). The string should contain +# the token types that should fail; c, e +WRITE_CHAOS = os.environ.get("ANACONDA_ANON_USAGE_WRITE_CHAOS") or "" +# Causes token writes to include a trailing newline (for testing). +WRITE_NEWLINE = False + +WRITE_SUCCESS = 0 +WRITE_DEFER = 1 +WRITE_FAIL = 2 + +# Number of bits of randomness to include in the token +MIN_ENTROPY = 128 +# Number of base64-encoded characters required to contain +# at least MIN_ENTROPY bits of randomness +TOKEN_LENGTH = (MIN_ENTROPY - 1) // 6 + 1 + + +def cached(func): + def call_if_needed(*args, **kwargs): + global CACHE + key = (func.__name__, args, tuple(kwargs.items())) + if key not in CACHE: + with LOCK: + # Need to check again, just in case the + # computation was happening between the + # first check and the lock acquisition. + if key not in CACHE: + CACHE[key] = func(*args, **kwargs) + return CACHE[key] + + return call_if_needed + + +def _cache_clear(*args): + global CACHE + global __nodestr + if not args: + CACHE.clear() + else: + CACHE = {k: v for k, v in CACHE.items() if k[0] not in args} + + +def _debug(s, *args, error=False): + if error and not DEBUG: + # Suppress error output in --json mode. This accommodates + # processes that might be using --json mode and merging + # stdout and stderr together. If DEBUG is True we assume + # this accommodation is not necessary. The import is + # deferred here as well to reduce the likelihood of a + # circular import issue. + from conda.base.context import context + + error = not context.json + if error or DEBUG: + print((DPREFIX + s) % args, file=sys.stderr) + + +def _random_token(what="random"): + # base64 encoding captures 6 bits per character. + # Generate enough random bytes to ensure all characters are random + data = os.urandom((TOKEN_LENGTH * 6 - 1) // 8 + 1) + result = base64.urlsafe_b64encode(data).decode("ascii")[:TOKEN_LENGTH] + _debug("Generated %s token: %s", what, result) + return result + + +def _final_attempt(): + """ + Called upon the graceful exit from conda, this attempts to + write an environment token that was deferred because the + environment directory was not yet available. + """ + global DEFERRED + for must_exist, fpath, token, what in DEFERRED: + _write_attempt(must_exist, fpath, token) + + +atexit.register(_final_attempt) + + +def _write_attempt(must_exist, fpath, client_token, emulate_fail=False): + """ + Attempt to write the token to the given location. + Return True with success, False otherwise. + """ + if must_exist and not isdir(must_exist): + _debug("Directory not ready: %s", must_exist) + return WRITE_DEFER + try: + if emulate_fail: + raise OSError(errno.EROFS, "Testing permissions issues") + os.makedirs(dirname(fpath), exist_ok=True) + if WRITE_NEWLINE: + client_token = client_token + "\n# Test comment" + with open(fpath, "w") as fp: + fp.write(client_token) + _debug("Token saved: %s", fpath) + return WRITE_SUCCESS + except Exception as exc: + # If we get here, a second attempt is unlikely to succeed, + # so we return a code to indicate that we should not re-attempt. + if getattr(exc, "errno", None) in (errno.EACCES, errno.EPERM, errno.EROFS): + _debug("No write permissions; cannot write token") + else: + _debug( + "Unexpected error writing token file:\n path: %s\n exception: %s", + fpath, + exc, + error=True, + ) + return WRITE_FAIL + + +def _deferred_exists( + fpath: str, what: str, deferred_writes: List = DEFERRED +) -> Optional[str]: + """ + Check if the deferred token write exists in the DEFERRED write array. + If the path must already exist, this helper function determines + if the token will be written in the future. + + Args: + fpath: The file path to check for. + what: The type of token to check for. + deferred_tokens: The list of deferred tokens to check. + + Returns: + The token if it exists, otherwise None. + """ + for _, fp, token, w in deferred_writes: + if fp == fpath and w == what: + return token + + +def _read_file(fpath, what, read_only=False, single_line=False): + """ + Implements the saved token functionality. If the specified + file exists, and contains a token with the right format, + return it. Otherwise, generate a new one and save it in + this location. If that fails, return an empty string. + """ + global DEFERRED + + # If a deferred token exits for the given fpath, return it instead of generating a new one. + deferred_token = _deferred_exists(fpath, what) + if deferred_token: + _debug("Returning deferred %s: %s", what, deferred_token) + return deferred_token + + _debug("%s path: %s", what.capitalize(), fpath) + if what[0] in READ_CHAOS: + _debug("Pretending %s is not present", what) + elif not isfile(fpath): + _debug("%s file is not present", what) + else: + try: + with open(fpath) as fp: + data = fp.read() + if single_line: + # Use just the first non-blank line of the file + data = data.strip() + if data: + data = data.splitlines()[0] + _debug("Retrieved %s: %s", what, data) + return data + except Exception as exc: + _debug("Unexpected error reading: %s\n %s", fpath, exc, error=True) + + +def _get_node_str(): + """ + Returns a base64-encoded representation of the host ID + as determined by uuid.getnode(). + """ + val = uuid._unix_getnode() or uuid._windll_getnode() + # https://github.com/anaconda/anaconda-anon-usage/pull/173 + if not val and getattr(uuid, "_generate_time_safe", None): + val = uuid.UUID(bytes=uuid._generate_time_safe()[0]).node + if val: + val = val.to_bytes(6, byteorder=sys.byteorder) + val = base64.urlsafe_b64encode(val) + val = val.decode("ascii") + return val + + +def _saved_token(fpath, what, must_exist=None, read_only=False, node_tie=False): + """ + Implements the saved token functionality. If the specified + file exists, and contains a token with the right format, + return it. Otherwise, generate a new one and save it in + this location. If that fails, return an empty string. + """ + global DEFERRED + what = what + " token" + regenerate = resave = False + client_token = _read_file(fpath, what, single_line=True) or "" + # Version 0.7.0 stored the host ID alongside the client token + client_token, *xtra = client_token.split(" ", 1) + if len(client_token) < TOKEN_LENGTH: + if client_token: + _debug("Regenerating %s due to short length", what) + regenerate = True + if node_tie: + # Client tokens should be unique to each user, but under some + # scenarios they are inadvertently copied to multiple machines, + # which breaks that behavior. To resolve this issue, we create a + # sidecar file containing the host ID. If the host ID changes, + # we can regenerate the token. The token itself remains 100% + # anonymous under this approach, and the host ID is not sent. + current_node = _get_node_str() + npath = fpath + "_host" + saved_node = _read_file(npath, "Host id", single_line=True) or "" + true_node = saved_node or (xtra[0] if xtra else None) + if regenerate or not true_node: + pass + elif true_node != current_node: + _debug("Regenerating %s due to hostID change", what) + regenerate = True + elif xtra: + _debug("Stripping host ID from %s file", what) + resave = True + else: + _debug("Host ID match confirmed for %s", what) + if saved_node != current_node: + action = ( + ("Migrating" if true_node == current_node else "Updating") + if true_node + else "Saving" + ) + current_node = current_node or "" + _debug("%s host ID: %s", action, current_node) + if _write_attempt(False, npath, current_node, False) == WRITE_DEFER: + DEFERRED.append((False, npath, current_node, "Host ID")) + if regenerate or resave: + if read_only: + return "" + if regenerate: + client_token = _random_token() + status = _write_attempt(must_exist, fpath, client_token, what[0] in WRITE_CHAOS) + if status == WRITE_FAIL: + _debug("Returning blank %s", what) + return "" + elif status == WRITE_DEFER: + # If the environment has not yet been created we need + # to defer the token write until later. + _debug("Deferring %s write", what) + DEFERRED.append((must_exist, fpath, client_token, what)) + return client_token diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__init__.py b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e04ef04759ffcb14c56a4795e59972f13e1305dd --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__init__.py @@ -0,0 +1,10 @@ +try: + from anaconda_auth._version import version as __version__ +except ImportError: # pragma: nocover + __version__ = "unknown" + +from anaconda_auth.actions import login # noqa: E402 +from anaconda_auth.actions import logout # noqa: E402 +from anaconda_auth.client import client_factory # noqa: E402 + +__all__ = ["__version__", "login", "logout", "client_factory"] diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__main__.py b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..84f0bb918868aff1e38e39b4950bc039b28dc621 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__main__.py @@ -0,0 +1,4 @@ +from anaconda_auth.cli import app + +if __name__ == "__main__": + app() diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_version.py b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..2cb81870fb27605a1393b9cb659eb692187bfdbb --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_version.py @@ -0,0 +1,34 @@ +# file generated by setuptools-scm +# don't change, don't track in version control + +__all__ = [ + "__version__", + "__version_tuple__", + "version", + "version_tuple", + "__commit_id__", + "commit_id", +] + +TYPE_CHECKING = False +if TYPE_CHECKING: + from typing import Tuple + from typing import Union + + VERSION_TUPLE = Tuple[Union[int, str], ...] + COMMIT_ID = Union[str, None] +else: + VERSION_TUPLE = object + COMMIT_ID = object + +version: str +__version__: str +__version_tuple__: VERSION_TUPLE +version_tuple: VERSION_TUPLE +commit_id: COMMIT_ID +__commit_id__: COMMIT_ID + +__version__ = version = '0.12.3' +__version_tuple__ = version_tuple = (0, 12, 3) + +__commit_id__ = commit_id = None diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/actions.py b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/actions.py new file mode 100644 index 0000000000000000000000000000000000000000..ad043b1a2f2dfc58ae34477e1f43f8f951ea87e9 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/actions.py @@ -0,0 +1,324 @@ +import logging +import uuid +import warnings +import webbrowser +from typing import Optional +from typing import Union +from urllib.parse import urlencode + +import pkce + +from anaconda_auth import __version__ +from anaconda_auth.client import BaseClient +from anaconda_auth.config import AnacondaAuthConfig +from anaconda_auth.config import AnacondaAuthSite +from anaconda_auth.device_flow import DeviceCodeFlow +from anaconda_auth.exceptions import AuthenticationError +from anaconda_auth.exceptions import DeviceFlowError +from anaconda_auth.exceptions import TokenNotFoundError +from anaconda_auth.handlers import capture_auth_code +from anaconda_auth.token import TokenInfo +from anaconda_cli_base.console import console + +logger = logging.getLogger(__name__) + + +def make_auth_code_request_url( + code_challenge: str, state: str, config: Optional[AnacondaAuthSite] = None +) -> str: + """Build the authorization code request URL.""" + + if config is None: + config = AnacondaAuthConfig() + + authorization_endpoint = config.oidc.authorization_endpoint + client_id = config.client_id + redirect_uri = config.redirect_uri + + params = dict( + client_id=client_id, + response_type="code", + scope="openid email profile offline_access", + state=state, + redirect_uri=redirect_uri, + code_challenge=code_challenge, + code_challenge_method="S256", + ) + encoded_params = urlencode(params) + url = f"{authorization_endpoint}?{encoded_params}" + + return url + + +def _send_auth_code_request( + code_challenge: str, state: str, config: AnacondaAuthSite +) -> None: + """Open the authentication flow in the browser.""" + url = make_auth_code_request_url(code_challenge, state, config) + webbrowser.open(url) + + +def refresh_access_token(refresh_token: str, config: AnacondaAuthSite) -> str: + """Refresh and save the tokens.""" + client = BaseClient(site=config) + response = client.post( + config.oidc.token_endpoint, + data={ + "grant_type": "refresh_token", + "refresh_token": refresh_token, + "client_id": config.client_id, + }, + auth=False, # type: ignore + ) + response.raise_for_status() + response_data = response.json() + + access_token = response_data["access_token"] + return access_token + + +def request_access_token( + auth_code: str, code_verifier: str, config: AnacondaAuthSite +) -> str: + """Request an access token using the provided authorization code and code verifier.""" + token_endpoint = config.oidc.token_endpoint + client_id = config.client_id + redirect_uri = config.redirect_uri + + client = BaseClient(site=config) + response = client.post( + token_endpoint, + data=dict( + grant_type="authorization_code", + client_id=client_id, + code=auth_code, + redirect_uri=redirect_uri, + code_verifier=code_verifier, + ), + auth=False, # type: ignore + ) + result = response.json() + + if "error" in result: + raise AuthenticationError( + f"Error getting JWT: {result.get('error')} - {result.get('error_description')}" + ) + + access_token = result.get("access_token") + return access_token + + +def _do_device_flow(config: Optional[AnacondaAuthSite] = None) -> str: + """Login using OAuth 2.0 device code flow.""" + config = config or AnacondaAuthConfig() + + # Initialize device flow + device_flow = DeviceCodeFlow(config=config) + + # Step 1: Initiate device authorization + device_authorization = device_flow.initiate_device_authorization() + + # Step 2: Display instructions to user + console.print( + "Attempting to automatically open the authorization page in your default browser." + ) + console.print( + "If the browser does not open or you wish to use a different device to authorize this request, open the following URL:" + ) + console.print() + console.print(device_authorization.verification_uri) + console.print() + console.print("Then enter the code:") + console.print() + console.print(device_authorization.user_code) + console.print() + + # Try to open browser automatically + try: + webbrowser.open(device_authorization.verification_uri_complete) + except Exception: + pass + + status = console.status("Waiting for authorization (CTRL-C to cancel)") + + try: + # Step 3: Poll for token + status.start() + token_response = device_flow.poll_for_token() + status.stop() + console.print("✓ Login successful!") + # return access token + return token_response["access_token"] + except KeyboardInterrupt: + status.stop() + raise + except DeviceFlowError: + status.stop() + raise + + +def _do_auth_flow(config: Optional[AnacondaAuthSite] = None) -> str: + """Do the browser-based auth flow and return the short-lived access_token and id_token tuple.""" + config = config or AnacondaAuthConfig() + + state = str(uuid.uuid4()) + code_verifier, code_challenge = pkce.generate_pkce_pair(code_verifier_length=128) + + _send_auth_code_request(code_challenge, state, config) + + # Listen for the response + auth_code = capture_auth_code(config.redirect_uri, state=state, config=config) + logger.debug("Authentication successful! Getting JWT token.") + + # Do auth code exchange + return request_access_token(auth_code, code_verifier, config) + + +def _login_with_username(config: Optional[AnacondaAuthSite] = None) -> str: + """Prompt for username and password and log in with the password grant flow.""" + warnings.warn( + "Basic login with username/password is deprecated and will be disabled soon.", + UserWarning, + stacklevel=0, + ) + + if config is None: + config = AnacondaAuthConfig() + + username = console.input("Please enter your email: ") + password = console.input("Please enter your password: ", password=True) + + client = BaseClient(site=config) + response = client.post( + config.oidc.token_endpoint, + data={ + "grant_type": "password", + "username": username, + "password": password, + }, + auth=False, # type: ignore + ) + response_data = response.json() + response.raise_for_status() + + access_token = response_data["access_token"] + return access_token + + +def _do_login(config: AnacondaAuthSite, basic: bool) -> None: + if basic: + access_token = _login_with_username(config=config) + elif config.use_device_flow: + access_token = _do_device_flow(config=config) + else: + access_token = _do_auth_flow(config=config) + + api_key = get_api_key( + access_token, + config=config, + ) + + token_info = TokenInfo(api_key=api_key, domain=config.domain) + token_info.save() + + +def get_api_key( + access_token: str, + config: Optional[AnacondaAuthSite] = None, +) -> str: + config = config or AnacondaAuthConfig() + client = BaseClient(site=config) + + headers = {"Authorization": f"Bearer {access_token}"} + + aau_token = config.aau_token + if aau_token is not None: + headers["X-AAU-CLIENT"] = aau_token + + # Retry logic until we stabilize on new API + urls = [ + f"https://{config.auth_domain}/api/auth/api-keys", + f"https://{config.domain}/api/iam/api-keys", + ] + for url in urls: + response = client.post( + url, + json=dict( + scopes=["cloud:read", "cloud:write", "repo:read"], + tags=[f"anaconda-auth/v{__version__}"], + ), + headers=headers, + auth=False, # type: ignore + ) + if response.status_code == 201: + break + else: + console.print("Error retrieving an API key") + raise AuthenticationError + return response.json()["api_key"] + + +def _api_key_is_valid(config: AnacondaAuthSite) -> bool: + try: + valid = not TokenInfo.load(config.domain).expired + except TokenNotFoundError: + valid = False + + return valid + + +def login( + config: Optional[AnacondaAuthSite] = None, + ssl_verify: Optional[bool] = None, + basic: bool = False, + force: bool = False, +) -> None: + """Log into anaconda.com and store the token information in the keyring.""" + if config is None: + config = AnacondaAuthConfig() + if ssl_verify is not None: + config = config.model_copy(update={"ssl_verify": ssl_verify}) + + if force or not _api_key_is_valid(config=config): + _do_login(config=config, basic=basic) + + +def logout(config: Optional[AnacondaAuthSite] = None) -> None: + """Log out of anaconda.com.""" + if config is None: + config = AnacondaAuthConfig() + + try: + token_info = TokenInfo.load(domain=config.domain) + token_info.delete() + except TokenNotFoundError: + pass + + if config.domain != "anaconda.com": + # Since anaconda.com is the default, don't do anything special if + # User explicitly overrode the configured domain. + return + + # If the request was for anaconda.com (the default), also remove + # anaconda.cloud if it exists. This is just an edge case for the + # likely rare scenario where a user has a stored token for both + # domains. + try: + token_info = TokenInfo.load(domain="anaconda.cloud") + token_info.delete() + except TokenNotFoundError: + pass + + +def is_logged_in(site: Optional[Union[str, AnacondaAuthSite]] = None) -> bool: + if isinstance(site, AnacondaAuthSite): + config = site + else: + config = AnacondaAuthConfig(site=site) + + try: + token_info = TokenInfo.load(domain=config.domain) + except TokenNotFoundError: + token_info = None + + return token_info is not None diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/adapters.py b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/adapters.py new file mode 100644 index 0000000000000000000000000000000000000000..e3d84db94c68e7720ca680ad92b7e8d7bbcce0fa --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/adapters.py @@ -0,0 +1,48 @@ +from typing import TYPE_CHECKING +from typing import Any +from typing import Optional + +from requests.adapters import HTTPAdapter as BaseHttpAdapter + +if TYPE_CHECKING: + from ssl import SSLContext + + from urllib3 import PoolManager + + +class _SSLContextAdapterMixin: + """Mixin to add the ``ssl_context`` constructor argument to HTTP adapters. + + The additional argument is forwarded directly to the pool manager. This allows us + to dynamically decide what SSL store to use at runtime, which is used to implement + the optional ``truststore`` backend. + """ + + def __init__( + self, + *, + ssl_context: Optional["SSLContext"] = None, + **kwargs: Any, + ) -> None: + self._ssl_context = ssl_context + super().__init__(**kwargs) + + def init_poolmanager( + self, + connections: int, + maxsize: int, + block: bool = False, + **pool_kwargs: Any, + ) -> "PoolManager": + if self._ssl_context is not None: + pool_kwargs.setdefault("ssl_context", self._ssl_context) + return super().init_poolmanager( # type: ignore[misc] + connections=connections, + maxsize=maxsize, + block=block, + **pool_kwargs, + ) + + +class HTTPAdapter(_SSLContextAdapterMixin, BaseHttpAdapter): + pass diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/cli.py b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..4d50f0a323bb2a651a239892264785e3e42acf46 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/cli.py @@ -0,0 +1,334 @@ +import os +import sys +import warnings +from textwrap import dedent +from typing import List +from typing import Optional + +import typer +from requests.exceptions import HTTPError +from requests.exceptions import JSONDecodeError +from rich.prompt import Confirm +from rich.syntax import Syntax + +from anaconda_auth import __version__ +from anaconda_auth.actions import login +from anaconda_auth.actions import logout +from anaconda_auth.client import BaseClient +from anaconda_auth.exceptions import TokenExpiredError +from anaconda_auth.token import TokenInfo +from anaconda_auth.token import TokenNotFoundError +from anaconda_cli_base.config import anaconda_config_path +from anaconda_cli_base.console import console +from anaconda_cli_base.exceptions import register_error_handler + + +def _continue_with_login() -> int: + if sys.stdout.isatty(): + do_login = Confirm.ask("Continue with interactive login?", choices=["y", "n"]) + if do_login: + login() + return -1 + else: + console.print( + dedent(""" + To configure your credentials you can run + [green]anaconda login --at anaconda.com[/green] + + or set your API key using the [green]ANACONDA_AUTH_API_KEY[/green] env var + + or set + """) + ) + console.print( + Syntax( + dedent( + """\ + [plugin.auth] + api_key = "" + """ + ), + "toml", + background_color=None, + ) + ) + console.print(f"in {anaconda_config_path()}") + return 1 + + +def _login_required_message(error_classifier: str) -> None: + console.print( + f"[bold][red]{error_classifier}[/red][/bold]: Login is required to complete this action." + ) + + +@register_error_handler(TokenNotFoundError) +def login_required(e: Exception) -> int: + _login_required_message(e.__class__.__name__) + return _continue_with_login() + + +@register_error_handler(TokenExpiredError) +def token_expired(e: Exception) -> int: + console.print( + f"[bold][red]{e.__class__.__name__}[/red][/bold]: Your login token has expired" + ) + + return _continue_with_login() + + +@register_error_handler(HTTPError) +def http_error(e: HTTPError) -> int: + try: + error_code = e.response.json().get("error", {}).get("code", "") + except JSONDecodeError: + error_code = "" + + if error_code == "auth_required": + if "Authorization" in e.request.headers: + console.print( + "[bold][red]InvalidAuthentication:[/red][/bold] Your provided API Key or login token is invalid" + ) + else: + _login_required_message("AuthenticationMissingError") + return _continue_with_login() + else: + console.print(f"[bold][red]{e.__class__.__name__}:[/red][/bold] {e}") + return 1 + + +def _override_default_site(at: Optional[str] = None) -> None: + if at: + os.environ["ANACONDA_DEFAULT_SITE"] = at + + +app = typer.Typer( + name="auth", + add_completion=False, + help="Manage your Anaconda authentication", + context_settings={ + "allow_extra_args": True, + "ignore_unknown_options": True, + "help_option_names": ["--help", "-h"], + }, +) + + +@app.callback( + invoke_without_command=True, + no_args_is_help=False, +) +def main( + ctx: typer.Context, + version: bool = typer.Option(False, "-V", "--version"), + name: Optional[str] = typer.Option( + None, + "-n", + "--name", + hidden=True, + ), + organization: Optional[str] = typer.Option( + None, + "-o", + "--org", + "--organization", + hidden=True, + ), + strength: Optional[str] = typer.Option( + None, + "--strength", + hidden=True, + ), + strong: Optional[bool] = typer.Option( + None, + "--strong", + hidden=True, + ), + weak: Optional[bool] = typer.Option( + None, + "-w", + "--weak", + hidden=True, + ), + url: Optional[str] = typer.Option( + None, + "--url", + hidden=True, + ), + max_age: Optional[str] = typer.Option( + None, + "--max-age", + hidden=True, + ), + scopes: Optional[str] = typer.Option( + None, + "-s", + "--scopes", + hidden=True, + ), + out: Optional[str] = typer.Option( + None, + "--out", + hidden=True, + ), + list_scopes: Optional[bool] = typer.Option( + None, + "-x", + "--list-scopes", + hidden=True, + ), + list_tokens: Optional[bool] = typer.Option( + None, + "-l", + "--list", + hidden=True, + ), + remove: Optional[str] = typer.Option( + None, + "-r", + "--remove", + hidden=True, + ), + create: Optional[bool] = typer.Option( + None, + "-c", + "--create", + hidden=True, + ), + info: Optional[bool] = typer.Option( + None, + "-i", + "--info", + "--current-info", + hidden=True, + ), + extra_args: Optional[List[str]] = typer.Argument( + default=None, hidden=True, metavar="" + ), +) -> None: + if version: + console.print( + f"anaconda-auth, version [cyan]{__version__}[/cyan]", + style="bold green", + ) + raise typer.Exit() + + # We have to manually handle subcommands due the the handling of the auth subcommand + # as a top-level subcommand in anaconda-client + extra_args = extra_args or [] + if extra_args: + subcommand_name = extra_args[0] + else: + subcommand_name = None + + # Extract the subcommands attached to the app. Use dynamic loading just to be safe, + # because static typing shows this to be invalid. + subcommands_dict = getattr(ctx.command, "commands", {}) + + # If the subcommand is known, then we delegate to the actual functions defined in this module + if cmd := subcommands_dict.get(subcommand_name): + cmd.main( + extra_args[1:], prog_name=subcommand_name, standalone_mode=False, parent=ctx + ) + return + + has_legacy_options = any( + value is not None + for value in ( + name, + organization, + strength, + strong, + weak, + url, + max_age, + scopes, + out, + list_scopes, + list_tokens, + remove, + create, + info, + ) + ) + + if has_legacy_options or subcommand_name: + # If any of the anaconda-client options are passed, try to delegate to + # binstar_main if it exists. Otherwise, we just exit gracefully. + + try: + from binstar_client.scripts.cli import main as binstar_main + except (ImportError, ModuleNotFoundError): + return + + console.print( + "[yellow]DeprecationWarning[/yellow]: Please use [cyan]anaconda org auth[/cyan] instead for explicit management of anaconda.org auth tokens\n" + ) + warnings.warn( + "Please use `anaconda org auth` instead for explicit management of anaconda.org auth tokens", + DeprecationWarning, + ) + + binstar_main(sys.argv[1:], allow_plugin_main=False) + return + + # No subcommand was given, so we print help + console.print(ctx.get_help()) + + +@app.command("login") +def auth_login( + force: bool = False, + ssl_verify: Optional[bool] = typer.Option(None, "--ssl-verify/--no-ssl-verify"), + at: Optional[str] = None, +) -> None: + """Login""" + _override_default_site(at) + try: + token_info = TokenInfo.load() + domain = token_info.domain + if token_info.expired: + console.print(f"Your API key has expired, logging into {domain}") + login(force=True, ssl_verify=ssl_verify) + raise typer.Exit() + except TokenNotFoundError: + pass # Proceed to login + else: + force = force or Confirm.ask( + f"You are already logged into Anaconda ({domain}). Would you like to force a new login?", + default=False, + ) + if not force: + raise typer.Exit() + + login(force=force, ssl_verify=ssl_verify) + + +@app.command(name="whoami") +def auth_info(at: Optional[str] = None) -> None: + """Display information about the currently signed-in user""" + _override_default_site(at) + client = BaseClient() + response = client.get("/api/account") + response.raise_for_status() + console.print(f"Your info ({client.config.domain}):") + console.print_json(data=response.json(), indent=2, sort_keys=True) + + +@app.command(name="api-key") +def auth_key(at: Optional[str] = None) -> None: + """Display API Key for signed-in user""" + _override_default_site(at) + token_info = TokenInfo.load() + if not token_info.expired: + print(token_info.api_key) + return + else: + raise TokenExpiredError() + + +@app.command(name="logout") +def auth_logout(at: Optional[str] = None) -> None: + """Logout""" + _override_default_site(at) + logout() diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/client.py b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/client.py new file mode 100644 index 0000000000000000000000000000000000000000..77a986bfa721715e480af8e5861ced6df79379ee --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/client.py @@ -0,0 +1,299 @@ +import json +import warnings +from functools import cached_property +from hashlib import md5 +from typing import Any +from typing import Dict +from typing import MutableMapping +from typing import Optional +from typing import Union +from typing import cast +from urllib.parse import urljoin + +import requests +from requests import PreparedRequest +from requests import Response +from requests.auth import AuthBase + +from anaconda_auth import __version__ as version +from anaconda_auth.adapters import HTTPAdapter +from anaconda_auth.config import AnacondaAuthConfig +from anaconda_auth.config import AnacondaAuthSite +from anaconda_auth.exceptions import TokenExpiredError +from anaconda_auth.exceptions import TokenNotFoundError +from anaconda_auth.token import TokenInfo +from anaconda_auth.utils import get_hostname +from anaconda_cli_base.exceptions import AnacondaConfigValidationError + +# VersionInfo was renamed and is deprecated in semver>=3 +try: + from semver.version import Version +except ImportError: + # In semver<3, it's called VersionInfo + from semver import VersionInfo as Version + + +def login_required(response: Response, *args: Any, **kwargs: Any) -> Response: + has_auth_header = response.request.headers.get("Authorization", False) + + if response.status_code in [401, 403]: + try: + error_code = response.json().get("error", {}).get("code", "") + except requests.JSONDecodeError: + error_code = "" + + if error_code == "auth_required": + if has_auth_header: + response.reason = "Your API key or login token is invalid." + else: + response.reason = ( + "You must login before using this API endpoint" + " or provide an api_key to your client." + ) + + return response + + +class BearerAuth(AuthBase): + def __init__( + self, domain: Optional[str] = None, api_key: Optional[str] = None + ) -> None: + self.api_key = api_key + if domain is None: + domain = AnacondaAuthConfig().domain + + self._token_info = TokenInfo(domain=domain) + + def __call__(self, r: PreparedRequest) -> PreparedRequest: + if not self.api_key: + try: + r.headers["Authorization"] = ( + f"Bearer {self._token_info.get_access_token()}" + ) + except (TokenNotFoundError, TokenExpiredError): + pass + else: + r.headers["Authorization"] = f"Bearer {self.api_key}" + return r + + +class BaseClient(requests.Session): + _user_agent: str = f"anaconda-auth/{version}" + _api_version: Optional[str] = None + + def __init__( + self, + site: Optional[Union[str, AnacondaAuthSite]] = None, + base_uri: Optional[str] = None, + domain: Optional[str] = None, + auth_domain_override: Optional[str] = None, + api_key: Optional[str] = None, + user_agent: Optional[str] = None, + api_version: Optional[str] = None, + ssl_verify: Optional[Union[bool, str]] = None, + extra_headers: Optional[Union[str, dict]] = None, + hash_hostname: Optional[bool] = None, + proxy_servers: Optional[MutableMapping[str, str]] = None, + client_cert: Optional[str] = None, + client_cert_key: Optional[str] = None, + ): + super().__init__() + + # Prepare the requested or default site config + if isinstance(site, AnacondaAuthSite): + config = site + elif site: + config = AnacondaAuthConfig(site=site) + else: + config = AnacondaAuthConfig() + + # Prepare site overrides + if base_uri and domain: + raise ValueError("Can only specify one of `domain` or `base_uri` argument") + + kwargs: Dict[str, Any] = {} + if domain is not None: + kwargs["domain"] = domain + if auth_domain_override is not None: + kwargs["auth_domain_override"] = auth_domain_override + if api_key is not None: + kwargs["api_key"] = api_key + if ssl_verify is not None: + kwargs["ssl_verify"] = ssl_verify + if extra_headers is not None: + kwargs["extra_headers"] = extra_headers + if hash_hostname is not None: + kwargs["hash_hostname"] = hash_hostname + if proxy_servers is not None: + kwargs["proxy_servers"] = proxy_servers + if client_cert_key is not None: + kwargs["client_cert"] = client_cert + kwargs["client_cert_key"] = client_cert_key + if client_cert is not None: + kwargs["client_cert"] = client_cert + + self.config = config.model_copy(update=kwargs) + + self.proxies = self.config.proxy_servers or {} + self.configure_ssl() + + # base_url overrides domain + self._base_uri = base_uri or f"https://{self.config.domain}" + self.headers["User-Agent"] = user_agent or self._user_agent + self.headers["X-Client-Hostname"] = get_hostname(hash=self.config.hash_hostname) + self.api_version = api_version or self._api_version + if self.api_version: + self.headers["Api-Version"] = self.api_version + + if self.config.extra_headers is not None: + if isinstance(self.config.extra_headers, str): + try: + self.config.extra_headers = cast( + dict, json.loads(self.config.extra_headers) + ) + except json.decoder.JSONDecodeError: + raise ValueError( + f"{repr(self.config.extra_headers)} is not valid JSON." + ) + + keys_to_add = self.config.extra_headers.keys() - self.headers.keys() + for k in keys_to_add: + self.headers[k] = self.config.extra_headers[k] + + self.auth = BearerAuth(domain=self.config.domain, api_key=self.config.api_key) + self.hooks["response"].append(login_required) + + def configure_ssl(self) -> None: + ssl_context = None + + if self.config.ssl_verify == "truststore": + try: + import ssl + + import truststore # type: ignore + + ssl_context = truststore.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + + except ImportError: + raise AnacondaConfigValidationError( + "The `ssl_verify: truststore` setting is only supported on Python 3.10 or later." + ) + self.verify = True + else: + self.verify = self.config.ssl_verify + + http_adapter = HTTPAdapter(ssl_context=ssl_context) + + self.mount("http://", http_adapter) + self.mount("https://", http_adapter) + + if self.config.client_cert_key and self.config.client_cert: + self.cert = (self.config.client_cert, self.config.client_cert_key) + elif self.config.client_cert: + self.cert = self.config.client_cert + + def urljoin(self, url: str) -> str: + return urljoin(self._base_uri, url) + + def prepare_request(self, request: requests.Request) -> PreparedRequest: + request.url = self.urljoin(str(request.url)) + return super().prepare_request(request) + + def request( + self, + method: Union[str, bytes], + url: Union[str, bytes], + *args: Any, + **kwargs: Any, + ) -> Response: + joined_url = self.urljoin(str(url)) + + # Ensure we don't set `verify` twice. If it is passed as a kwarg to this method, + # that becomes the value. Otherwise, we use the value in `self.config.ssl_verify`. + kwargs.setdefault("verify", self.config.ssl_verify) + + response = super().request(method, joined_url, *args, **kwargs) + + min_api_version_string = response.headers.get("Min-Api-Version") + self._validate_api_version(min_api_version_string) + + return response + + @cached_property + def account(self) -> dict: + res = self.get("/api/account") + res.raise_for_status() + account = res.json() + return account + + @property + def name(self) -> str: + user = self.account.get("user", {}) + + first_name = user.get("first_name", "") + last_name = user.get("last_name", "") + if not first_name and not last_name: + return self.email + else: + return f"{first_name} {last_name}".strip() + + @property + def email(self) -> str: + value = self.account.get("user", {}).get("email") + if value is None: + raise ValueError( + "Something is wrong with your account. An email address could not be found." + ) + else: + return value + + @cached_property + def avatar(self) -> Union[bytes, None]: + hashed = md5(self.email.encode("utf-8")).hexdigest() + res = self.get( + f"https://gravatar.com/avatar/{hashed}.png?size=120&d=404", + verify=self.config.ssl_verify, + auth=False, # type: ignore + ) + if res.ok: + return res.content + else: + return None + + def _validate_api_version(self, min_api_version_string: Optional[str]) -> None: + """Validate that the client API version against the min API version from the service.""" + if min_api_version_string is None or self.api_version is None: + return None + + # Convert to optional Version objects + api_version = _parse_semver_string(self.api_version) + min_api_version = _parse_semver_string(min_api_version_string) + + if api_version is None or min_api_version is None: + return None + + if api_version < min_api_version: + warnings.warn( + f"Client API version is {self.api_version}, minimum supported API version is {min_api_version_string}. " + "You may need to update your client.", + DeprecationWarning, + ) + + +def _parse_semver_string(version: str) -> Optional[Version]: + """Parse a version string into a semver Version object, stripping off any leading zeros from the components. + + If the version string is invalid, returns None. + + """ + norm_version = ".".join(s.lstrip("0") for s in version.split(".")) + try: + return Version.parse(norm_version) + except ValueError: + return None + + +def client_factory( + user_agent: Optional[str], api_version: Optional[str] = None +) -> BaseClient: + return BaseClient(user_agent=user_agent, api_version=api_version) diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/config.py b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/config.py new file mode 100644 index 0000000000000000000000000000000000000000..06da859a26bde81a61f9aa97ad1cd9abb6abbe18 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/config.py @@ -0,0 +1,318 @@ +import warnings +from functools import cached_property +from typing import Any +from typing import ClassVar +from typing import Dict +from typing import List +from typing import Literal +from typing import MutableMapping +from typing import Optional +from typing import Tuple +from typing import Type +from typing import Union +from urllib.parse import urljoin + +from pydantic import BaseModel +from pydantic import RootModel +from pydantic import field_validator +from pydantic.fields import FieldInfo +from pydantic_settings import BaseSettings +from pydantic_settings import PydanticBaseSettingsSource + +from anaconda_auth import __version__ as version +from anaconda_auth.exceptions import UnknownSiteName +from anaconda_cli_base.config import AnacondaBaseSettings +from anaconda_cli_base.config import AnacondaConfigTomlSettingsSource +from anaconda_cli_base.config import anaconda_config_path +from anaconda_cli_base.console import console + + +def _raise_deprecated_field_set_warning(set_fields: Dict[str, Any]) -> None: + fields_str = ", ".join(sorted(f'"{s}"' for s in set_fields.keys())) + warning_text = ( + "The following fields have been set using legacy environment variables " + + "prefixed with 'ANACONDA_CLOUD_` or in the `plugins.cloud` section " + + f"of `~/.anaconda/config.toml`: {fields_str}\n\n" + + "Please either rename environment variables to the corresponding " + + "`ANACONDA_AUTH_` version, or replace the `plugins.cloud` section " + + "of the config file with `plugins.auth`." + ) + console.print(f"[red]{warning_text}[/red]") + warnings.warn( + warning_text, + DeprecationWarning, + ) + + +class AnacondaAuthSite(BaseModel): + site: Optional[str] = "anaconda.com" + preferred_token_storage: Literal["system", "anaconda-keyring"] = "anaconda-keyring" + domain: str = "anaconda.com" + auth_domain_override: Optional[str] = None + api_key: Optional[str] = None + keyring: Optional[Dict[str, Dict[str, str]]] = None + ssl_verify: Union[bool, str] = True + extra_headers: Optional[Union[Dict[str, str], str]] = None + client_id: str = "b4ad7f1d-c784-46b5-a9fe-106e50441f5a" + redirect_uri: str = "http://127.0.0.1:8000/auth/oidc" + openid_config_path: str = "/.well-known/openid-configuration" + oidc_request_headers: Dict[str, str] = {"User-Agent": f"anaconda-auth/{version}"} + login_success_path: str = "/app/local-login-success" + login_error_path: str = "/app/local-login-error" + use_unified_repo_api_key: bool = False + hash_hostname: bool = True + proxy_servers: Optional[MutableMapping[str, str]] = None + client_cert: Optional[str] = None + client_cert_key: Optional[str] = None + use_device_flow: bool = False + _merged: bool = False + + @field_validator("ssl_verify", mode="before") + @classmethod + def validate_ssl_verify(cls, value: Any) -> Any: + if not isinstance(value, (bool, str)): + raise ValueError("Must be bool or str") + # Convert environment variable booleans + if value == "0": + return False + elif value == "1": + return True + else: + return value + + @property + def auth_domain(self) -> str: + """The authentication domain base URL. + + Defaults to the `auth` subdomain of the main domain. + + """ + if self.auth_domain_override: + return self.auth_domain_override + return self.domain + + @property + def well_known_url(self) -> str: + """The URL from which to load the OpenID configuration.""" + return urljoin(f"https://{self.auth_domain}", self.openid_config_path) + + @property + def login_success_url(self) -> str: + """The location to redirect after auth flow, if successful.""" + return urljoin(f"https://{self.domain}", self.login_success_path) + + @property + def login_error_url(self) -> str: + """The location to redirect after auth flow, if there is an error.""" + return urljoin(f"https://{self.domain}", self.login_error_path) + + @property + def oidc(self) -> "OpenIDConfiguration": + """The OIDC configuration, cached as a regular instance attribute.""" + from anaconda_auth.client import BaseClient + + client = BaseClient(site=self) + res = client.get( + self.well_known_url, + auth=False, # type: ignore + ) + res.raise_for_status() + oidc_config = OpenIDConfiguration(**res.json()) + return self.__dict__.setdefault("_oidc", oidc_config) + + @cached_property + def aau_token(self) -> Union[str, None]: + # The token is cached in anaconda_anon_usage, so we can also cache here + try: + from anaconda_anon_usage.tokens import token_string + except ImportError: + return None + + try: + return token_string() + except Exception: + # We don't want this to block user login in any case, + # so let any Exceptions pass silently. + return None + + +class AnacondaSettingsSource(PydanticBaseSettingsSource): + def get_field_value( + self, field: FieldInfo, field_name: str + ) -> tuple[Any, str, bool]: + # Nothing to do here. Only implement the return statement to make mypy happy + return None, "", False + + +class CondaContextSettingsSource(AnacondaSettingsSource): + def __call__(self) -> Dict[str, Any]: + values = {} + + try: + from conda.base.context import context + + if context.proxy_servers: + values["proxy_servers"] = dict(context.proxy_servers) + if context.client_ssl_cert: + values["client_cert"] = context.client_ssl_cert + if context.client_ssl_cert_key: + values["client_cert_key"] = context.client_ssl_cert_key + + values["ssl_verify"] = context.ssl_verify + + except ImportError: + pass + + return values + + +class AnacondaCloudSettingsSource(AnacondaSettingsSource): + def __call__(self) -> Dict[str, Any]: + cloud_config = AnacondaCloudConfig(raise_deprecation_warning=False) + set_fields = cloud_config.model_dump(exclude_unset=True) + if set_fields: + _raise_deprecated_field_set_warning(set_fields) + return set_fields + + +class AnacondaSiteSettingsSource(AnacondaSettingsSource): + def __call__(self) -> Dict[str, Any]: + state = self.current_state + site_config = AnacondaAuthSitesConfig() + all_sites = site_config.sites + if state.get("site"): + # If an explicit site is requested, the name must + # be an exact match for a key in the sites data. + site = all_sites._find_key(state["site"]) + elif state.get("domain"): + # If a domain is requested: + # - if a single match is found, use it + # - if multiple matches are found, raise an error + # - if no match is found, use the default + try: + site = all_sites._find_domain(state["domain"]) + except UnknownSiteName: + return {} + else: + # We now fall back to default_site, which for historical + # reasons can be a site key or a domain. + site = all_sites._find_at(site_config.default_site) + return all_sites.root[site].model_dump(exclude_unset=True) + + +class AnacondaAuthConfig(AnacondaAuthSite, AnacondaBaseSettings, plugin_name="auth"): + @classmethod + def settings_customise_sources( + cls, + settings_cls: Type[BaseSettings], + init_settings: PydanticBaseSettingsSource, + env_settings: PydanticBaseSettingsSource, + dotenv_settings: PydanticBaseSettingsSource, + file_secret_settings: PydanticBaseSettingsSource, + ) -> Tuple[PydanticBaseSettingsSource, ...]: + return ( + init_settings, + env_settings, + file_secret_settings, + dotenv_settings, + AnacondaSiteSettingsSource(cls), + AnacondaCloudSettingsSource(cls), + AnacondaConfigTomlSettingsSource(settings_cls, anaconda_config_path()), + CondaContextSettingsSource(cls), + ) + + +class OpenIDConfiguration(BaseModel): + authorization_endpoint: str + token_endpoint: str + device_authorization_endpoint: Optional[str] = None + + +_OLD_OIDC_REQUEST_HEADERS = {"User-Agent": f"anaconda-cloud-auth/{version}"} + + +class AnacondaCloudConfig(AnacondaAuthSite, AnacondaBaseSettings, plugin_name="cloud"): + oidc_request_headers: Dict[str, str] = _OLD_OIDC_REQUEST_HEADERS + + def __init__(self, raise_deprecation_warning: bool = True, **kwargs: Any): + if self.__class__ == "AnacondaCloudConfig" and raise_deprecation_warning: + warnings.warn( + "AnacondaCloudConfig is deprecated, please use AnacondaAuthConfig instead.", + DeprecationWarning, + ) + super().__init__(**kwargs) + + +class Sites(RootModel[Dict[str, AnacondaAuthSite]]): + def _find_key(self, key: Optional[str]) -> str: + if key in self.root: + return key + raise UnknownSiteName( + f"The site name {key} has not been configured in {anaconda_config_path()}" + ) + + def _find_domain(self, domain: Optional[str]) -> str: + matches = [ + (key, site) for key, site in self.root.items() if site.domain == domain + ] + if len(matches) == 1: + return matches[0][0] + if matches: + mstr = ", ".join(skey for skey, _ in matches) + raise ValueError( + f"The domain {domain} matches more than one configured site ({mstr})" + ) + elif domain == "anaconda.com": + self.root[domain] = AnacondaAuthSite() + return domain + else: + raise UnknownSiteName( + f"The site or domain {domain} has not been configured in {anaconda_config_path()}" + ) + + def _find_at(self, key: Optional[str]) -> str: + # Fuzzy match: + # - If the key is an exact match for a site key, use it + # - If the key matches a single site's domain, use it + # - Otherwise, raise an exception + try: + return self._find_key(key) + except UnknownSiteName: + return self._find_domain(key) + + def __getitem__(self, key: str) -> AnacondaAuthConfig: + return AnacondaAuthConfig(site=self._find_at(key)) + + +class AnacondaAuthSitesConfig(AnacondaBaseSettings, plugin_name=None): + _instance: ClassVar[Optional["AnacondaAuthSitesConfig"]] = None + + default_site: Optional[str] = None + sites: Sites = Sites({}) + + def __new__(cls) -> "AnacondaAuthSitesConfig": + if cls._instance is None: + cls._instance = super().__new__(cls) + return cls._instance + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + if self.default_site is None: + if self.sites.root: + self.default_site = next(iter(self.sites.root)) + else: + self.default_site = "anaconda.com" + self.sites.root["anaconda.com"] = AnacondaAuthSite() + for key, value in self.sites.root.items(): + value.site = key + + @classmethod + def all_sites(cls) -> List[str]: + return list(cls().sites.root) + + @classmethod + def load_site(cls, site: Optional[str] = None) -> AnacondaAuthSite: + """Load the site configuration object (site=None loads default_site)""" + config = cls() + sstr: str = site or config.default_site or "anaconda.com" + return config.sites[sstr] diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/device_flow.py b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/device_flow.py new file mode 100644 index 0000000000000000000000000000000000000000..16fd4b6832388cacd0d05f9332b53507c3c72637 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/device_flow.py @@ -0,0 +1,166 @@ +""" +Device Code Flow implementation for OAuth 2.0 device authorization grant (RFC 8628). +""" + +import json +import time +from typing import Dict +from typing import Optional + +import requests +from pydantic import BaseModel + +from anaconda_auth.client import BaseClient +from anaconda_auth.config import AnacondaAuthSite +from anaconda_auth.exceptions import DeviceFlowDenied +from anaconda_auth.exceptions import DeviceFlowError +from anaconda_auth.exceptions import DeviceFlowTimeout + + +class DeviceAuthorizationResponse(BaseModel): + device_code: str + user_code: str + verification_uri: str + verification_uri_complete: str + expires_in: int = 60 + interval: int = 5 + + +class DeviceCodeFlow: + """ + OAuth 2.0 Device Code Flow implementation. + + This implements RFC 8628 for devices that are either browserless + or have limited input capabilities. + """ + + config: AnacondaAuthSite + authorize_response: Optional[DeviceAuthorizationResponse] + + def __init__(self, config: AnacondaAuthSite): + """ + Initialize device code flow. + + Args: + config: Configuration for the client + """ + self.config = config + self.client = BaseClient(site=config) + + # Device authorization response data + self.authorize_response = None + + def initiate_device_authorization(self) -> DeviceAuthorizationResponse: + """ + Initiate device authorization request. + + Returns: + Tuple of (user_code, verification_uri) to display to user + """ + + data = {"client_id": self.config.client_id, "scope": "openid"} + + if self.config.oidc.device_authorization_endpoint is None: + raise DeviceFlowError("Server does not support device authorization") + + try: + response = self.client.post( + self.config.oidc.device_authorization_endpoint, + data=data, + verify=self.config.ssl_verify, + headers={"Content-Type": "application/x-www-form-urlencoded"}, + ) + response.raise_for_status() + + auth_response = response.json() + + self.authorize_response = DeviceAuthorizationResponse(**auth_response) + return self.authorize_response + + except requests.RequestException as e: + raise DeviceFlowError(f"Device authorization request failed: {e}") + except KeyError as e: + raise DeviceFlowError(f"Missing required field in response: {e}") + + def poll_for_token(self) -> Dict[str, str]: + """ + Poll the token endpoint until authorization is complete. + + Returns: + Token response containing access_token, etc. + """ + if not self.authorize_response: + raise DeviceFlowError("Must call initiate_device_authorization first") + + start_time = time.time() + expires_in = self.authorize_response.expires_in + interval = self.authorize_response.interval + + while time.time() - start_time < expires_in: + try: + token_response = self._request_token() + return token_response + + except DeviceFlowTimeout: + raise + except DeviceFlowDenied: + raise + except DeviceFlowError as e: + # Check for authorization_pending + if "authorization_pending" in str(e).lower(): + time.sleep(interval) + continue + elif "slow_down" in str(e).lower(): + # Server asked us to slow down + interval = min(interval + 5, 30) + time.sleep(interval) + continue + else: + raise + + raise DeviceFlowTimeout("Device authorization timed out") + + def _request_token(self) -> Dict[str, str]: + """Make a single token request.""" + if not self.authorize_response: + raise DeviceFlowError("Must call initiate_device_authorization first") + + data = { + "grant_type": "urn:ietf:params:oauth:grant-type:device_code", + "device_code": self.authorize_response.device_code, + "client_id": self.config.client_id, + } + + response = self.client.post( + self.config.oidc.token_endpoint, + data=data, + verify=self.config.ssl_verify, + headers={"Content-Type": "application/x-www-form-urlencoded"}, + ) + + if response.status_code == 200: + return response.json() + + # Handle error responses + try: + error_data = response.json() + error_code = error_data.get("error", "unknown_error") + error_description = error_data.get("error_description", "") + + if error_code == "authorization_pending": + raise DeviceFlowError("authorization_pending") + elif error_code == "slow_down": + raise DeviceFlowError("slow_down") + elif error_code == "expired_token": + raise DeviceFlowTimeout("Device code expired") + elif error_code == "access_denied": + raise DeviceFlowDenied("User denied authorization") + else: + raise DeviceFlowError( + f"Token request failed: {error_code} - {error_description}" + ) + + except json.JSONDecodeError: + response.raise_for_status() + + raise DeviceFlowError("Token request failed") diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/exceptions.py b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..e195486873c3dd56b6573a8878ffc0385312fc29 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/exceptions.py @@ -0,0 +1,40 @@ +class AuthenticationError(Exception): + pass + + +class InvalidTokenError(AuthenticationError): + pass + + +class TokenNotFoundError(Exception): + pass + + +class LoginRequiredError(Exception): + pass + + +class TokenExpiredError(Exception): + pass + + +class UnknownSiteName(Exception): + pass + + +class DeviceFlowError(Exception): + """Base exception for device flow errors.""" + + pass + + +class DeviceFlowTimeout(DeviceFlowError): + """Device authorization timed out.""" + + pass + + +class DeviceFlowDenied(DeviceFlowError): + """User denied device authorization.""" + + pass diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/handlers.py b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/handlers.py new file mode 100644 index 0000000000000000000000000000000000000000..48f3c2234be5554685d7c22289d7fcf32b8cd545 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/handlers.py @@ -0,0 +1,176 @@ +import logging +from http import HTTPStatus +from http.server import BaseHTTPRequestHandler +from http.server import HTTPServer +from socket import socket +from typing import Any +from typing import Dict +from typing import List +from typing import Optional +from typing import Set +from typing import Tuple +from typing import Union +from urllib.parse import parse_qs +from urllib.parse import urlparse + +import requests +from pydantic import BaseModel + +from anaconda_auth.config import AnacondaAuthConfig +from anaconda_auth.config import AnacondaAuthSite +from anaconda_auth.exceptions import AuthenticationError + +logger = logging.getLogger(__name__) + + +class Result(BaseModel): + """This class is needed to capture the auth code redirect data""" + + auth_code: str = "" + state: str = "" + scopes: List[str] = [] + + +TRequest = Union[socket, Tuple[bytes, socket]] + + +class AuthCodeRedirectServer(HTTPServer): + """A simple http server to handle the incoming auth code redirect from Ory""" + + _open_servers: Set["AuthCodeRedirectServer"] = set() + + def __init__( + self, + oidc_path: str, + server_address: Tuple[str, int], + config: Optional[AnacondaAuthSite] = None, + ): + super().__init__(server_address, AuthCodeRedirectRequestHandler) # type: ignore[arg-type] + self.result: Union[Result, None] = None + self.host_name = str(self.server_address[0]) + self.oidc_path = oidc_path + self.config = config or AnacondaAuthConfig() + + def __enter__(self) -> "AuthCodeRedirectServer": + self._open_servers.add(self) + return super().__enter__() + + def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None: + try: + self._open_servers.remove(self) + except KeyError: + # In case another thread removed it already, just ignore + pass + return super().__exit__(exc_type, exc_val, exc_tb) + + def finish_request(self, request: TRequest, client_address: str) -> None: + """Finish one request by instantiating RequestHandlerClass.""" + AuthCodeRedirectRequestHandler( + request, + client_address, + server=self, + oidc_path=self.oidc_path, + host_name=self.host_name, + login_success_url=self.config.login_success_url, + login_error_url=self.config.login_error_url, + ) + + +class AuthCodeRedirectRequestHandler(BaseHTTPRequestHandler): + """Request handler to get the auth code from the redirect from Ory""" + + server: AuthCodeRedirectServer + + def __init__( + self, + *args: Any, + oidc_path: str, + host_name: str, + login_success_url: str, + login_error_url: str, + **kwargs: Any, + ): + # these are set before __init__ because __init__ calls the do_GET method + self.oidc_path = oidc_path + self.host_name = host_name + self.login_success_url = login_success_url + self.login_error_url = login_error_url + + super().__init__(*args, **kwargs) + + def log_message(self, format: str, *args: Any) -> None: + """Override base method to suppress log message.""" + + def _handle_auth(self, query_params: Dict[str, List[str]]) -> None: + if "code" in query_params and "state" in query_params: + location = self.login_success_url + self.server.result = Result( + auth_code=query_params["code"][0], + state=query_params["state"][0], + scopes=query_params.get("scope", []), + ) + else: + location = self.login_error_url + + self.send_response(HTTPStatus.TEMPORARY_REDIRECT) + self.send_header("Location", location) + self.end_headers() + + def _not_found(self) -> None: + self.send_response(HTTPStatus.NOT_FOUND) + self.send_header("Content-type", "text/html") + self.end_headers() + + def do_GET(self) -> None: + parsed_url = urlparse(f"http://{self.host_name}{self.path}") + query_params = parse_qs(parsed_url.query) + + # Only accept requests to self.oidc_path + if parsed_url.path != self.oidc_path: + self._not_found() + else: + self._handle_auth(query_params) + + +def capture_auth_code( + redirect_uri: str, state: str, config: Optional[AnacondaAuthSite] = None +) -> str: + config = config or AnacondaAuthConfig() + parsed_url = urlparse(redirect_uri) + + host_name, port = parsed_url.netloc.split(":") + server_port = int(port or "80") + oidc_path = parsed_url.path + + logger.debug(f"Listening on: {redirect_uri}") + + with AuthCodeRedirectServer( + oidc_path, (host_name, server_port), config=config + ) as web_server: + web_server.handle_request() + + result = web_server.result + + if result is None: + raise AuthenticationError("Could not complete authentication") + + if result.auth_code is None: + raise AuthenticationError("No authorization code") + + if result.state != state: + raise AuthenticationError("State does not match") + + return result.auth_code + + +def shutdown_all_servers() -> None: + """Cancel all open AuthCodeRedirectServer instances, which may be blocking their thread waiting + for an auth code. + + This function should be called from a separate thread than the servers. + + """ + for server in list(AuthCodeRedirectServer._open_servers): + # Here, we just make a single request to force the `server.handle_request()` method to stop blocking. + # There is probably a better way by calling some method, but :shrug: + requests.get(f"http://{server.host_name}:{server.server_port}/cancel") diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/panel.py b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/panel.py new file mode 100644 index 0000000000000000000000000000000000000000..19a215d3fb7b23e61784396b5b79ce38384cdf3c --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/panel.py @@ -0,0 +1,48 @@ +from functools import cached_property + +from panel.auth import OAuthLoginHandler +from panel.config import config + +from anaconda_auth.config import AnacondaAuthConfig + + +class AnacondaLoginHandler(OAuthLoginHandler): + """Anaconda OAuth2 Authentication + + To utilize this handler you must have a Client ID (key) + and secret. The OAuth client at Anaconda must be configured for: + + * Set scopes: offline_access, openid, email, profile + * Set redirect url to http://localhost:5006 + * Set grant type: Authorization Code + * Set response types: ID Token, Token, Code + * Set access token type: JWT + * Set Authentication Method: HTTP Body + + """ + + _access_token_header: str = "Bearer {}" + + _EXTRA_TOKEN_PARAMS: dict = {"grant_type": "authorization_code"} + + _USER_KEY: str = "email" + _OAUTH_REDIRECT_URL: str = "http://localhost:5006" + + @cached_property + def _config(self) -> AnacondaAuthConfig: + return AnacondaAuthConfig() + + @property + def _OAUTH_AUTHORIZE_URL(self) -> str: + domain = config.oauth_extra_params.get("auth-domain", self._config.domain) # type: ignore + return f"https://{domain}/oauth2/auth" + + @property + def _OAUTH_USER_URL(self) -> str: + domain = config.oauth_extra_params.get("auth-domain", self._config.domain) # type: ignore + return f"https://{domain}/oauth2/userinfo" + + @property + def _OAUTH_ACCESS_TOKEN_URL(self) -> str: + domain = config.oauth_extra_params.get("auth-domain", self._config.domain) # type: ignore + return f"https://{domain}/oauth2/token" diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/py.typed b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/repo.py b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/repo.py new file mode 100644 index 0000000000000000000000000000000000000000..1d4e02a7b32572a695719d0f0f5df81955000365 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/repo.py @@ -0,0 +1,318 @@ +from __future__ import annotations + +from datetime import datetime +from uuid import UUID + +import typer +from pydantic import BaseModel +from rich.prompt import Confirm +from rich.table import Table + +from anaconda_auth.client import BaseClient +from anaconda_auth.token import RepoToken +from anaconda_auth.token import TokenInfo +from anaconda_cli_base import console +from anaconda_cli_base.console import select_from_list + +app = typer.Typer(name="token") + + +class TokenInfoResponse(BaseModel): + id: UUID + expires_at: datetime + + +class TokenCreateResponse(BaseModel): + token: str + expires_at: datetime + + +class OrganizationData(BaseModel): + id: UUID + name: str + title: str + + +class SubscriptionData(BaseModel): + org_id: UUID + product_code: str + + +class RepoAPIClient(BaseClient): + def _get_repo_token_info(self, org_name: str) -> TokenInfoResponse | None: + """Return the token information, if it exists. + + Args: + org_name: The name of the organization. + + Returns: + The token information, including its id and expiration date, or + None if a token doesn't exist. + """ + response = self.get( + f"/api/organizations/{org_name}/ce/current-token", + ) + if response.status_code == 404: + return None + response.raise_for_status() + return TokenInfoResponse(**response.json()) + + def _create_repo_token(self, org_name: str) -> TokenCreateResponse: + """Create a new repo token. + + Args: + org_name: The name of the organization. + + Returns: + The token information, including its value and expiration date. + """ + response = self.put( + f"/api/organizations/{org_name}/ce/current-token", + json={"confirm": "yes"}, + ) + return TokenCreateResponse(**response.json()) + + def issue_new_token(self, org_name: str, yes: bool = False) -> str: + """Issue a new repository token from anaconda.com.""" + existing_token_info = self._get_repo_token_info(org_name=org_name) + + if existing_token_info is not None and not yes: + console.print( + f"An existing token already exists for the organization [cyan]{org_name}[/cyan]." + ) + console.print( + "Reissuing a new token will revoke and deactivate any existing token access. This action can't be undone." + ) + should_continue = Confirm.ask("Proceed?", default=False) + if not should_continue: + raise typer.Abort() + + response = self._create_repo_token(org_name=org_name) + + console.print( + f"Your conda token has been installed and expires [cyan]{response.expires_at}[/cyan]. To view your token(s), you can use [cyan]anaconda token list[/cyan]" + ) + return response.token + + def get_organizations_for_user(self) -> list[OrganizationData]: + """Get a list of all organizations the user belongs to.""" + response = self.get("/api/organizations/my") + response.raise_for_status() + data = response.json() + return [OrganizationData(**item) for item in data] + + def get_business_organizations_for_user(self) -> list[OrganizationData]: + """Get a list of all organizations the user belongs to that have a Business subscription.""" + organizations = self.get_organizations_for_user() + subscriptions = [ + SubscriptionData(**sub) for sub in self.account.get("subscriptions", []) + ] + business_subscription_org_ids = [ + sub.org_id for sub in subscriptions if "starter" not in sub.product_code + ] + return [org for org in organizations if org.id in business_subscription_org_ids] + + +def _print_repo_token_table( + tokens: list[RepoToken], legacy_tokens: dict[str, str] +) -> None: + table = Table(title="Anaconda Repository Tokens", title_style="green") + + table.add_column("Organization") + table.add_column("Channel URL") + table.add_column("Token") + + from anaconda_auth._conda.repo_config import REPO_URL + + for repo_token in tokens: + channel_url = f"{REPO_URL}{repo_token.org_name}/*" + table.add_row(repo_token.org_name, channel_url, repo_token.token) + + for url, token in legacy_tokens.items(): + table.add_row(None, url, token) + + console.print(table) + + +def _select_org_name(client: RepoAPIClient) -> str: + organizations = client.get_business_organizations_for_user() + + if not organizations: + console.print("No organizations found.") + raise typer.Abort() + + if len(organizations) == 1: + org_name = organizations[0].name + console.print( + f"Only one organization found, automatically selecting: {org_name}" + ) + return org_name + + name_map = {} + choices = [] + for org in organizations: + key = f"{org.title} ([cyan]{org.name}[/cyan])" + name_map[key] = org.name + choices.append(key) + + org_title = select_from_list( + "Please select an organization:", + choices=choices, + ) + return name_map[org_title] + + +@app.callback(invoke_without_command=True, no_args_is_help=True) +def main() -> None: + """Manage your Anaconda repo tokens.""" + + +@app.command(name="list") +def list_tokens() -> None: + """List all installed repository tokens.""" + from anaconda_auth._conda.repo_config import token_list + + tokens = token_list() + + token_info = TokenInfo.load(create=True) + repo_tokens = token_info.repo_tokens + + if not (tokens or repo_tokens): + console.print( + "No repo tokens are installed. Run [cyan]anaconda token install[/cyan]." + ) + raise typer.Abort() + + _print_repo_token_table(tokens=repo_tokens, legacy_tokens=tokens) + + +@app.command(name="install") +def install_token( + token: str = typer.Argument( + "", help="Optionally, provide the token received via email or web interface." + ), + org_name: str = typer.Option("", "-o", "--org", help="Organization name (slug)."), + set_default_channels: bool = typer.Option( + True, help="Automatically configure default channels." + ), + yes: bool = typer.Option(False, "-y", "--yes", help="Accept all prompts"), +) -> None: + """Create and install a new repository token.""" + client = RepoAPIClient() + + if not org_name: + org_name = _select_org_name(client) + + if not token: + token = client.issue_new_token(org_name=org_name, yes=yes) + + from anaconda_auth._conda import repo_config + + try: + repo_config.validate_token(token, no_ssl_verify=False) + except repo_config.CondaTokenError as e: + raise typer.Abort(e) + + token_info = TokenInfo.load(create=True) + token_info.set_repo_token(org_name, token) + token_info.save() + + msg = "Your token has been installed and validated" + + if set_default_channels: + repo_config.configure_default_channels(force=yes) + msg += ", and conda has been configured" + + console.print(f"Success! {msg}.") + + +@app.command(name="config") +def configure_conda( + force: bool = typer.Option( + False, help="Force configuration of default channels without prompt." + ), +) -> None: + """Configure conda's default channels to access Anaconda's premium repository.""" + from anaconda_auth._conda import repo_config + + repo_config.configure_default_channels(force=force) + + +@app.command(name="uninstall") +def uninstall_token( + org_name: str = typer.Option("", "-o", "--org"), + all: bool = typer.Option(False, "-a", "--all"), +) -> None: + """Uninstall a repository token for a specific organization.""" + + token_info = TokenInfo.load() + if all: + token_info.delete_all_repo_token() + token_info.save() + console.print("Successfully deleted [cyan]all[/cyan] repo tokens.") + return + + if not org_name: + # TODO: We should try to load this dynamically and present a picker + console.print("Must explicitly provide an [cyan]--org[/cyan] option") + raise typer.Abort() + + token_info.delete_repo_token(org_name=org_name) + token_info.save() + + console.print( + f"Successfully deleted token for organization: [cyan]{org_name}[/cyan]" + ) + + +@app.command(name="set") +def set_token( + token: str = typer.Argument( + ..., help="Optionally, provide the token received via email or web interface." + ), + org_name: str = typer.Option("", "-o", "--org", help="Organization name (slug)."), + set_default_channels: bool = typer.Option( + True, help="Automatically configure default channels." + ), + file: str = typer.Option( + "", "-f", "--file", help="Write to the system .condarc file at '~/.condarc'." + ), + env: bool = typer.Option( + False, + "-e", + "--env", + help="Write to the active conda environment .condarc file. If no environment is active, write to the user config file (~/.condarc).", + ), + system: bool = typer.Option( + True, "-s", "--system", help="Organization name (slug)." + ), +) -> None: + """Install a new repository token.""" + if org_name: + install_token( + token=token, org_name=org_name, set_default_channels=set_default_channels + ) + from anaconda_auth._conda import repo_config + + repo_config.token_set(token=token, file=file, env=env, system=system) + + +@app.command(name="remove") +def remove_token( + file: str = typer.Option( + "", "-f", "--file", help="Write to the system .condarc file at '~/.condarc'." + ), + env: bool = typer.Option( + False, + "-e", + "--env", + help="Write to the active conda environment .condarc file. If no environment is active, write to the user config file (~/.condarc).", + ), + system: bool = typer.Option( + True, "-s", "--system", help="Organization name (slug)." + ), +) -> None: + """Remove binstar token and data from Keyring.""" + from anaconda_auth._conda import repo_config + + repo_config.token_remove(file=file, env=env, system=system) diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/token.py b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/token.py new file mode 100644 index 0000000000000000000000000000000000000000..0389286d8c17bd6ba6661037efca8abd00b73c2b --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/token.py @@ -0,0 +1,422 @@ +import base64 +import datetime as dt +import json +import logging +import os +from pathlib import Path +from typing import Any +from typing import Callable +from typing import Dict +from typing import List +from typing import Optional +from typing import Type +from typing import Union +from urllib.error import HTTPError + +import jwt +import keyring +from keyring.backend import KeyringBackend +from keyring.backend import properties +from keyring.errors import PasswordDeleteError +from keyring.errors import PasswordSetError +from pydantic import BaseModel +from pydantic import Field + +from anaconda_auth.config import AnacondaAuthConfig +from anaconda_auth.exceptions import TokenExpiredError +from anaconda_auth.exceptions import TokenNotFoundError + +# Note: we can remove this if we pin keyring>=23.9.0 +try: + classproperty = properties.classproperty +except AttributeError: + _KeyringClassMethod = Callable[[Type[KeyringBackend]], Any] + + def classproperty(method: _KeyringClassMethod) -> _KeyringClassMethod: # type: ignore + return properties.ClassProperty(classmethod(method)) # type: ignore + + +logger = logging.getLogger(__name__) + +# TODO: Rename to "Anaconda" and then migrate existing +KEYRING_NAME = "Anaconda Cloud" + + +# Type aliases +LocalKeyringData = Dict[str, Dict[str, str]] +OrgName = str +TokenString = str + + +def _as_base64_string(payload: str) -> str: + """Encode a string to a base64 string""" + return base64.b64encode(payload.encode("utf-8")).decode("utf-8") + + +class NavigatorFallback(KeyringBackend): + priority = 0.1 # type: ignore + + @classproperty + def viable(cls) -> bool: + try: + import anaconda_navigator # noqa: F401 + + return True + except ModuleNotFoundError: + return False + + def set_password(self, service: str, username: str, password: str) -> None: + raise PasswordSetError("This keyring cannot set passwords") + + def _get_auth_domain(self) -> str: + from anaconda_navigator.config import CONF as navigator_config + + known_mapping = {"https://anaconda.cloud": "id.anaconda.cloud"} + + cloud_base_url: str = navigator_config.get( + "main", "cloud_base_url", "https://anaconda.cloud" + ).strip("/") + return known_mapping[cloud_base_url] + + def get_password(self, service: str, username: str) -> Union[str, None]: + try: + from anaconda_navigator.api.nucleus.token import NucleusToken + + auth_domain = self._get_auth_domain() + except ImportError: + return None + + if service != KEYRING_NAME and username != auth_domain: + return None + + token = NucleusToken.from_file() + if token is not None: + from anaconda_auth.actions import get_api_key + from anaconda_auth.actions import refresh_access_token + + config = AnacondaAuthConfig(domain=auth_domain) + if not token.valid: + try: + access_token = refresh_access_token( + token.refresh_token, config=config + ) + except HTTPError: + return None + else: + access_token = token.access_token + + api_key = get_api_key(access_token) + token_info = { + "username": token.username, + "api_key": api_key, + "domain": config.domain, + } + payload = json.dumps(token_info) + encoded = _as_base64_string(payload) + keyring.set_password(KEYRING_NAME, auth_domain, encoded) + + return encoded + return None + + def delete_password(self, service: str, username: str) -> None: + auth_domain = self._get_auth_domain() + try: + from anaconda_navigator.api.nucleus.token import ( + TOKEN_FILE as navigator_token_file, + ) + + except ImportError: + return None + + if service != KEYRING_NAME and username != auth_domain: + return None + else: + try: + os.remove(navigator_token_file) + except FileNotFoundError: + return None + + +class AnacondaKeyring(KeyringBackend): + name = "token AnacondaKeyring" # Pinning name explicitly instead of relying on module.submodule automatic naming convention. + keyring_path = Path("~/.anaconda/keyring").expanduser() + + @classproperty + def priority(cls) -> float: + config = AnacondaAuthConfig() + if config.preferred_token_storage == "system": + return 0.2 + elif config.preferred_token_storage == "anaconda-keyring": + return 11.0 + else: + raise ValueError( + f"token_storage: {config.preferred_token_storage} is not supported." + ) + + @classproperty + def viable(cls) -> bool: + try: + cls.keyring_path.parent.mkdir(exist_ok=True, parents=True) + with cls.keyring_path.open("a") as f: + writable = f.writable() + return writable + except OSError: + return False + + def _read(self) -> LocalKeyringData: + if not self.keyring_path.exists(): + return {} + + try: + with self.keyring_path.open("r") as fp: + data = json.load(fp) + return data + except json.JSONDecodeError: + return {} + + def _save(self, data: LocalKeyringData) -> None: + self.keyring_path.parent.mkdir(exist_ok=True, parents=True) + + with self.keyring_path.open("w") as fp: + json.dump(data, fp) + + def set_password(self, service: str, username: str, password: str) -> None: + data = self._read() + + if service not in data: + data[service] = {} + + data[service][username] = password + + self._save(data) + + def get_password(self, service: str, username: str) -> Union[str, None]: + data = self._read() + return data.get(service, {}).get(username, None) + + def delete_password(self, service: str, username: str) -> None: + data = self._read() + try: + data.get(service, {}).pop(username) + self._save(data) + except KeyError: + raise PasswordDeleteError + + +class ConfigKeyring(AnacondaKeyring): + name = "token ConfigKeyring" + + @classproperty + def priority(cls) -> float: + config = AnacondaAuthConfig() + return 100.0 if config.api_key or config.keyring else 0.0 + + def set_password(self, service: str, username: str, password: str) -> None: + raise PasswordSetError("This keyring cannot set passwords") + + def delete_password(self, service: str, username: str) -> None: + raise PasswordSetError("This keyring cannot delete passwords") + + def _read(self) -> LocalKeyringData: + config = AnacondaAuthConfig() + if config.api_key: + # Build a keyring structure out of the api key and domain + decoded = TokenInfo(domain=config.domain, api_key=config.api_key) + encoded = base64.b64encode( + decoded.model_dump_json().encode("ascii") + ).decode("ascii") + return {KEYRING_NAME: {config.domain: encoded}} + if config.keyring: + return config.keyring + return {} + + +class RepoToken(BaseModel): + token: TokenString + org_name: Union[OrgName, None] = None + + +# A mapping of modern domain to a list of legacy domains. If a token is searched +# for at the modern domain and not found, we will search for any of the legacy domains +# and, if found, migrate the keyring storage from that domain to the new one. +MIGRATIONS: Dict[str, List[str]] = { + "anaconda.com": ["id.anaconda.cloud", "anaconda.cloud"] +} +TOKEN_INFO_VERSION = 2 + + +class TokenInfo(BaseModel): + domain: str = Field(default_factory=lambda: AnacondaAuthConfig().domain) + api_key: Union[str, None] = None + username: Union[str, None] = None + repo_tokens: List[RepoToken] = [] + version: Optional[int] = TOKEN_INFO_VERSION + + @classmethod + def _decode(cls, keyring_data: str) -> dict: + decoded_bytes = base64.b64decode(keyring_data) + decoded_dict = json.loads(decoded_bytes) + return decoded_dict + + @classmethod + def _migrate( + cls, keyring_data: str, from_domain: str, to_domain: str + ) -> "TokenInfo": + """Migrate the domain and save token under new domain.""" + decoded_dict = cls._decode(keyring_data) + decoded_dict["domain"] = to_domain + decoded_dict["version"] = TOKEN_INFO_VERSION + token_info = TokenInfo(**decoded_dict) + token_info.save() + keyring.delete_password(KEYRING_NAME, from_domain) + logger.debug( + f"🔓 Token has been migrated from legacy domain '{from_domain}' to '{to_domain}' 🎉" + ) + return token_info + + @classmethod + def load(cls, domain: Optional[str] = None, *, create: bool = False) -> "TokenInfo": + """Load the token information from the system keyring. + + Args: + domain: The domain for which to load the token information. If + not provided, defaults to the configuration domain. + create: If True, create a new TokenInfo object if not found. + + Returns: + The token information. + + """ + domain = domain or AnacondaAuthConfig().domain + + keyring_data = keyring.get_password(KEYRING_NAME, domain) + if keyring_data is not None: + logger.debug("🔓 Token has been successfully retrieved from keyring 🎉") + decoded_dict = cls._decode(keyring_data) + return TokenInfo(**decoded_dict) + + # Try again to see if there is a legacy token on disk + legacy_domains = MIGRATIONS.get(domain, []) + for legacy_domain in legacy_domains: + existing_keyring_data = keyring.get_password(KEYRING_NAME, legacy_domain) + if existing_keyring_data is not None: + return cls._migrate( + existing_keyring_data, from_domain=legacy_domain, to_domain=domain + ) + + if create: + logger.debug("🔓 Token has been successfully created 🎉") + return TokenInfo(domain=domain) + + raise TokenNotFoundError + + def save(self) -> None: + """Write the token information to the system keyring.""" + payload = self.model_dump_json(exclude_none=True) + encoded = _as_base64_string(payload) + keyring.set_password(KEYRING_NAME, self.domain, encoded) + logger.debug("🔒 Token has been safely stored in system keychain 🎉") + + def delete(self) -> None: + """Delete the token information from the system keyring.""" + try: + keyring.delete_password(KEYRING_NAME, self.domain) + if NavigatorFallback.viable: + NavigatorFallback().delete_password(KEYRING_NAME, self.domain) + except PasswordDeleteError: + raise TokenNotFoundError + + @property + def expired(self) -> bool: + if self.api_key is None: + return True + + decoded = jwt.decode( + self.api_key, algorithms=["RS256"], options={"verify_signature": False} + ) + expiry = dt.datetime.fromtimestamp(decoded["exp"]).replace( + tzinfo=dt.timezone.utc + ) + return expiry < dt.datetime.now(tz=dt.timezone.utc) + + def get_access_token(self) -> str: + """Get the access token, ensuring login and refresh if necessary.""" + if self.api_key is None: + try: + new_token_info = TokenInfo.load(self.domain) + except TokenNotFoundError: + message = "No token found, please login with `anaconda login`" + raise TokenNotFoundError(message) + + # Store the new token information for later retrieval + self.username = new_token_info.username + self.api_key = new_token_info.api_key + + assert self.api_key is not None + + if self.expired: + raise TokenExpiredError( + "Your login token as expired. Please login again using\n" + " anaconda login --force" + ) + + return self.api_key + + def set_repo_token(self, org_name: OrgName, token: TokenString) -> None: + """Set the repo token for a specific organization. + + Args: + org_name: The organization name for which to search for a token. + token: The token value. + + """ + + try: + self.get_repo_token(org_name=org_name) + except TokenNotFoundError: + # This is good, we don't need to do anything + pass + else: + # We need to remove the existing token for this org first + # TODO: We can drop this once we just use a dictionary instead + self.repo_tokens[:] = [ + t for t in self.repo_tokens if t.org_name != org_name + ] + + self.repo_tokens.append(RepoToken(org_name=org_name, token=token)) + + def get_repo_token(self, org_name: OrgName) -> TokenString: + """Return the installed repo token for a specific organization. + + Args: + org_name: The organization name for which to search for a token. + + Returns: + The repo access token associated with the requested organization. + + Raises: + TokenNotFoundError: if no token is found in the keyring for that organization. + + """ + for token in self.repo_tokens: + if token.org_name == org_name: + return token.token + raise TokenNotFoundError(f"Could not find repo token for org {org_name}") + + def delete_repo_token(self, org_name: OrgName) -> None: + """Delete the repo token for a specific organization. + + Args: + org_name: The organization name for which to delete a token. + + """ + # TODO: Confirm whether we should raise an exception or not if token doesn't exist for specified organization + + # We need to remove the existing token for this org first + # TODO: We can drop this once we just use a dictionary instead + self.repo_tokens[:] = [t for t in self.repo_tokens if t.org_name != org_name] + + def delete_all_repo_token(self) -> None: + """Delete all repo tokens""" + + self.repo_tokens[:] = [] diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/utils.py b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..dbffc3d210979ea8bc56b84e48171a31fd94c2c2 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/utils.py @@ -0,0 +1,57 @@ +import base64 +import logging +from hashlib import blake2b +from socket import gethostname +from typing import Optional +from typing import Union + +logger = logging.getLogger(__name__) + + +def get_hostname(hash: bool = False, pepper: Optional[str] = None) -> str: + """ + Return the hostname for the current machine. + + Args: + hash: Whether to hash the hostname. + pepper: Optional pepper for additional security (base64 encoded) + + Returns: + The hostname. + """ + try: + hostname = gethostname() + if not hostname: + logger.info("socket.gethostname returned an empty value") + except Exception as e: + logger.info(f"socket.gethostname raised an exception: {e}") + hostname = "" + + if hostname.endswith(".local"): + hostname = hostname.rsplit(".", 1)[0] + if hash: + hostname = hash_string("hostname", hostname, pepper) + + return hostname + + +def hash_string(what: str, s: str, pepper: Optional[Union[str, bytes]] = None) -> str: + """ + Return the hashed string for the current machine. + + Args: + what: The what to hash (example: "hostname"). + s: The string to hash. + pepper: Optional pepper for additional security (base64 encoded) + + Returns: + Hashed string + """ + if isinstance(pepper, str): + pepper = pepper.encode("utf-8") + pepper = (pepper or b"")[: blake2b.SALT_SIZE] + person = what.encode("utf-8") + hfunc = blake2b(s.encode("utf-8"), digest_size=16, person=person, salt=pepper) # type: ignore + data = hfunc.digest() + result = base64.urlsafe_b64encode(data).strip(b"=").decode("ascii") + return result diff --git a/data/miniconda3/lib/python3.13/site-packages/anyio/__init__.py b/data/miniconda3/lib/python3.13/site-packages/anyio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d23c5a5a27878561b79551da9513cf600dce5005 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anyio/__init__.py @@ -0,0 +1,111 @@ +from __future__ import annotations + +from ._core._contextmanagers import AsyncContextManagerMixin as AsyncContextManagerMixin +from ._core._contextmanagers import ContextManagerMixin as ContextManagerMixin +from ._core._eventloop import current_time as current_time +from ._core._eventloop import get_all_backends as get_all_backends +from ._core._eventloop import get_available_backends as get_available_backends +from ._core._eventloop import get_cancelled_exc_class as get_cancelled_exc_class +from ._core._eventloop import run as run +from ._core._eventloop import sleep as sleep +from ._core._eventloop import sleep_forever as sleep_forever +from ._core._eventloop import sleep_until as sleep_until +from ._core._exceptions import BrokenResourceError as BrokenResourceError +from ._core._exceptions import BrokenWorkerInterpreter as BrokenWorkerInterpreter +from ._core._exceptions import BrokenWorkerProcess as BrokenWorkerProcess +from ._core._exceptions import BusyResourceError as BusyResourceError +from ._core._exceptions import ClosedResourceError as ClosedResourceError +from ._core._exceptions import ConnectionFailed as ConnectionFailed +from ._core._exceptions import DelimiterNotFound as DelimiterNotFound +from ._core._exceptions import EndOfStream as EndOfStream +from ._core._exceptions import IncompleteRead as IncompleteRead +from ._core._exceptions import NoEventLoopError as NoEventLoopError +from ._core._exceptions import RunFinishedError as RunFinishedError +from ._core._exceptions import TypedAttributeLookupError as TypedAttributeLookupError +from ._core._exceptions import WouldBlock as WouldBlock +from ._core._fileio import AsyncFile as AsyncFile +from ._core._fileio import Path as Path +from ._core._fileio import open_file as open_file +from ._core._fileio import wrap_file as wrap_file +from ._core._resources import aclose_forcefully as aclose_forcefully +from ._core._signals import open_signal_receiver as open_signal_receiver +from ._core._sockets import TCPConnectable as TCPConnectable +from ._core._sockets import UNIXConnectable as UNIXConnectable +from ._core._sockets import as_connectable as as_connectable +from ._core._sockets import connect_tcp as connect_tcp +from ._core._sockets import connect_unix as connect_unix +from ._core._sockets import create_connected_udp_socket as create_connected_udp_socket +from ._core._sockets import ( + create_connected_unix_datagram_socket as create_connected_unix_datagram_socket, +) +from ._core._sockets import create_tcp_listener as create_tcp_listener +from ._core._sockets import create_udp_socket as create_udp_socket +from ._core._sockets import create_unix_datagram_socket as create_unix_datagram_socket +from ._core._sockets import create_unix_listener as create_unix_listener +from ._core._sockets import getaddrinfo as getaddrinfo +from ._core._sockets import getnameinfo as getnameinfo +from ._core._sockets import notify_closing as notify_closing +from ._core._sockets import wait_readable as wait_readable +from ._core._sockets import wait_socket_readable as wait_socket_readable +from ._core._sockets import wait_socket_writable as wait_socket_writable +from ._core._sockets import wait_writable as wait_writable +from ._core._streams import create_memory_object_stream as create_memory_object_stream +from ._core._subprocesses import open_process as open_process +from ._core._subprocesses import run_process as run_process +from ._core._synchronization import CapacityLimiter as CapacityLimiter +from ._core._synchronization import ( + CapacityLimiterStatistics as CapacityLimiterStatistics, +) +from ._core._synchronization import Condition as Condition +from ._core._synchronization import ConditionStatistics as ConditionStatistics +from ._core._synchronization import Event as Event +from ._core._synchronization import EventStatistics as EventStatistics +from ._core._synchronization import Lock as Lock +from ._core._synchronization import LockStatistics as LockStatistics +from ._core._synchronization import ResourceGuard as ResourceGuard +from ._core._synchronization import Semaphore as Semaphore +from ._core._synchronization import SemaphoreStatistics as SemaphoreStatistics +from ._core._tasks import TASK_STATUS_IGNORED as TASK_STATUS_IGNORED +from ._core._tasks import CancelScope as CancelScope +from ._core._tasks import create_task_group as create_task_group +from ._core._tasks import current_effective_deadline as current_effective_deadline +from ._core._tasks import fail_after as fail_after +from ._core._tasks import move_on_after as move_on_after +from ._core._tempfile import NamedTemporaryFile as NamedTemporaryFile +from ._core._tempfile import SpooledTemporaryFile as SpooledTemporaryFile +from ._core._tempfile import TemporaryDirectory as TemporaryDirectory +from ._core._tempfile import TemporaryFile as TemporaryFile +from ._core._tempfile import gettempdir as gettempdir +from ._core._tempfile import gettempdirb as gettempdirb +from ._core._tempfile import mkdtemp as mkdtemp +from ._core._tempfile import mkstemp as mkstemp +from ._core._testing import TaskInfo as TaskInfo +from ._core._testing import get_current_task as get_current_task +from ._core._testing import get_running_tasks as get_running_tasks +from ._core._testing import wait_all_tasks_blocked as wait_all_tasks_blocked +from ._core._typedattr import TypedAttributeProvider as TypedAttributeProvider +from ._core._typedattr import TypedAttributeSet as TypedAttributeSet +from ._core._typedattr import typed_attribute as typed_attribute + +# Re-export imports so they look like they live directly in this package +for __value in list(locals().values()): + if getattr(__value, "__module__", "").startswith("anyio."): + __value.__module__ = __name__ + + +del __value + + +def __getattr__(attr: str) -> type[BrokenWorkerInterpreter]: + """Support deprecated aliases.""" + if attr == "BrokenWorkerIntepreter": + import warnings + + warnings.warn( + "The 'BrokenWorkerIntepreter' alias is deprecated, use 'BrokenWorkerInterpreter' instead.", + DeprecationWarning, + stacklevel=2, + ) + return BrokenWorkerInterpreter + + raise AttributeError(f"module {__name__!r} has no attribute {attr!r}") diff --git a/data/miniconda3/lib/python3.13/site-packages/anyio/from_thread.py b/data/miniconda3/lib/python3.13/site-packages/anyio/from_thread.py new file mode 100644 index 0000000000000000000000000000000000000000..837de5e96715b6ba324d156e9f4a2432a7ccf27d --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anyio/from_thread.py @@ -0,0 +1,578 @@ +from __future__ import annotations + +__all__ = ( + "BlockingPortal", + "BlockingPortalProvider", + "check_cancelled", + "run", + "run_sync", + "start_blocking_portal", +) + +import sys +from collections.abc import Awaitable, Callable, Generator +from concurrent.futures import Future +from contextlib import ( + AbstractAsyncContextManager, + AbstractContextManager, + contextmanager, +) +from dataclasses import dataclass, field +from functools import partial +from inspect import isawaitable +from threading import Lock, Thread, current_thread, get_ident +from types import TracebackType +from typing import ( + Any, + Generic, + TypeVar, + cast, + overload, +) + +from ._core._eventloop import ( + get_cancelled_exc_class, + threadlocals, +) +from ._core._eventloop import run as run_eventloop +from ._core._exceptions import NoEventLoopError +from ._core._synchronization import Event +from ._core._tasks import CancelScope, create_task_group +from .abc._tasks import TaskStatus +from .lowlevel import EventLoopToken, current_token + +if sys.version_info >= (3, 11): + from typing import TypeVarTuple, Unpack +else: + from typing_extensions import TypeVarTuple, Unpack + +T_Retval = TypeVar("T_Retval") +T_co = TypeVar("T_co", covariant=True) +PosArgsT = TypeVarTuple("PosArgsT") + + +def _token_or_error(token: EventLoopToken | None) -> EventLoopToken: + if token is not None: + return token + + try: + return threadlocals.current_token + except AttributeError: + raise NoEventLoopError( + "Not running inside an AnyIO worker thread, and no event loop token was " + "provided" + ) from None + + +def run( + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], + *args: Unpack[PosArgsT], + token: EventLoopToken | None = None, +) -> T_Retval: + """ + Call a coroutine function from a worker thread. + + :param func: a coroutine function + :param args: positional arguments for the callable + :param token: an event loop token to use to get back to the event loop thread + (required if calling this function from outside an AnyIO worker thread) + :return: the return value of the coroutine function + :raises MissingTokenError: if no token was provided and called from outside an + AnyIO worker thread + :raises RunFinishedError: if the event loop tied to ``token`` is no longer running + + .. versionchanged:: 4.11.0 + Added the ``token`` parameter. + + """ + explicit_token = token is not None + token = _token_or_error(token) + return token.backend_class.run_async_from_thread( + func, args, token=token.native_token if explicit_token else None + ) + + +def run_sync( + func: Callable[[Unpack[PosArgsT]], T_Retval], + *args: Unpack[PosArgsT], + token: EventLoopToken | None = None, +) -> T_Retval: + """ + Call a function in the event loop thread from a worker thread. + + :param func: a callable + :param args: positional arguments for the callable + :param token: an event loop token to use to get back to the event loop thread + (required if calling this function from outside an AnyIO worker thread) + :return: the return value of the callable + :raises MissingTokenError: if no token was provided and called from outside an + AnyIO worker thread + :raises RunFinishedError: if the event loop tied to ``token`` is no longer running + + .. versionchanged:: 4.11.0 + Added the ``token`` parameter. + + """ + explicit_token = token is not None + token = _token_or_error(token) + return token.backend_class.run_sync_from_thread( + func, args, token=token.native_token if explicit_token else None + ) + + +class _BlockingAsyncContextManager(Generic[T_co], AbstractContextManager): + _enter_future: Future[T_co] + _exit_future: Future[bool | None] + _exit_event: Event + _exit_exc_info: tuple[ + type[BaseException] | None, BaseException | None, TracebackType | None + ] = (None, None, None) + + def __init__( + self, async_cm: AbstractAsyncContextManager[T_co], portal: BlockingPortal + ): + self._async_cm = async_cm + self._portal = portal + + async def run_async_cm(self) -> bool | None: + try: + self._exit_event = Event() + value = await self._async_cm.__aenter__() + except BaseException as exc: + self._enter_future.set_exception(exc) + raise + else: + self._enter_future.set_result(value) + + try: + # Wait for the sync context manager to exit. + # This next statement can raise `get_cancelled_exc_class()` if + # something went wrong in a task group in this async context + # manager. + await self._exit_event.wait() + finally: + # In case of cancellation, it could be that we end up here before + # `_BlockingAsyncContextManager.__exit__` is called, and an + # `_exit_exc_info` has been set. + result = await self._async_cm.__aexit__(*self._exit_exc_info) + + return result + + def __enter__(self) -> T_co: + self._enter_future = Future() + self._exit_future = self._portal.start_task_soon(self.run_async_cm) + return self._enter_future.result() + + def __exit__( + self, + __exc_type: type[BaseException] | None, + __exc_value: BaseException | None, + __traceback: TracebackType | None, + ) -> bool | None: + self._exit_exc_info = __exc_type, __exc_value, __traceback + self._portal.call(self._exit_event.set) + return self._exit_future.result() + + +class _BlockingPortalTaskStatus(TaskStatus): + def __init__(self, future: Future): + self._future = future + + def started(self, value: object = None) -> None: + self._future.set_result(value) + + +class BlockingPortal: + """ + An object that lets external threads run code in an asynchronous event loop. + + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + """ + + def __init__(self) -> None: + self._token = current_token() + self._event_loop_thread_id: int | None = get_ident() + self._stop_event = Event() + self._task_group = create_task_group() + + async def __aenter__(self) -> BlockingPortal: + await self._task_group.__aenter__() + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> bool: + await self.stop() + return await self._task_group.__aexit__(exc_type, exc_val, exc_tb) + + def _check_running(self) -> None: + if self._event_loop_thread_id is None: + raise RuntimeError("This portal is not running") + if self._event_loop_thread_id == get_ident(): + raise RuntimeError( + "This method cannot be called from the event loop thread" + ) + + async def sleep_until_stopped(self) -> None: + """Sleep until :meth:`stop` is called.""" + await self._stop_event.wait() + + async def stop(self, cancel_remaining: bool = False) -> None: + """ + Signal the portal to shut down. + + This marks the portal as no longer accepting new calls and exits from + :meth:`sleep_until_stopped`. + + :param cancel_remaining: ``True`` to cancel all the remaining tasks, ``False`` + to let them finish before returning + + """ + self._event_loop_thread_id = None + self._stop_event.set() + if cancel_remaining: + self._task_group.cancel_scope.cancel("the blocking portal is shutting down") + + async def _call_func( + self, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval] | T_Retval], + args: tuple[Unpack[PosArgsT]], + kwargs: dict[str, Any], + future: Future[T_Retval], + ) -> None: + def callback(f: Future[T_Retval]) -> None: + if f.cancelled(): + if self._event_loop_thread_id == get_ident(): + scope.cancel("the future was cancelled") + elif self._event_loop_thread_id is not None: + self.call(scope.cancel, "the future was cancelled") + + try: + retval_or_awaitable = func(*args, **kwargs) + if isawaitable(retval_or_awaitable): + with CancelScope() as scope: + future.add_done_callback(callback) + retval = await retval_or_awaitable + else: + retval = retval_or_awaitable + except get_cancelled_exc_class(): + future.cancel() + future.set_running_or_notify_cancel() + except BaseException as exc: + if not future.cancelled(): + future.set_exception(exc) + + # Let base exceptions fall through + if not isinstance(exc, Exception): + raise + else: + if not future.cancelled(): + future.set_result(retval) + finally: + scope = None # type: ignore[assignment] + + def _spawn_task_from_thread( + self, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval] | T_Retval], + args: tuple[Unpack[PosArgsT]], + kwargs: dict[str, Any], + name: object, + future: Future[T_Retval], + ) -> None: + """ + Spawn a new task using the given callable. + + :param func: a callable + :param args: positional arguments to be passed to the callable + :param kwargs: keyword arguments to be passed to the callable + :param name: name of the task (will be coerced to a string if not ``None``) + :param future: a future that will resolve to the return value of the callable, + or the exception raised during its execution + + """ + run_sync( + partial(self._task_group.start_soon, name=name), + self._call_func, + func, + args, + kwargs, + future, + token=self._token, + ) + + @overload + def call( + self, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], + *args: Unpack[PosArgsT], + ) -> T_Retval: ... + + @overload + def call( + self, func: Callable[[Unpack[PosArgsT]], T_Retval], *args: Unpack[PosArgsT] + ) -> T_Retval: ... + + def call( + self, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval] | T_Retval], + *args: Unpack[PosArgsT], + ) -> T_Retval: + """ + Call the given function in the event loop thread. + + If the callable returns a coroutine object, it is awaited on. + + :param func: any callable + :raises RuntimeError: if the portal is not running or if this method is called + from within the event loop thread + + """ + return cast(T_Retval, self.start_task_soon(func, *args).result()) + + @overload + def start_task_soon( + self, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], + *args: Unpack[PosArgsT], + name: object = None, + ) -> Future[T_Retval]: ... + + @overload + def start_task_soon( + self, + func: Callable[[Unpack[PosArgsT]], T_Retval], + *args: Unpack[PosArgsT], + name: object = None, + ) -> Future[T_Retval]: ... + + def start_task_soon( + self, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval] | T_Retval], + *args: Unpack[PosArgsT], + name: object = None, + ) -> Future[T_Retval]: + """ + Start a task in the portal's task group. + + The task will be run inside a cancel scope which can be cancelled by cancelling + the returned future. + + :param func: the target function + :param args: positional arguments passed to ``func`` + :param name: name of the task (will be coerced to a string if not ``None``) + :return: a future that resolves with the return value of the callable if the + task completes successfully, or with the exception raised in the task + :raises RuntimeError: if the portal is not running or if this method is called + from within the event loop thread + :rtype: concurrent.futures.Future[T_Retval] + + .. versionadded:: 3.0 + + """ + self._check_running() + f: Future[T_Retval] = Future() + self._spawn_task_from_thread(func, args, {}, name, f) + return f + + def start_task( + self, + func: Callable[..., Awaitable[T_Retval]], + *args: object, + name: object = None, + ) -> tuple[Future[T_Retval], Any]: + """ + Start a task in the portal's task group and wait until it signals for readiness. + + This method works the same way as :meth:`.abc.TaskGroup.start`. + + :param func: the target function + :param args: positional arguments passed to ``func`` + :param name: name of the task (will be coerced to a string if not ``None``) + :return: a tuple of (future, task_status_value) where the ``task_status_value`` + is the value passed to ``task_status.started()`` from within the target + function + :rtype: tuple[concurrent.futures.Future[T_Retval], Any] + + .. versionadded:: 3.0 + + """ + + def task_done(future: Future[T_Retval]) -> None: + if not task_status_future.done(): + if future.cancelled(): + task_status_future.cancel() + elif future.exception(): + task_status_future.set_exception(future.exception()) + else: + exc = RuntimeError( + "Task exited without calling task_status.started()" + ) + task_status_future.set_exception(exc) + + self._check_running() + task_status_future: Future = Future() + task_status = _BlockingPortalTaskStatus(task_status_future) + f: Future = Future() + f.add_done_callback(task_done) + self._spawn_task_from_thread(func, args, {"task_status": task_status}, name, f) + return f, task_status_future.result() + + def wrap_async_context_manager( + self, cm: AbstractAsyncContextManager[T_co] + ) -> AbstractContextManager[T_co]: + """ + Wrap an async context manager as a synchronous context manager via this portal. + + Spawns a task that will call both ``__aenter__()`` and ``__aexit__()``, stopping + in the middle until the synchronous context manager exits. + + :param cm: an asynchronous context manager + :return: a synchronous context manager + + .. versionadded:: 2.1 + + """ + return _BlockingAsyncContextManager(cm, self) + + +@dataclass +class BlockingPortalProvider: + """ + A manager for a blocking portal. Used as a context manager. The first thread to + enter this context manager causes a blocking portal to be started with the specific + parameters, and the last thread to exit causes the portal to be shut down. Thus, + there will be exactly one blocking portal running in this context as long as at + least one thread has entered this context manager. + + The parameters are the same as for :func:`~anyio.run`. + + :param backend: name of the backend + :param backend_options: backend options + + .. versionadded:: 4.4 + """ + + backend: str = "asyncio" + backend_options: dict[str, Any] | None = None + _lock: Lock = field(init=False, default_factory=Lock) + _leases: int = field(init=False, default=0) + _portal: BlockingPortal = field(init=False) + _portal_cm: AbstractContextManager[BlockingPortal] | None = field( + init=False, default=None + ) + + def __enter__(self) -> BlockingPortal: + with self._lock: + if self._portal_cm is None: + self._portal_cm = start_blocking_portal( + self.backend, self.backend_options + ) + self._portal = self._portal_cm.__enter__() + + self._leases += 1 + return self._portal + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + portal_cm: AbstractContextManager[BlockingPortal] | None = None + with self._lock: + assert self._portal_cm + assert self._leases > 0 + self._leases -= 1 + if not self._leases: + portal_cm = self._portal_cm + self._portal_cm = None + del self._portal + + if portal_cm: + portal_cm.__exit__(None, None, None) + + +@contextmanager +def start_blocking_portal( + backend: str = "asyncio", + backend_options: dict[str, Any] | None = None, + *, + name: str | None = None, +) -> Generator[BlockingPortal, Any, None]: + """ + Start a new event loop in a new thread and run a blocking portal in its main task. + + The parameters are the same as for :func:`~anyio.run`. + + :param backend: name of the backend + :param backend_options: backend options + :param name: name of the thread + :return: a context manager that yields a blocking portal + + .. versionchanged:: 3.0 + Usage as a context manager is now required. + + """ + + async def run_portal() -> None: + async with BlockingPortal() as portal_: + if name is None: + current_thread().name = f"{backend}-portal-{id(portal_):x}" + + future.set_result(portal_) + await portal_.sleep_until_stopped() + + def run_blocking_portal() -> None: + if future.set_running_or_notify_cancel(): + try: + run_eventloop( + run_portal, backend=backend, backend_options=backend_options + ) + except BaseException as exc: + if not future.done(): + future.set_exception(exc) + + future: Future[BlockingPortal] = Future() + thread = Thread(target=run_blocking_portal, daemon=True, name=name) + thread.start() + try: + cancel_remaining_tasks = False + portal = future.result() + try: + yield portal + except BaseException: + cancel_remaining_tasks = True + raise + finally: + try: + portal.call(portal.stop, cancel_remaining_tasks) + except RuntimeError: + pass + finally: + thread.join() + + +def check_cancelled() -> None: + """ + Check if the cancel scope of the host task's running the current worker thread has + been cancelled. + + If the host task's current cancel scope has indeed been cancelled, the + backend-specific cancellation exception will be raised. + + :raises RuntimeError: if the current thread was not spawned by + :func:`.to_thread.run_sync` + + """ + try: + token: EventLoopToken = threadlocals.current_token + except AttributeError: + raise NoEventLoopError( + "This function can only be called inside an AnyIO worker thread" + ) from None + + token.backend_class.check_cancelled() diff --git a/data/miniconda3/lib/python3.13/site-packages/anyio/functools.py b/data/miniconda3/lib/python3.13/site-packages/anyio/functools.py new file mode 100644 index 0000000000000000000000000000000000000000..f1d6c7c55c17b041f0b010dca5a4b8f1bcb5da7a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anyio/functools.py @@ -0,0 +1,409 @@ +from __future__ import annotations + +__all__ = ( + "AsyncCacheInfo", + "AsyncCacheParameters", + "AsyncLRUCacheWrapper", + "cache", + "lru_cache", + "reduce", +) + +import functools +import sys +from collections import OrderedDict +from collections.abc import ( + AsyncIterable, + Awaitable, + Callable, + Coroutine, + Hashable, + Iterable, +) +from functools import update_wrapper +from inspect import iscoroutinefunction +from typing import ( + Any, + Generic, + NamedTuple, + TypedDict, + TypeVar, + cast, + final, + overload, +) +from weakref import WeakKeyDictionary + +from ._core._eventloop import current_time +from ._core._synchronization import Lock +from .lowlevel import RunVar, checkpoint + +if sys.version_info >= (3, 11): + from typing import ParamSpec +else: + from typing_extensions import ParamSpec + +T = TypeVar("T") +S = TypeVar("S") +P = ParamSpec("P") +lru_cache_items: RunVar[ + WeakKeyDictionary[ + AsyncLRUCacheWrapper[Any, Any], + OrderedDict[ + Hashable, + tuple[_InitialMissingType, Lock, float | None] + | tuple[Any, None, float | None], + ], + ] +] = RunVar("lru_cache_items") + + +class _InitialMissingType: + pass + + +initial_missing: _InitialMissingType = _InitialMissingType() + + +class AsyncCacheInfo(NamedTuple): + hits: int + misses: int + maxsize: int | None + currsize: int + ttl: int | None + + +class AsyncCacheParameters(TypedDict): + maxsize: int | None + typed: bool + always_checkpoint: bool + ttl: int | None + + +class _LRUMethodWrapper(Generic[T]): + def __init__(self, wrapper: AsyncLRUCacheWrapper[..., T], instance: object): + self.__wrapper = wrapper + self.__instance = instance + + def cache_info(self) -> AsyncCacheInfo: + return self.__wrapper.cache_info() + + def cache_parameters(self) -> AsyncCacheParameters: + return self.__wrapper.cache_parameters() + + def cache_clear(self) -> None: + self.__wrapper.cache_clear() + + async def __call__(self, *args: Any, **kwargs: Any) -> T: + if self.__instance is None: + return await self.__wrapper(*args, **kwargs) + + return await self.__wrapper(self.__instance, *args, **kwargs) + + +@final +class AsyncLRUCacheWrapper(Generic[P, T]): + def __init__( + self, + func: Callable[P, Awaitable[T]], + maxsize: int | None, + typed: bool, + always_checkpoint: bool, + ttl: int | None, + ): + self.__wrapped__ = func + self._hits: int = 0 + self._misses: int = 0 + self._maxsize = max(maxsize, 0) if maxsize is not None else None + self._currsize: int = 0 + self._typed = typed + self._always_checkpoint = always_checkpoint + self._ttl = ttl + update_wrapper(self, func) + + def cache_info(self) -> AsyncCacheInfo: + return AsyncCacheInfo( + self._hits, self._misses, self._maxsize, self._currsize, self._ttl + ) + + def cache_parameters(self) -> AsyncCacheParameters: + return { + "maxsize": self._maxsize, + "typed": self._typed, + "always_checkpoint": self._always_checkpoint, + "ttl": self._ttl, + } + + def cache_clear(self) -> None: + if cache := lru_cache_items.get(None): + cache.pop(self, None) + self._hits = self._misses = self._currsize = 0 + + async def __call__(self, *args: P.args, **kwargs: P.kwargs) -> T: + # Easy case first: if maxsize == 0, no caching is done + if self._maxsize == 0: + value = await self.__wrapped__(*args, **kwargs) + self._misses += 1 + return value + + # The key is constructed as a flat tuple to avoid memory overhead + key: tuple[Any, ...] = args + if kwargs: + # initial_missing is used as a separator + key += (initial_missing,) + sum(kwargs.items(), ()) + + if self._typed: + key += tuple(type(arg) for arg in args) + if kwargs: + key += (initial_missing,) + tuple(type(val) for val in kwargs.values()) + + try: + cache = lru_cache_items.get() + except LookupError: + cache = WeakKeyDictionary() + lru_cache_items.set(cache) + + try: + cache_entry = cache[self] + except KeyError: + cache_entry = cache[self] = OrderedDict() + + cached_value: T | _InitialMissingType + try: + cached_value, lock, expires_at = cache_entry[key] + except KeyError: + # We're the first task to call this function + cached_value, lock, expires_at = ( + initial_missing, + Lock(fast_acquire=not self._always_checkpoint), + None, + ) + cache_entry[key] = cached_value, lock, expires_at + + if lock is None: + if expires_at is not None and current_time() >= expires_at: + self._currsize -= 1 + cached_value, lock, expires_at = ( + initial_missing, + Lock(fast_acquire=not self._always_checkpoint), + None, + ) + cache_entry[key] = cached_value, lock, expires_at + else: + # The value was already cached + self._hits += 1 + cache_entry.move_to_end(key) + if self._always_checkpoint: + await checkpoint() + + return cast(T, cached_value) + + async with lock: + # Check if another task filled the cache while we acquired the lock + if (cached_value := cache_entry[key][0]) is initial_missing: + self._misses += 1 + if self._maxsize is not None and self._currsize >= self._maxsize: + cache_entry.popitem(last=False) + else: + self._currsize += 1 + + value = await self.__wrapped__(*args, **kwargs) + expires_at = ( + current_time() + self._ttl if self._ttl is not None else None + ) + cache_entry[key] = value, None, expires_at + else: + # Another task filled the cache while we were waiting for the lock + self._hits += 1 + cache_entry.move_to_end(key) + value = cast(T, cached_value) + + return value + + def __get__( + self, instance: object, owner: type | None = None + ) -> _LRUMethodWrapper[T]: + wrapper = _LRUMethodWrapper(self, instance) + update_wrapper(wrapper, self.__wrapped__) + return wrapper + + +class _LRUCacheWrapper(Generic[T]): + def __init__( + self, maxsize: int | None, typed: bool, always_checkpoint: bool, ttl: int | None + ): + self._maxsize = maxsize + self._typed = typed + self._always_checkpoint = always_checkpoint + self._ttl = ttl + + @overload + def __call__( # type: ignore[overload-overlap] + self, func: Callable[P, Coroutine[Any, Any, T]], / + ) -> AsyncLRUCacheWrapper[P, T]: ... + + @overload + def __call__( + self, func: Callable[..., T], / + ) -> functools._lru_cache_wrapper[T]: ... + + def __call__( + self, f: Callable[P, Coroutine[Any, Any, T]] | Callable[..., T], / + ) -> AsyncLRUCacheWrapper[P, T] | functools._lru_cache_wrapper[T]: + if iscoroutinefunction(f): + return AsyncLRUCacheWrapper( + f, self._maxsize, self._typed, self._always_checkpoint, self._ttl + ) + + return functools.lru_cache(maxsize=self._maxsize, typed=self._typed)(f) # type: ignore[arg-type] + + +@overload +def cache( # type: ignore[overload-overlap] + func: Callable[P, Coroutine[Any, Any, T]], / +) -> AsyncLRUCacheWrapper[P, T]: ... + + +@overload +def cache(func: Callable[..., T], /) -> functools._lru_cache_wrapper[T]: ... + + +def cache( + func: Callable[..., T] | Callable[P, Coroutine[Any, Any, T]], / +) -> AsyncLRUCacheWrapper[P, T] | functools._lru_cache_wrapper[T]: + """ + A convenient shortcut for :func:`lru_cache` with ``maxsize=None``. + + This is the asynchronous equivalent to :func:`functools.cache`. + + """ + return lru_cache(maxsize=None)(func) + + +@overload +def lru_cache( + *, + maxsize: int | None = ..., + typed: bool = ..., + always_checkpoint: bool = ..., + ttl: int | None = ..., +) -> _LRUCacheWrapper[Any]: ... + + +@overload +def lru_cache( # type: ignore[overload-overlap] + func: Callable[P, Coroutine[Any, Any, T]], / +) -> AsyncLRUCacheWrapper[P, T]: ... + + +@overload +def lru_cache(func: Callable[..., T], /) -> functools._lru_cache_wrapper[T]: ... + + +def lru_cache( + func: Callable[P, Coroutine[Any, Any, T]] | Callable[..., T] | None = None, + /, + *, + maxsize: int | None = 128, + typed: bool = False, + always_checkpoint: bool = False, + ttl: int | None = None, +) -> ( + AsyncLRUCacheWrapper[P, T] | functools._lru_cache_wrapper[T] | _LRUCacheWrapper[Any] +): + """ + An asynchronous version of :func:`functools.lru_cache`. + + If a synchronous function is passed, the standard library + :func:`functools.lru_cache` is applied instead. + + :param always_checkpoint: if ``True``, every call to the cached function will be + guaranteed to yield control to the event loop at least once + :param ttl: time in seconds after which to invalidate cache entries + + .. note:: Caches and locks are managed on a per-event loop basis. + + """ + if func is None: + return _LRUCacheWrapper[Any](maxsize, typed, always_checkpoint, ttl) + + if not callable(func): + raise TypeError("the first argument must be callable") + + return _LRUCacheWrapper[T](maxsize, typed, always_checkpoint, ttl)(func) + + +@overload +async def reduce( + function: Callable[[T, S], Awaitable[T]], + iterable: Iterable[S] | AsyncIterable[S], + /, + initial: T, +) -> T: ... + + +@overload +async def reduce( + function: Callable[[T, T], Awaitable[T]], + iterable: Iterable[T] | AsyncIterable[T], + /, +) -> T: ... + + +async def reduce( # type: ignore[misc] + function: Callable[[T, T], Awaitable[T]] | Callable[[T, S], Awaitable[T]], + iterable: Iterable[T] | Iterable[S] | AsyncIterable[T] | AsyncIterable[S], + /, + initial: T | _InitialMissingType = initial_missing, +) -> T: + """ + Asynchronous version of :func:`functools.reduce`. + + :param function: a coroutine function that takes two arguments: the accumulated + value and the next element from the iterable + :param iterable: an iterable or async iterable + :param initial: the initial value (if missing, the first element of the iterable is + used as the initial value) + + """ + element: Any + function_called = False + if isinstance(iterable, AsyncIterable): + async_it = iterable.__aiter__() + if initial is initial_missing: + try: + value = cast(T, await async_it.__anext__()) + except StopAsyncIteration: + raise TypeError( + "reduce() of empty sequence with no initial value" + ) from None + else: + value = cast(T, initial) + + async for element in async_it: + value = await function(value, element) + function_called = True + elif isinstance(iterable, Iterable): + it = iter(iterable) + if initial is initial_missing: + try: + value = cast(T, next(it)) + except StopIteration: + raise TypeError( + "reduce() of empty sequence with no initial value" + ) from None + else: + value = cast(T, initial) + + for element in it: + value = await function(value, element) + function_called = True + else: + raise TypeError("reduce() argument 2 must be an iterable or async iterable") + + # Make sure there is at least one checkpoint, even if an empty iterable and an + # initial value were given + if not function_called: + await checkpoint() + + return value diff --git a/data/miniconda3/lib/python3.13/site-packages/anyio/lowlevel.py b/data/miniconda3/lib/python3.13/site-packages/anyio/lowlevel.py new file mode 100644 index 0000000000000000000000000000000000000000..ffbb75a7079aa4b1a13318641c1e1299e7bc1827 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anyio/lowlevel.py @@ -0,0 +1,196 @@ +from __future__ import annotations + +__all__ = ( + "EventLoopToken", + "RunvarToken", + "RunVar", + "checkpoint", + "checkpoint_if_cancelled", + "cancel_shielded_checkpoint", + "current_token", +) + +import enum +from dataclasses import dataclass +from types import TracebackType +from typing import Any, Generic, Literal, TypeVar, final, overload +from weakref import WeakKeyDictionary + +from ._core._eventloop import get_async_backend +from .abc import AsyncBackend + +T = TypeVar("T") +D = TypeVar("D") + + +async def checkpoint() -> None: + """ + Check for cancellation and allow the scheduler to switch to another task. + + Equivalent to (but more efficient than):: + + await checkpoint_if_cancelled() + await cancel_shielded_checkpoint() + + .. versionadded:: 3.0 + + """ + await get_async_backend().checkpoint() + + +async def checkpoint_if_cancelled() -> None: + """ + Enter a checkpoint if the enclosing cancel scope has been cancelled. + + This does not allow the scheduler to switch to a different task. + + .. versionadded:: 3.0 + + """ + await get_async_backend().checkpoint_if_cancelled() + + +async def cancel_shielded_checkpoint() -> None: + """ + Allow the scheduler to switch to another task but without checking for cancellation. + + Equivalent to (but potentially more efficient than):: + + with CancelScope(shield=True): + await checkpoint() + + .. versionadded:: 3.0 + + """ + await get_async_backend().cancel_shielded_checkpoint() + + +@final +@dataclass(frozen=True, repr=False) +class EventLoopToken: + """ + An opaque object that holds a reference to an event loop. + + .. versionadded:: 4.11.0 + """ + + backend_class: type[AsyncBackend] + native_token: object + + +def current_token() -> EventLoopToken: + """ + Return a token object that can be used to call code in the current event loop from + another thread. + + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + + .. versionadded:: 4.11.0 + + """ + backend_class = get_async_backend() + raw_token = backend_class.current_token() + return EventLoopToken(backend_class, raw_token) + + +_run_vars: WeakKeyDictionary[object, dict[RunVar[Any], Any]] = WeakKeyDictionary() + + +class _NoValueSet(enum.Enum): + NO_VALUE_SET = enum.auto() + + +class RunvarToken(Generic[T]): + __slots__ = "_var", "_value", "_redeemed" + + def __init__(self, var: RunVar[T], value: T | Literal[_NoValueSet.NO_VALUE_SET]): + self._var = var + self._value: T | Literal[_NoValueSet.NO_VALUE_SET] = value + self._redeemed = False + + def __enter__(self) -> RunvarToken[T]: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self._var.reset(self) + + +class RunVar(Generic[T]): + """ + Like a :class:`~contextvars.ContextVar`, except scoped to the running event loop. + + Can be used as a context manager, Just like :class:`~contextvars.ContextVar`, that + will reset the variable to its previous value when the context block is exited. + """ + + __slots__ = "_name", "_default" + + NO_VALUE_SET: Literal[_NoValueSet.NO_VALUE_SET] = _NoValueSet.NO_VALUE_SET + + def __init__( + self, name: str, default: T | Literal[_NoValueSet.NO_VALUE_SET] = NO_VALUE_SET + ): + self._name = name + self._default = default + + @property + def _current_vars(self) -> dict[RunVar[T], T]: + native_token = current_token().native_token + try: + return _run_vars[native_token] + except KeyError: + run_vars = _run_vars[native_token] = {} + return run_vars + + @overload + def get(self, default: D) -> T | D: ... + + @overload + def get(self) -> T: ... + + def get( + self, default: D | Literal[_NoValueSet.NO_VALUE_SET] = NO_VALUE_SET + ) -> T | D: + try: + return self._current_vars[self] + except KeyError: + if default is not RunVar.NO_VALUE_SET: + return default + elif self._default is not RunVar.NO_VALUE_SET: + return self._default + + raise LookupError( + f'Run variable "{self._name}" has no value and no default set' + ) + + def set(self, value: T) -> RunvarToken[T]: + current_vars = self._current_vars + token = RunvarToken(self, current_vars.get(self, RunVar.NO_VALUE_SET)) + current_vars[self] = value + return token + + def reset(self, token: RunvarToken[T]) -> None: + if token._var is not self: + raise ValueError("This token does not belong to this RunVar") + + if token._redeemed: + raise ValueError("This token has already been used") + + if token._value is _NoValueSet.NO_VALUE_SET: + try: + del self._current_vars[self] + except KeyError: + pass + else: + self._current_vars[self] = token._value + + token._redeemed = True + + def __repr__(self) -> str: + return f"" diff --git a/data/miniconda3/lib/python3.13/site-packages/anyio/py.typed b/data/miniconda3/lib/python3.13/site-packages/anyio/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/lib/python3.13/site-packages/anyio/pytest_plugin.py b/data/miniconda3/lib/python3.13/site-packages/anyio/pytest_plugin.py new file mode 100644 index 0000000000000000000000000000000000000000..a5183f0c84590ca912ac08b61e9f9eb676fc01e3 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anyio/pytest_plugin.py @@ -0,0 +1,363 @@ +from __future__ import annotations + +import dataclasses +import socket +import sys +from collections.abc import Callable, Generator, Iterator +from contextlib import ExitStack, contextmanager +from inspect import isasyncgenfunction, iscoroutinefunction, ismethod +from typing import Any, cast + +import pytest +from _pytest.fixtures import FuncFixtureInfo, SubRequest +from _pytest.outcomes import Exit +from _pytest.python import CallSpec2 +from _pytest.scope import Scope + +from . import get_available_backends +from ._core._eventloop import ( + current_async_library, + get_async_backend, + reset_current_async_library, + set_current_async_library, +) +from ._core._exceptions import iterate_exceptions +from .abc import TestRunner + +if sys.version_info < (3, 11): + from exceptiongroup import ExceptionGroup + +_current_runner: TestRunner | None = None +_runner_stack: ExitStack | None = None +_runner_leases = 0 + + +def extract_backend_and_options(backend: object) -> tuple[str, dict[str, Any]]: + if isinstance(backend, str): + return backend, {} + elif isinstance(backend, tuple) and len(backend) == 2: + if isinstance(backend[0], str) and isinstance(backend[1], dict): + return cast(tuple[str, dict[str, Any]], backend) + + raise TypeError("anyio_backend must be either a string or tuple of (string, dict)") + + +@contextmanager +def get_runner( + backend_name: str, backend_options: dict[str, Any] +) -> Iterator[TestRunner]: + global _current_runner, _runner_leases, _runner_stack + if _current_runner is None: + asynclib = get_async_backend(backend_name) + _runner_stack = ExitStack() + if current_async_library() is None: + # Since we're in control of the event loop, we can cache the name of the + # async library + token = set_current_async_library(backend_name) + _runner_stack.callback(reset_current_async_library, token) + + backend_options = backend_options or {} + _current_runner = _runner_stack.enter_context( + asynclib.create_test_runner(backend_options) + ) + + _runner_leases += 1 + try: + yield _current_runner + finally: + _runner_leases -= 1 + if not _runner_leases: + assert _runner_stack is not None + _runner_stack.close() + _runner_stack = _current_runner = None + + +def pytest_addoption(parser: pytest.Parser) -> None: + parser.addini( + "anyio_mode", + default="strict", + help='AnyIO plugin mode (either "strict" or "auto")', + ) + + +def pytest_configure(config: pytest.Config) -> None: + config.addinivalue_line( + "markers", + "anyio: mark the (coroutine function) test to be run asynchronously via anyio.", + ) + if ( + config.getini("anyio_mode") == "auto" + and config.pluginmanager.has_plugin("asyncio") + and config.getini("asyncio_mode") == "auto" + ): + config.issue_config_time_warning( + pytest.PytestConfigWarning( + "AnyIO auto mode has been enabled together with pytest-asyncio auto " + "mode. This may cause unexpected behavior." + ), + 1, + ) + + +@pytest.hookimpl(hookwrapper=True) +def pytest_fixture_setup(fixturedef: Any, request: Any) -> Generator[Any]: + def wrapper(anyio_backend: Any, request: SubRequest, **kwargs: Any) -> Any: + # Rebind any fixture methods to the request instance + if ( + request.instance + and ismethod(func) + and type(func.__self__) is type(request.instance) + ): + local_func = func.__func__.__get__(request.instance) + else: + local_func = func + + backend_name, backend_options = extract_backend_and_options(anyio_backend) + if has_backend_arg: + kwargs["anyio_backend"] = anyio_backend + + if has_request_arg: + kwargs["request"] = request + + with get_runner(backend_name, backend_options) as runner: + if isasyncgenfunction(local_func): + yield from runner.run_asyncgen_fixture(local_func, kwargs) + else: + yield runner.run_fixture(local_func, kwargs) + + # Only apply this to coroutine functions and async generator functions in requests + # that involve the anyio_backend fixture + func = fixturedef.func + if isasyncgenfunction(func) or iscoroutinefunction(func): + if "anyio_backend" in request.fixturenames: + fixturedef.func = wrapper + original_argname = fixturedef.argnames + + if not (has_backend_arg := "anyio_backend" in fixturedef.argnames): + fixturedef.argnames += ("anyio_backend",) + + if not (has_request_arg := "request" in fixturedef.argnames): + fixturedef.argnames += ("request",) + + try: + return (yield) + finally: + fixturedef.func = func + fixturedef.argnames = original_argname + + return (yield) + + +@pytest.hookimpl(tryfirst=True) +def pytest_pycollect_makeitem( + collector: pytest.Module | pytest.Class, name: str, obj: object +) -> None: + if collector.istestfunction(obj, name): + inner_func = obj.hypothesis.inner_test if hasattr(obj, "hypothesis") else obj + if iscoroutinefunction(inner_func): + anyio_auto_mode = collector.config.getini("anyio_mode") == "auto" + marker = collector.get_closest_marker("anyio") + own_markers = getattr(obj, "pytestmark", ()) + if ( + anyio_auto_mode + or marker + or any(marker.name == "anyio" for marker in own_markers) + ): + pytest.mark.usefixtures("anyio_backend")(obj) + + +def pytest_collection_finish(session: pytest.Session) -> None: + for i, item in reversed(list(enumerate(session.items))): + if ( + isinstance(item, pytest.Function) + and iscoroutinefunction(item.function) + and item.get_closest_marker("anyio") is not None + and "anyio_backend" not in item.fixturenames + ): + new_items = [] + try: + cs_fields = {f.name for f in dataclasses.fields(CallSpec2)} + except TypeError: + cs_fields = set() + + for param_index, backend in enumerate(get_available_backends()): + if "_arg2scope" in cs_fields: # pytest >= 8 + callspec = CallSpec2( + params={"anyio_backend": backend}, + indices={"anyio_backend": param_index}, + _arg2scope={"anyio_backend": Scope.Module}, + _idlist=[backend], + marks=[], + ) + else: # pytest 7.x + callspec = CallSpec2( # type: ignore[call-arg] + funcargs={}, + params={"anyio_backend": backend}, + indices={"anyio_backend": param_index}, + arg2scope={"anyio_backend": Scope.Module}, + idlist=[backend], + marks=[], + ) + + fi = item._fixtureinfo + new_names_closure = list(fi.names_closure) + if "anyio_backend" not in new_names_closure: + new_names_closure.append("anyio_backend") + + new_fixtureinfo = FuncFixtureInfo( + argnames=fi.argnames, + initialnames=fi.initialnames, + names_closure=new_names_closure, + name2fixturedefs=fi.name2fixturedefs, + ) + new_item = pytest.Function.from_parent( + item.parent, + name=f"{item.originalname}[{backend}]", + callspec=callspec, + callobj=item.obj, + fixtureinfo=new_fixtureinfo, + keywords=item.keywords, + originalname=item.originalname, + ) + new_items.append(new_item) + + session.items[i : i + 1] = new_items + + +@pytest.hookimpl(tryfirst=True) +def pytest_pyfunc_call(pyfuncitem: Any) -> bool | None: + def run_with_hypothesis(**kwargs: Any) -> None: + with get_runner(backend_name, backend_options) as runner: + runner.run_test(original_func, kwargs) + + backend = pyfuncitem.funcargs.get("anyio_backend") + if backend: + backend_name, backend_options = extract_backend_and_options(backend) + + if hasattr(pyfuncitem.obj, "hypothesis"): + # Wrap the inner test function unless it's already wrapped + original_func = pyfuncitem.obj.hypothesis.inner_test + if original_func.__qualname__ != run_with_hypothesis.__qualname__: + if iscoroutinefunction(original_func): + pyfuncitem.obj.hypothesis.inner_test = run_with_hypothesis + + return None + + if iscoroutinefunction(pyfuncitem.obj): + funcargs = pyfuncitem.funcargs + testargs = {arg: funcargs[arg] for arg in pyfuncitem._fixtureinfo.argnames} + with get_runner(backend_name, backend_options) as runner: + try: + runner.run_test(pyfuncitem.obj, testargs) + except ExceptionGroup as excgrp: + for exc in iterate_exceptions(excgrp): + if isinstance(exc, (Exit, KeyboardInterrupt, SystemExit)): + raise exc from excgrp + + raise + + return True + + return None + + +@pytest.fixture(scope="module", params=get_available_backends()) +def anyio_backend(request: Any) -> Any: + return request.param + + +@pytest.fixture +def anyio_backend_name(anyio_backend: Any) -> str: + if isinstance(anyio_backend, str): + return anyio_backend + else: + return anyio_backend[0] + + +@pytest.fixture +def anyio_backend_options(anyio_backend: Any) -> dict[str, Any]: + if isinstance(anyio_backend, str): + return {} + else: + return anyio_backend[1] + + +class FreePortFactory: + """ + Manages port generation based on specified socket kind, ensuring no duplicate + ports are generated. + + This class provides functionality for generating available free ports on the + system. It is initialized with a specific socket kind and can generate ports + for given address families while avoiding reuse of previously generated ports. + + Users should not instantiate this class directly, but use the + ``free_tcp_port_factory`` and ``free_udp_port_factory`` fixtures instead. For simple + uses cases, ``free_tcp_port`` and ``free_udp_port`` can be used instead. + """ + + def __init__(self, kind: socket.SocketKind) -> None: + self._kind = kind + self._generated = set[int]() + + @property + def kind(self) -> socket.SocketKind: + """ + The type of socket connection (e.g., :data:`~socket.SOCK_STREAM` or + :data:`~socket.SOCK_DGRAM`) used to bind for checking port availability + + """ + return self._kind + + def __call__(self, family: socket.AddressFamily | None = None) -> int: + """ + Return an unbound port for the given address family. + + :param family: if omitted, both IPv4 and IPv6 addresses will be tried + :return: a port number + + """ + if family is not None: + families = [family] + else: + families = [socket.AF_INET] + if socket.has_ipv6: + families.append(socket.AF_INET6) + + while True: + port = 0 + with ExitStack() as stack: + for family in families: + sock = stack.enter_context(socket.socket(family, self._kind)) + addr = "::1" if family == socket.AF_INET6 else "127.0.0.1" + try: + sock.bind((addr, port)) + except OSError: + break + + if not port: + port = sock.getsockname()[1] + else: + if port not in self._generated: + self._generated.add(port) + return port + + +@pytest.fixture(scope="session") +def free_tcp_port_factory() -> FreePortFactory: + return FreePortFactory(socket.SOCK_STREAM) + + +@pytest.fixture(scope="session") +def free_udp_port_factory() -> FreePortFactory: + return FreePortFactory(socket.SOCK_DGRAM) + + +@pytest.fixture +def free_tcp_port(free_tcp_port_factory: Callable[[], int]) -> int: + return free_tcp_port_factory() + + +@pytest.fixture +def free_udp_port(free_udp_port_factory: Callable[[], int]) -> int: + return free_udp_port_factory() diff --git a/data/miniconda3/lib/python3.13/site-packages/anyio/to_interpreter.py b/data/miniconda3/lib/python3.13/site-packages/anyio/to_interpreter.py new file mode 100644 index 0000000000000000000000000000000000000000..694dbe77bc8581032ee72316afe4e0590311ba00 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anyio/to_interpreter.py @@ -0,0 +1,246 @@ +from __future__ import annotations + +__all__ = ( + "run_sync", + "current_default_interpreter_limiter", +) + +import atexit +import os +import sys +from collections import deque +from collections.abc import Callable +from typing import Any, Final, TypeVar + +from . import current_time, to_thread +from ._core._exceptions import BrokenWorkerInterpreter +from ._core._synchronization import CapacityLimiter +from .lowlevel import RunVar + +if sys.version_info >= (3, 11): + from typing import TypeVarTuple, Unpack +else: + from typing_extensions import TypeVarTuple, Unpack + +if sys.version_info >= (3, 14): + from concurrent.interpreters import ExecutionFailed, create + + def _interp_call( + func: Callable[..., Any], args: tuple[Any, ...] + ) -> tuple[Any, bool]: + try: + retval = func(*args) + except BaseException as exc: + return exc, True + else: + return retval, False + + class _Worker: + last_used: float = 0 + + def __init__(self) -> None: + self._interpreter = create() + + def destroy(self) -> None: + self._interpreter.close() + + def call( + self, + func: Callable[..., T_Retval], + args: tuple[Any, ...], + ) -> T_Retval: + try: + res, is_exception = self._interpreter.call(_interp_call, func, args) + except ExecutionFailed as exc: + raise BrokenWorkerInterpreter(exc.excinfo) from exc + + if is_exception: + raise res + + return res +elif sys.version_info >= (3, 13): + import _interpqueues + import _interpreters + + UNBOUND: Final = 2 # I have no clue how this works, but it was used in the stdlib + FMT_UNPICKLED: Final = 0 + FMT_PICKLED: Final = 1 + QUEUE_PICKLE_ARGS: Final = (FMT_PICKLED, UNBOUND) + QUEUE_UNPICKLE_ARGS: Final = (FMT_UNPICKLED, UNBOUND) + + _run_func = compile( + """ +import _interpqueues +from _interpreters import NotShareableError +from pickle import loads, dumps, HIGHEST_PROTOCOL + +QUEUE_PICKLE_ARGS = (1, 2) +QUEUE_UNPICKLE_ARGS = (0, 2) + +item = _interpqueues.get(queue_id)[0] +try: + func, args = loads(item) + retval = func(*args) +except BaseException as exc: + is_exception = True + retval = exc +else: + is_exception = False + +try: + _interpqueues.put(queue_id, (retval, is_exception), *QUEUE_UNPICKLE_ARGS) +except NotShareableError: + retval = dumps(retval, HIGHEST_PROTOCOL) + _interpqueues.put(queue_id, (retval, is_exception), *QUEUE_PICKLE_ARGS) + """, + "", + "exec", + ) + + class _Worker: + last_used: float = 0 + + def __init__(self) -> None: + self._interpreter_id = _interpreters.create() + self._queue_id = _interpqueues.create(1, *QUEUE_UNPICKLE_ARGS) + _interpreters.set___main___attrs( + self._interpreter_id, {"queue_id": self._queue_id} + ) + + def destroy(self) -> None: + _interpqueues.destroy(self._queue_id) + _interpreters.destroy(self._interpreter_id) + + def call( + self, + func: Callable[..., T_Retval], + args: tuple[Any, ...], + ) -> T_Retval: + import pickle + + item = pickle.dumps((func, args), pickle.HIGHEST_PROTOCOL) + _interpqueues.put(self._queue_id, item, *QUEUE_PICKLE_ARGS) + exc_info = _interpreters.exec(self._interpreter_id, _run_func) + if exc_info: + raise BrokenWorkerInterpreter(exc_info) + + res = _interpqueues.get(self._queue_id) + (res, is_exception), fmt = res[:2] + if fmt == FMT_PICKLED: + res = pickle.loads(res) + + if is_exception: + raise res + + return res +else: + + class _Worker: + last_used: float = 0 + + def __init__(self) -> None: + raise RuntimeError("subinterpreters require at least Python 3.13") + + def call( + self, + func: Callable[..., T_Retval], + args: tuple[Any, ...], + ) -> T_Retval: + raise NotImplementedError + + def destroy(self) -> None: + pass + + +DEFAULT_CPU_COUNT: Final = 8 # this is just an arbitrarily selected value +MAX_WORKER_IDLE_TIME = ( + 30 # seconds a subinterpreter can be idle before becoming eligible for pruning +) + +T_Retval = TypeVar("T_Retval") +PosArgsT = TypeVarTuple("PosArgsT") + +_idle_workers = RunVar[deque[_Worker]]("_available_workers") +_default_interpreter_limiter = RunVar[CapacityLimiter]("_default_interpreter_limiter") + + +def _stop_workers(workers: deque[_Worker]) -> None: + for worker in workers: + worker.destroy() + + workers.clear() + + +async def run_sync( + func: Callable[[Unpack[PosArgsT]], T_Retval], + *args: Unpack[PosArgsT], + limiter: CapacityLimiter | None = None, +) -> T_Retval: + """ + Call the given function with the given arguments in a subinterpreter. + + .. warning:: On Python 3.13, the :mod:`concurrent.interpreters` module was not yet + available, so the code path for that Python version relies on an undocumented, + private API. As such, it is recommended to not rely on this function for anything + mission-critical on Python 3.13. + + :param func: a callable + :param args: the positional arguments for the callable + :param limiter: capacity limiter to use to limit the total number of subinterpreters + running (if omitted, the default limiter is used) + :return: the result of the call + :raises BrokenWorkerInterpreter: if there's an internal error in a subinterpreter + + """ + if limiter is None: + limiter = current_default_interpreter_limiter() + + try: + idle_workers = _idle_workers.get() + except LookupError: + idle_workers = deque() + _idle_workers.set(idle_workers) + atexit.register(_stop_workers, idle_workers) + + async with limiter: + try: + worker = idle_workers.pop() + except IndexError: + worker = _Worker() + + try: + return await to_thread.run_sync( + worker.call, + func, + args, + limiter=limiter, + ) + finally: + # Prune workers that have been idle for too long + now = current_time() + while idle_workers: + if now - idle_workers[0].last_used <= MAX_WORKER_IDLE_TIME: + break + + await to_thread.run_sync(idle_workers.popleft().destroy, limiter=limiter) + + worker.last_used = current_time() + idle_workers.append(worker) + + +def current_default_interpreter_limiter() -> CapacityLimiter: + """ + Return the capacity limiter used by default to limit the number of concurrently + running subinterpreters. + + Defaults to the number of CPU cores. + + :return: a capacity limiter object + + """ + try: + return _default_interpreter_limiter.get() + except LookupError: + limiter = CapacityLimiter(os.cpu_count() or DEFAULT_CPU_COUNT) + _default_interpreter_limiter.set(limiter) + return limiter diff --git a/data/miniconda3/lib/python3.13/site-packages/anyio/to_process.py b/data/miniconda3/lib/python3.13/site-packages/anyio/to_process.py new file mode 100644 index 0000000000000000000000000000000000000000..b289234ecfaafc1651dfa76e924291e5a5e9521e --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anyio/to_process.py @@ -0,0 +1,266 @@ +from __future__ import annotations + +__all__ = ( + "current_default_process_limiter", + "process_worker", + "run_sync", +) + +import os +import pickle +import subprocess +import sys +from collections import deque +from collections.abc import Callable +from importlib.util import module_from_spec, spec_from_file_location +from typing import TypeVar, cast + +from ._core._eventloop import current_time, get_async_backend, get_cancelled_exc_class +from ._core._exceptions import BrokenWorkerProcess +from ._core._subprocesses import open_process +from ._core._synchronization import CapacityLimiter +from ._core._tasks import CancelScope, fail_after +from .abc import ByteReceiveStream, ByteSendStream, Process +from .lowlevel import RunVar, checkpoint_if_cancelled +from .streams.buffered import BufferedByteReceiveStream + +if sys.version_info >= (3, 11): + from typing import TypeVarTuple, Unpack +else: + from typing_extensions import TypeVarTuple, Unpack + +WORKER_MAX_IDLE_TIME = 300 # 5 minutes + +T_Retval = TypeVar("T_Retval") +PosArgsT = TypeVarTuple("PosArgsT") + +_process_pool_workers: RunVar[set[Process]] = RunVar("_process_pool_workers") +_process_pool_idle_workers: RunVar[deque[tuple[Process, float]]] = RunVar( + "_process_pool_idle_workers" +) +_default_process_limiter: RunVar[CapacityLimiter] = RunVar("_default_process_limiter") + + +async def run_sync( # type: ignore[return] + func: Callable[[Unpack[PosArgsT]], T_Retval], + *args: Unpack[PosArgsT], + cancellable: bool = False, + limiter: CapacityLimiter | None = None, +) -> T_Retval: + """ + Call the given function with the given arguments in a worker process. + + If the ``cancellable`` option is enabled and the task waiting for its completion is + cancelled, the worker process running it will be abruptly terminated using SIGKILL + (or ``terminateProcess()`` on Windows). + + :param func: a callable + :param args: positional arguments for the callable + :param cancellable: ``True`` to allow cancellation of the operation while it's + running + :param limiter: capacity limiter to use to limit the total amount of processes + running (if omitted, the default limiter is used) + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + :return: an awaitable that yields the return value of the function. + + """ + + async def send_raw_command(pickled_cmd: bytes) -> object: + try: + await stdin.send(pickled_cmd) + response = await buffered.receive_until(b"\n", 50) + status, length = response.split(b" ") + if status not in (b"RETURN", b"EXCEPTION"): + raise RuntimeError( + f"Worker process returned unexpected response: {response!r}" + ) + + pickled_response = await buffered.receive_exactly(int(length)) + except BaseException as exc: + workers.discard(process) + try: + process.kill() + with CancelScope(shield=True): + await process.aclose() + except ProcessLookupError: + pass + + if isinstance(exc, get_cancelled_exc_class()): + raise + else: + raise BrokenWorkerProcess from exc + + retval = pickle.loads(pickled_response) + if status == b"EXCEPTION": + assert isinstance(retval, BaseException) + raise retval + else: + return retval + + # First pickle the request before trying to reserve a worker process + await checkpoint_if_cancelled() + request = pickle.dumps(("run", func, args), protocol=pickle.HIGHEST_PROTOCOL) + + # If this is the first run in this event loop thread, set up the necessary variables + try: + workers = _process_pool_workers.get() + idle_workers = _process_pool_idle_workers.get() + except LookupError: + workers = set() + idle_workers = deque() + _process_pool_workers.set(workers) + _process_pool_idle_workers.set(idle_workers) + get_async_backend().setup_process_pool_exit_at_shutdown(workers) + + async with limiter or current_default_process_limiter(): + # Pop processes from the pool (starting from the most recently used) until we + # find one that hasn't exited yet + process: Process + while idle_workers: + process, idle_since = idle_workers.pop() + if process.returncode is None: + stdin = cast(ByteSendStream, process.stdin) + buffered = BufferedByteReceiveStream( + cast(ByteReceiveStream, process.stdout) + ) + + # Prune any other workers that have been idle for WORKER_MAX_IDLE_TIME + # seconds or longer + now = current_time() + killed_processes: list[Process] = [] + while idle_workers: + if now - idle_workers[0][1] < WORKER_MAX_IDLE_TIME: + break + + process_to_kill, idle_since = idle_workers.popleft() + process_to_kill.kill() + workers.remove(process_to_kill) + killed_processes.append(process_to_kill) + + with CancelScope(shield=True): + for killed_process in killed_processes: + await killed_process.aclose() + + break + + workers.remove(process) + else: + command = [sys.executable, "-u", "-m", __name__] + process = await open_process( + command, stdin=subprocess.PIPE, stdout=subprocess.PIPE + ) + try: + stdin = cast(ByteSendStream, process.stdin) + buffered = BufferedByteReceiveStream( + cast(ByteReceiveStream, process.stdout) + ) + with fail_after(20): + message = await buffered.receive(6) + + if message != b"READY\n": + raise BrokenWorkerProcess( + f"Worker process returned unexpected response: {message!r}" + ) + + main_module_path = getattr(sys.modules["__main__"], "__file__", None) + pickled = pickle.dumps( + ("init", sys.path, main_module_path), + protocol=pickle.HIGHEST_PROTOCOL, + ) + await send_raw_command(pickled) + except (BrokenWorkerProcess, get_cancelled_exc_class()): + raise + except BaseException as exc: + process.kill() + raise BrokenWorkerProcess( + "Error during worker process initialization" + ) from exc + + workers.add(process) + + with CancelScope(shield=not cancellable): + try: + return cast(T_Retval, await send_raw_command(request)) + finally: + if process in workers: + idle_workers.append((process, current_time())) + + +def current_default_process_limiter() -> CapacityLimiter: + """ + Return the capacity limiter that is used by default to limit the number of worker + processes. + + :return: a capacity limiter object + + """ + try: + return _default_process_limiter.get() + except LookupError: + limiter = CapacityLimiter(os.cpu_count() or 2) + _default_process_limiter.set(limiter) + return limiter + + +def process_worker() -> None: + # Redirect standard streams to os.devnull so that user code won't interfere with the + # parent-worker communication + stdin = sys.stdin + stdout = sys.stdout + sys.stdin = open(os.devnull) + sys.stdout = open(os.devnull, "w") + + stdout.buffer.write(b"READY\n") + while True: + retval = exception = None + try: + command, *args = pickle.load(stdin.buffer) + except EOFError: + return + except BaseException as exc: + exception = exc + else: + if command == "run": + func, args = args + try: + retval = func(*args) + except BaseException as exc: + exception = exc + elif command == "init": + main_module_path: str | None + sys.path, main_module_path = args + del sys.modules["__main__"] + if main_module_path and os.path.isfile(main_module_path): + # Load the parent's main module but as __mp_main__ instead of + # __main__ (like multiprocessing does) to avoid infinite recursion + try: + spec = spec_from_file_location("__mp_main__", main_module_path) + if spec and spec.loader: + main = module_from_spec(spec) + spec.loader.exec_module(main) + sys.modules["__main__"] = main + except BaseException as exc: + exception = exc + try: + if exception is not None: + status = b"EXCEPTION" + pickled = pickle.dumps(exception, pickle.HIGHEST_PROTOCOL) + else: + status = b"RETURN" + pickled = pickle.dumps(retval, pickle.HIGHEST_PROTOCOL) + except BaseException as exc: + exception = exc + status = b"EXCEPTION" + pickled = pickle.dumps(exc, pickle.HIGHEST_PROTOCOL) + + stdout.buffer.write(b"%s %d\n" % (status, len(pickled))) + stdout.buffer.write(pickled) + + # Respect SIGTERM + if isinstance(exception, SystemExit): + raise exception + + +if __name__ == "__main__": + process_worker() diff --git a/data/miniconda3/lib/python3.13/site-packages/anyio/to_thread.py b/data/miniconda3/lib/python3.13/site-packages/anyio/to_thread.py new file mode 100644 index 0000000000000000000000000000000000000000..83c79d1cd4029ccdaf23b22a9ad10074a0979ec2 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anyio/to_thread.py @@ -0,0 +1,78 @@ +from __future__ import annotations + +__all__ = ( + "run_sync", + "current_default_thread_limiter", +) + +import sys +from collections.abc import Callable +from typing import TypeVar +from warnings import warn + +from ._core._eventloop import get_async_backend +from .abc import CapacityLimiter + +if sys.version_info >= (3, 11): + from typing import TypeVarTuple, Unpack +else: + from typing_extensions import TypeVarTuple, Unpack + +T_Retval = TypeVar("T_Retval") +PosArgsT = TypeVarTuple("PosArgsT") + + +async def run_sync( + func: Callable[[Unpack[PosArgsT]], T_Retval], + *args: Unpack[PosArgsT], + abandon_on_cancel: bool = False, + cancellable: bool | None = None, + limiter: CapacityLimiter | None = None, +) -> T_Retval: + """ + Call the given function with the given arguments in a worker thread. + + If the ``abandon_on_cancel`` option is enabled and the task waiting for its + completion is cancelled, the thread will still run its course but its + return value (or any raised exception) will be ignored. + + :param func: a callable + :param args: positional arguments for the callable + :param abandon_on_cancel: ``True`` to abandon the thread (leaving it to run + unchecked on own) if the host task is cancelled, ``False`` to ignore + cancellations in the host task until the operation has completed in the worker + thread + :param cancellable: deprecated alias of ``abandon_on_cancel``; will override + ``abandon_on_cancel`` if both parameters are passed + :param limiter: capacity limiter to use to limit the total amount of threads running + (if omitted, the default limiter is used) + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + :return: an awaitable that yields the return value of the function. + + """ + if cancellable is not None: + abandon_on_cancel = cancellable + warn( + "The `cancellable=` keyword argument to `anyio.to_thread.run_sync` is " + "deprecated since AnyIO 4.1.0; use `abandon_on_cancel=` instead", + DeprecationWarning, + stacklevel=2, + ) + + return await get_async_backend().run_sync_in_worker_thread( + func, args, abandon_on_cancel=abandon_on_cancel, limiter=limiter + ) + + +def current_default_thread_limiter() -> CapacityLimiter: + """ + Return the capacity limiter that is used by default to limit the number of + concurrent threads. + + :return: a capacity limiter object + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + + """ + return get_async_backend().current_default_thread_limiter() diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/__init__.py b/data/miniconda3/lib/python3.13/site-packages/archspec/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2425354e623ab3e58c65ab9aa67e4c7d884053b4 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/__init__.py @@ -0,0 +1,3 @@ +"""Init file to avoid namespace packages""" + +__version__ = "0.2.5" diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/__main__.py b/data/miniconda3/lib/python3.13/site-packages/archspec/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..45fbe12704517a629bf56fa10fbb6e32672c9d74 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/__main__.py @@ -0,0 +1,9 @@ +""" +Run the `archspec` CLI as a module. +""" + +import sys + +from .cli import main + +sys.exit(main()) diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/cli.py b/data/miniconda3/lib/python3.13/site-packages/archspec/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..eaddaf5d77bef895fc6a6104c0f4b6b16ff83735 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/cli.py @@ -0,0 +1,70 @@ +# Copyright 2019-2020 Lawrence Livermore National Security, LLC and other +# Archspec Project Developers. See the top-level COPYRIGHT file for details. +# +# SPDX-License-Identifier: (Apache-2.0 OR MIT) +""" +archspec command line interface +""" + +import argparse +import typing + +import archspec +import archspec.cpu + + +def _make_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + "archspec", + description="archspec command line interface", + add_help=False, + ) + parser.add_argument( + "--version", + "-V", + help="Show the version and exit.", + action="version", + version=f"archspec, version {archspec.__version__}", + ) + parser.add_argument("--help", "-h", help="Show the help and exit.", action="help") + + subcommands = parser.add_subparsers( + title="command", + metavar="COMMAND", + dest="command", + ) + + cpu_command = subcommands.add_parser( + "cpu", + help="archspec command line interface for CPU", + description="archspec command line interface for CPU", + ) + cpu_command.set_defaults(run=cpu) + + return parser + + +def cpu() -> int: + """Run the `archspec cpu` subcommand.""" + try: + print(archspec.cpu.host()) + except FileNotFoundError as exc: + print(exc) + return 1 + return 0 + + +def main(argv: typing.Optional[typing.List[str]] = None) -> int: + """Run the `archspec` command line interface.""" + parser = _make_parser() + + try: + args = parser.parse_args(argv) + except SystemExit as err: + return err.code + + if args.command is None: + parser.print_help() + return 0 + + return args.run() diff --git a/data/miniconda3/lib/python3.13/site-packages/boltons/__init__.py b/data/miniconda3/lib/python3.13/site-packages/boltons/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/lib/python3.13/site-packages/boltons/cacheutils.py b/data/miniconda3/lib/python3.13/site-packages/boltons/cacheutils.py new file mode 100644 index 0000000000000000000000000000000000000000..856bf195483aafbfcdb8f6f93a168daf0c9b5857 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/boltons/cacheutils.py @@ -0,0 +1,870 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# * The names of the contributors may not be used to endorse or +# promote products derived from this software without specific +# prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""``cacheutils`` contains consistent implementations of fundamental +cache types. Currently there are two to choose from: + + * :class:`LRI` - Least-recently inserted + * :class:`LRU` - Least-recently used + +Both caches are :class:`dict` subtypes, designed to be as +interchangeable as possible, to facilitate experimentation. A key +practice with performance enhancement with caching is ensuring that +the caching strategy is working. If the cache is constantly missing, +it is just adding more overhead and code complexity. The standard +statistics are: + + * ``hit_count`` - the number of times the queried key has been in + the cache + * ``miss_count`` - the number of times a key has been absent and/or + fetched by the cache + * ``soft_miss_count`` - the number of times a key has been absent, + but a default has been provided by the caller, as with + :meth:`dict.get` and :meth:`dict.setdefault`. Soft misses are a + subset of misses, so this number is always less than or equal to + ``miss_count``. + +Additionally, ``cacheutils`` provides :class:`ThresholdCounter`, a +cache-like bounded counter useful for online statistics collection. + +Learn more about `caching algorithms on Wikipedia +`_. + +""" + +# TODO: TimedLRI +# TODO: support 0 max_size? + + +import heapq +import weakref +import itertools +from operator import attrgetter + +try: + from threading import RLock +except Exception: + class RLock: + 'Dummy reentrant lock for builds without threads' + def __enter__(self): + pass + + def __exit__(self, exctype, excinst, exctb): + pass + +try: + from .typeutils import make_sentinel + _MISSING = make_sentinel(var_name='_MISSING') + _KWARG_MARK = make_sentinel(var_name='_KWARG_MARK') +except ImportError: + _MISSING = object() + _KWARG_MARK = object() + +PREV, NEXT, KEY, VALUE = range(4) # names for the link fields +DEFAULT_MAX_SIZE = 128 + + +class LRI(dict): + """The ``LRI`` implements the basic *Least Recently Inserted* strategy to + caching. One could also think of this as a ``SizeLimitedDefaultDict``. + + *on_miss* is a callable that accepts the missing key (as opposed + to :class:`collections.defaultdict`'s "default_factory", which + accepts no arguments.) Also note that, like the :class:`LRI`, + the ``LRI`` is instrumented with statistics tracking. + + >>> cap_cache = LRI(max_size=2) + >>> cap_cache['a'], cap_cache['b'] = 'A', 'B' + >>> from pprint import pprint as pp + >>> pp(dict(cap_cache)) + {'a': 'A', 'b': 'B'} + >>> [cap_cache['b'] for i in range(3)][0] + 'B' + >>> cap_cache['c'] = 'C' + >>> print(cap_cache.get('a')) + None + >>> cap_cache.hit_count, cap_cache.miss_count, cap_cache.soft_miss_count + (3, 1, 1) + """ + def __init__(self, max_size=DEFAULT_MAX_SIZE, values=None, + on_miss=None): + if max_size <= 0: + raise ValueError('expected max_size > 0, not %r' % max_size) + self.hit_count = self.miss_count = self.soft_miss_count = 0 + self.max_size = max_size + self._lock = RLock() + self._init_ll() + + if on_miss is not None and not callable(on_miss): + raise TypeError('expected on_miss to be a callable' + ' (or None), not %r' % on_miss) + self.on_miss = on_miss + + if values: + self.update(values) + + # TODO: fromkeys()? + + # linked list manipulation methods. + # + # invariants: + # 1) 'anchor' is the sentinel node in the doubly linked list. there is + # always only one, and its KEY and VALUE are both _MISSING. + # 2) the most recently accessed node comes immediately before 'anchor'. + # 3) the least recently accessed node comes immediately after 'anchor'. + def _init_ll(self): + anchor = [] + anchor[:] = [anchor, anchor, _MISSING, _MISSING] + # a link lookup table for finding linked list links in O(1) + # time. + self._link_lookup = {} + self._anchor = anchor + + def _print_ll(self): + print('***') + for (key, val) in self._get_flattened_ll(): + print(key, val) + print('***') + return + + def _get_flattened_ll(self): + flattened_list = [] + link = self._anchor + while True: + flattened_list.append((link[KEY], link[VALUE])) + link = link[NEXT] + if link is self._anchor: + break + return flattened_list + + def _get_link_and_move_to_front_of_ll(self, key): + # find what will become the newest link. this may raise a + # KeyError, which is useful to __getitem__ and __setitem__ + newest = self._link_lookup[key] + + # splice out what will become the newest link. + newest[PREV][NEXT] = newest[NEXT] + newest[NEXT][PREV] = newest[PREV] + + # move what will become the newest link immediately before + # anchor (invariant 2) + anchor = self._anchor + second_newest = anchor[PREV] + second_newest[NEXT] = anchor[PREV] = newest + newest[PREV] = second_newest + newest[NEXT] = anchor + return newest + + def _set_key_and_add_to_front_of_ll(self, key, value): + # create a new link and place it immediately before anchor + # (invariant 2). + anchor = self._anchor + second_newest = anchor[PREV] + newest = [second_newest, anchor, key, value] + second_newest[NEXT] = anchor[PREV] = newest + self._link_lookup[key] = newest + + def _set_key_and_evict_last_in_ll(self, key, value): + # the link after anchor is the oldest in the linked list + # (invariant 3). the current anchor becomes a link that holds + # the newest key, and the oldest link becomes the new anchor + # (invariant 1). now the newest link comes before anchor + # (invariant 2). no links are moved; only their keys + # and values are changed. + oldanchor = self._anchor + oldanchor[KEY] = key + oldanchor[VALUE] = value + + self._anchor = anchor = oldanchor[NEXT] + evicted = anchor[KEY] + anchor[KEY] = anchor[VALUE] = _MISSING + del self._link_lookup[evicted] + self._link_lookup[key] = oldanchor + return evicted + + def _remove_from_ll(self, key): + # splice a link out of the list and drop it from our lookup + # table. + link = self._link_lookup.pop(key) + link[PREV][NEXT] = link[NEXT] + link[NEXT][PREV] = link[PREV] + + def __setitem__(self, key, value): + with self._lock: + try: + link = self._get_link_and_move_to_front_of_ll(key) + except KeyError: + if len(self) < self.max_size: + self._set_key_and_add_to_front_of_ll(key, value) + else: + evicted = self._set_key_and_evict_last_in_ll(key, value) + super().__delitem__(evicted) + else: + link[VALUE] = value + super().__setitem__(key, value) + return + + def __getitem__(self, key): + with self._lock: + try: + link = self._link_lookup[key] + except KeyError: + self.miss_count += 1 + if not self.on_miss: + raise + ret = self[key] = self.on_miss(key) + return ret + + self.hit_count += 1 + return link[VALUE] + + def get(self, key, default=None): + try: + return self[key] + except KeyError: + self.soft_miss_count += 1 + return default + + def __delitem__(self, key): + with self._lock: + super().__delitem__(key) + self._remove_from_ll(key) + + def pop(self, key, default=_MISSING): + # NB: hit/miss counts are bypassed for pop() + with self._lock: + try: + ret = super().pop(key) + except KeyError: + if default is _MISSING: + raise + ret = default + else: + self._remove_from_ll(key) + return ret + + def popitem(self): + with self._lock: + item = super().popitem() + self._remove_from_ll(item[0]) + return item + + def clear(self): + with self._lock: + super().clear() + self._init_ll() + + def copy(self): + return self.__class__(max_size=self.max_size, values=self) + + def setdefault(self, key, default=None): + with self._lock: + try: + return self[key] + except KeyError: + self.soft_miss_count += 1 + self[key] = default + return default + + def update(self, E, **F): + # E and F are throwback names to the dict() __doc__ + with self._lock: + if E is self: + return + setitem = self.__setitem__ + if callable(getattr(E, 'keys', None)): + for k in E.keys(): + setitem(k, E[k]) + else: + for k, v in E: + setitem(k, v) + for k in F: + setitem(k, F[k]) + return + + def __eq__(self, other): + with self._lock: + if self is other: + return True + if len(other) != len(self): + return False + if not isinstance(other, LRI): + return other == self + return super().__eq__(other) + + def __ne__(self, other): + return not (self == other) + + def __repr__(self): + cn = self.__class__.__name__ + val_map = super().__repr__() + return ('%s(max_size=%r, on_miss=%r, values=%s)' + % (cn, self.max_size, self.on_miss, val_map)) + + +class LRU(LRI): + """The ``LRU`` is :class:`dict` subtype implementation of the + *Least-Recently Used* caching strategy. + + Args: + max_size (int): Max number of items to cache. Defaults to ``128``. + values (iterable): Initial values for the cache. Defaults to ``None``. + on_miss (callable): a callable which accepts a single argument, the + key not present in the cache, and returns the value to be cached. + + >>> cap_cache = LRU(max_size=2) + >>> cap_cache['a'], cap_cache['b'] = 'A', 'B' + >>> from pprint import pprint as pp + >>> pp(dict(cap_cache)) + {'a': 'A', 'b': 'B'} + >>> [cap_cache['b'] for i in range(3)][0] + 'B' + >>> cap_cache['c'] = 'C' + >>> print(cap_cache.get('a')) + None + + This cache is also instrumented with statistics + collection. ``hit_count``, ``miss_count``, and ``soft_miss_count`` + are all integer members that can be used to introspect the + performance of the cache. ("Soft" misses are misses that did not + raise :exc:`KeyError`, e.g., ``LRU.get()`` or ``on_miss`` was used to + cache a default. + + >>> cap_cache.hit_count, cap_cache.miss_count, cap_cache.soft_miss_count + (3, 1, 1) + + Other than the size-limiting caching behavior and statistics, + ``LRU`` acts like its parent class, the built-in Python :class:`dict`. + """ + def __getitem__(self, key): + with self._lock: + try: + link = self._get_link_and_move_to_front_of_ll(key) + except KeyError: + self.miss_count += 1 + if not self.on_miss: + raise + ret = self[key] = self.on_miss(key) + return ret + + self.hit_count += 1 + return link[VALUE] + + +### Cached decorator +# Key-making technique adapted from Python 3.4's functools + +class _HashedKey(list): + """The _HashedKey guarantees that hash() will be called no more than once + per cached function invocation. + """ + __slots__ = 'hash_value' + + def __init__(self, key): + self[:] = key + self.hash_value = hash(tuple(key)) + + def __hash__(self): + return self.hash_value + + def __repr__(self): + return f'{self.__class__.__name__}({list.__repr__(self)})' + + +def make_cache_key(args, kwargs, typed=False, + kwarg_mark=_KWARG_MARK, + fasttypes=frozenset([int, str, frozenset, type(None)])): + """Make a generic key from a function's positional and keyword + arguments, suitable for use in caches. Arguments within *args* and + *kwargs* must be `hashable`_. If *typed* is ``True``, ``3`` and + ``3.0`` will be treated as separate keys. + + The key is constructed in a way that is flat as possible rather than + as a nested structure that would take more memory. + + If there is only a single argument and its data type is known to cache + its hash value, then that argument is returned without a wrapper. This + saves space and improves lookup speed. + + >>> tuple(make_cache_key(('a', 'b'), {'c': ('d')})) + ('a', 'b', _KWARG_MARK, ('c', 'd')) + + .. _hashable: https://docs.python.org/2/glossary.html#term-hashable + """ + + # key = [func_name] if func_name else [] + # key.extend(args) + key = list(args) + if kwargs: + sorted_items = sorted(kwargs.items()) + key.append(kwarg_mark) + key.extend(sorted_items) + if typed: + key.extend([type(v) for v in args]) + if kwargs: + key.extend([type(v) for k, v in sorted_items]) + elif len(key) == 1 and type(key[0]) in fasttypes: + return key[0] + return _HashedKey(key) + +# for backwards compatibility in case someone was importing it +_make_cache_key = make_cache_key + + +class CachedFunction: + """This type is used by :func:`cached`, below. Instances of this + class are used to wrap functions in caching logic. + """ + def __init__(self, func, cache, scoped=True, typed=False, key=None): + self.func = func + if callable(cache): + self.get_cache = cache + elif not (callable(getattr(cache, '__getitem__', None)) + and callable(getattr(cache, '__setitem__', None))): + raise TypeError('expected cache to be a dict-like object,' + ' or callable returning a dict-like object, not %r' + % cache) + else: + def _get_cache(): + return cache + self.get_cache = _get_cache + self.scoped = scoped + self.typed = typed + self.key_func = key or make_cache_key + + def __call__(self, *args, **kwargs): + cache = self.get_cache() + key = self.key_func(args, kwargs, typed=self.typed) + try: + ret = cache[key] + except KeyError: + ret = cache[key] = self.func(*args, **kwargs) + return ret + + def __repr__(self): + cn = self.__class__.__name__ + if self.typed or not self.scoped: + return ("%s(func=%r, scoped=%r, typed=%r)" + % (cn, self.func, self.scoped, self.typed)) + return f"{cn}(func={self.func!r})" + + +class CachedMethod: + """Similar to :class:`CachedFunction`, this type is used by + :func:`cachedmethod` to wrap methods in caching logic. + """ + def __init__(self, func, cache, scoped=True, typed=False, key=None): + self.func = func + self.__isabstractmethod__ = getattr(func, '__isabstractmethod__', False) + if isinstance(cache, str): + self.get_cache = attrgetter(cache) + elif callable(cache): + self.get_cache = cache + elif not (callable(getattr(cache, '__getitem__', None)) + and callable(getattr(cache, '__setitem__', None))): + raise TypeError('expected cache to be an attribute name,' + ' dict-like object, or callable returning' + ' a dict-like object, not %r' % cache) + else: + def _get_cache(obj): + return cache + self.get_cache = _get_cache + self.scoped = scoped + self.typed = typed + self.key_func = key or make_cache_key + self.bound_to = None + + def __get__(self, obj, objtype=None): + if obj is None: + return self + cls = self.__class__ + ret = cls(self.func, self.get_cache, typed=self.typed, + scoped=self.scoped, key=self.key_func) + ret.bound_to = obj + return ret + + def __call__(self, *args, **kwargs): + obj = args[0] if self.bound_to is None else self.bound_to + cache = self.get_cache(obj) + key_args = (self.bound_to, self.func) + args if self.scoped else args + key = self.key_func(key_args, kwargs, typed=self.typed) + try: + ret = cache[key] + except KeyError: + if self.bound_to is not None: + args = (self.bound_to,) + args + ret = cache[key] = self.func(*args, **kwargs) + return ret + + def __repr__(self): + cn = self.__class__.__name__ + args = (cn, self.func, self.scoped, self.typed) + if self.bound_to is not None: + args += (self.bound_to,) + return ('<%s func=%r scoped=%r typed=%r bound_to=%r>' % args) + return ("%s(func=%r, scoped=%r, typed=%r)" % args) + + +def cached(cache, scoped=True, typed=False, key=None): + """Cache any function with the cache object of your choosing. Note + that the function wrapped should take only `hashable`_ arguments. + + Args: + cache (Mapping): Any :class:`dict`-like object suitable for + use as a cache. Instances of the :class:`LRU` and + :class:`LRI` are good choices, but a plain :class:`dict` + can work in some cases, as well. This argument can also be + a callable which accepts no arguments and returns a mapping. + scoped (bool): Whether the function itself is part of the + cache key. ``True`` by default, different functions will + not read one another's cache entries, but can evict one + another's results. ``False`` can be useful for certain + shared cache use cases. More advanced behavior can be + produced through the *key* argument. + typed (bool): Whether to factor argument types into the cache + check. Default ``False``, setting to ``True`` causes the + cache keys for ``3`` and ``3.0`` to be considered unequal. + + >>> my_cache = LRU() + >>> @cached(my_cache) + ... def cached_lower(x): + ... return x.lower() + ... + >>> cached_lower("CaChInG's FuN AgAiN!") + "caching's fun again!" + >>> len(my_cache) + 1 + + .. _hashable: https://docs.python.org/2/glossary.html#term-hashable + + """ + def cached_func_decorator(func): + return CachedFunction(func, cache, scoped=scoped, typed=typed, key=key) + return cached_func_decorator + + +def cachedmethod(cache, scoped=True, typed=False, key=None): + """Similar to :func:`cached`, ``cachedmethod`` is used to cache + methods based on their arguments, using any :class:`dict`-like + *cache* object. + + Args: + cache (str/Mapping/callable): Can be the name of an attribute + on the instance, any Mapping/:class:`dict`-like object, or + a callable which returns a Mapping. + scoped (bool): Whether the method itself and the object it is + bound to are part of the cache keys. ``True`` by default, + different methods will not read one another's cache + results. ``False`` can be useful for certain shared cache + use cases. More advanced behavior can be produced through + the *key* arguments. + typed (bool): Whether to factor argument types into the cache + check. Default ``False``, setting to ``True`` causes the + cache keys for ``3`` and ``3.0`` to be considered unequal. + key (callable): A callable with a signature that matches + :func:`make_cache_key` that returns a tuple of hashable + values to be used as the key in the cache. + + >>> class Lowerer(object): + ... def __init__(self): + ... self.cache = LRI() + ... + ... @cachedmethod('cache') + ... def lower(self, text): + ... return text.lower() + ... + >>> lowerer = Lowerer() + >>> lowerer.lower('WOW WHO COULD GUESS CACHING COULD BE SO NEAT') + 'wow who could guess caching could be so neat' + >>> len(lowerer.cache) + 1 + + """ + def cached_method_decorator(func): + return CachedMethod(func, cache, scoped=scoped, typed=typed, key=key) + return cached_method_decorator + + +class cachedproperty: + """The ``cachedproperty`` is used similar to :class:`property`, except + that the wrapped method is only called once. This is commonly used + to implement lazy attributes. + + After the property has been accessed, the value is stored on the + instance itself, using the same name as the cachedproperty. This + allows the cache to be cleared with :func:`delattr`, or through + manipulating the object's ``__dict__``. + """ + def __init__(self, func): + self.__doc__ = getattr(func, '__doc__') + self.__isabstractmethod__ = getattr(func, '__isabstractmethod__', False) + self.func = func + + def __get__(self, obj, objtype=None): + if obj is None: + return self + value = obj.__dict__[self.func.__name__] = self.func(obj) + return value + + def __repr__(self): + cn = self.__class__.__name__ + return f'<{cn} func={self.func}>' + + +class ThresholdCounter: + """A **bounded** dict-like Mapping from keys to counts. The + ThresholdCounter automatically compacts after every (1 / + *threshold*) additions, maintaining exact counts for any keys + whose count represents at least a *threshold* ratio of the total + data. In other words, if a particular key is not present in the + ThresholdCounter, its count represents less than *threshold* of + the total data. + + >>> tc = ThresholdCounter(threshold=0.1) + >>> tc.add(1) + >>> tc.items() + [(1, 1)] + >>> tc.update([2] * 10) + >>> tc.get(1) + 0 + >>> tc.add(5) + >>> 5 in tc + True + >>> len(list(tc.elements())) + 11 + + As you can see above, the API is kept similar to + :class:`collections.Counter`. The most notable feature omissions + being that counted items cannot be set directly, uncounted, or + removed, as this would disrupt the math. + + Use the ThresholdCounter when you need best-effort long-lived + counts for dynamically-keyed data. Without a bounded datastructure + such as this one, the dynamic keys often represent a memory leak + and can impact application reliability. The ThresholdCounter's + item replacement strategy is fully deterministic and can be + thought of as *Amortized Least Relevant*. The absolute upper bound + of keys it will store is *(2/threshold)*, but realistically + *(1/threshold)* is expected for uniformly random datastreams, and + one or two orders of magnitude better for real-world data. + + This algorithm is an implementation of the Lossy Counting + algorithm described in "Approximate Frequency Counts over Data + Streams" by Manku & Motwani. Hat tip to Kurt Rose for discovery + and initial implementation. + + """ + # TODO: hit_count/miss_count? + def __init__(self, threshold=0.001): + if not 0 < threshold < 1: + raise ValueError('expected threshold between 0 and 1, not: %r' + % threshold) + + self.total = 0 + self._count_map = {} + self._threshold = threshold + self._thresh_count = int(1 / threshold) + self._cur_bucket = 1 + + @property + def threshold(self): + return self._threshold + + def add(self, key): + """Increment the count of *key* by 1, automatically adding it if it + does not exist. + + Cache compaction is triggered every *1/threshold* additions. + """ + self.total += 1 + try: + self._count_map[key][0] += 1 + except KeyError: + self._count_map[key] = [1, self._cur_bucket - 1] + + if self.total % self._thresh_count == 0: + self._count_map = {k: v for k, v in self._count_map.items() + if sum(v) > self._cur_bucket} + self._cur_bucket += 1 + return + + def elements(self): + """Return an iterator of all the common elements tracked by the + counter. Yields each key as many times as it has been seen. + """ + repeaters = itertools.starmap(itertools.repeat, self.iteritems()) + return itertools.chain.from_iterable(repeaters) + + def most_common(self, n=None): + """Get the top *n* keys and counts as tuples. If *n* is omitted, + returns all the pairs. + """ + if not n or n <= 0: + return [] + ret = sorted(self.iteritems(), key=lambda x: x[1], reverse=True) + if n is None or n >= len(ret): + return ret + return ret[:n] + + def get_common_count(self): + """Get the sum of counts for keys exceeding the configured data + threshold. + """ + return sum([count for count, _ in self._count_map.values()]) + + def get_uncommon_count(self): + """Get the sum of counts for keys that were culled because the + associated counts represented less than the configured + threshold. The long-tail counts. + """ + return self.total - self.get_common_count() + + def get_commonality(self): + """Get a float representation of the effective count accuracy. The + higher the number, the less uniform the keys being added, and + the higher accuracy and efficiency of the ThresholdCounter. + + If a stronger measure of data cardinality is required, + consider using hyperloglog. + """ + return float(self.get_common_count()) / self.total + + def __getitem__(self, key): + return self._count_map[key][0] + + def __len__(self): + return len(self._count_map) + + def __contains__(self, key): + return key in self._count_map + + def iterkeys(self): + return iter(self._count_map) + + def keys(self): + return list(self.iterkeys()) + + def itervalues(self): + count_map = self._count_map + for k in count_map: + yield count_map[k][0] + + def values(self): + return list(self.itervalues()) + + def iteritems(self): + count_map = self._count_map + for k in count_map: + yield (k, count_map[k][0]) + + def items(self): + return list(self.iteritems()) + + def get(self, key, default=0): + "Get count for *key*, defaulting to 0." + try: + return self[key] + except KeyError: + return default + + def update(self, iterable, **kwargs): + """Like dict.update() but add counts instead of replacing them, used + to add multiple items in one call. + + Source can be an iterable of keys to add, or a mapping of keys + to integer counts. + """ + if iterable is not None: + if callable(getattr(iterable, 'iteritems', None)): + for key, count in iterable.iteritems(): + for i in range(count): + self.add(key) + else: + for key in iterable: + self.add(key) + if kwargs: + self.update(kwargs) + + +class MinIDMap: + """ + Assigns arbitrary weakref-able objects the smallest possible unique + integer IDs, such that no two objects have the same ID at the same + time. + + Maps arbitrary hashable objects to IDs. + + Based on https://gist.github.com/kurtbrose/25b48114de216a5e55df + """ + def __init__(self): + self.mapping = weakref.WeakKeyDictionary() + self.ref_map = {} + self.free = [] + + def get(self, a): + try: + return self.mapping[a][0] # if object is mapped, return ID + except KeyError: + pass + + if self.free: # if there are any free IDs, use the smallest + nxt = heapq.heappop(self.free) + else: # if there are no free numbers, use the next highest ID + nxt = len(self.mapping) + ref = weakref.ref(a, self._clean) + self.mapping[a] = (nxt, ref) + self.ref_map[ref] = nxt + return nxt + + def drop(self, a): + freed, ref = self.mapping[a] + del self.mapping[a] + del self.ref_map[ref] + heapq.heappush(self.free, freed) + + def _clean(self, ref): + print(self.ref_map[ref]) + heapq.heappush(self.free, self.ref_map[ref]) + del self.ref_map[ref] + + def __contains__(self, a): + return a in self.mapping + + def __iter__(self): + return iter(self.mapping) + + def __len__(self): + return self.mapping.__len__() + + def iteritems(self): + return iter((k, self.mapping[k][0]) for k in iter(self.mapping)) + + +# end cacheutils.py diff --git a/data/miniconda3/lib/python3.13/site-packages/boltons/debugutils.py b/data/miniconda3/lib/python3.13/site-packages/boltons/debugutils.py new file mode 100644 index 0000000000000000000000000000000000000000..16d18d4b9078d8864477cbe445d142addfae7134 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/boltons/debugutils.py @@ -0,0 +1,292 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# * The names of the contributors may not be used to endorse or +# promote products derived from this software without specific +# prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +""" +A small set of utilities useful for debugging misbehaving +applications. Currently this focuses on ways to use :mod:`pdb`, the +built-in Python debugger. +""" + +import sys +import time +from reprlib import Repr + +try: + from .typeutils import make_sentinel + _UNSET = make_sentinel(var_name='_UNSET') +except ImportError: + _UNSET = object() + +__all__ = ['pdb_on_signal', 'pdb_on_exception', 'wrap_trace'] + + +def pdb_on_signal(signalnum=None): + """Installs a signal handler for *signalnum*, which defaults to + ``SIGINT``, or keyboard interrupt/ctrl-c. This signal handler + launches a :mod:`pdb` breakpoint. Results vary in concurrent + systems, but this technique can be useful for debugging infinite + loops, or easily getting into deep call stacks. + + Args: + signalnum (int): The signal number of the signal to handle + with pdb. Defaults to :mod:`signal.SIGINT`, see + :mod:`signal` for more information. + """ + import pdb + import signal + if not signalnum: + signalnum = signal.SIGINT + + old_handler = signal.getsignal(signalnum) + + def pdb_int_handler(sig, frame): + signal.signal(signalnum, old_handler) + pdb.set_trace() + pdb_on_signal(signalnum) # use 'u' to find your code and 'h' for help + + signal.signal(signalnum, pdb_int_handler) + return + + +def pdb_on_exception(limit=100): + """Installs a handler which, instead of exiting, attaches a + post-mortem pdb console whenever an unhandled exception is + encountered. + + Args: + limit (int): the max number of stack frames to display when + printing the traceback + + A similar effect can be achieved from the command-line using the + following command:: + + python -m pdb your_code.py + + But ``pdb_on_exception`` allows you to do this conditionally and within + your application. To restore default behavior, just do:: + + sys.excepthook = sys.__excepthook__ + """ + import pdb + import sys + import traceback + + def pdb_excepthook(exc_type, exc_val, exc_tb): + traceback.print_tb(exc_tb, limit=limit) + pdb.post_mortem(exc_tb) + + sys.excepthook = pdb_excepthook + return + +_repr_obj = Repr() +_repr_obj.maxstring = 50 +_repr_obj.maxother = 50 +brief_repr = _repr_obj.repr + + +# events: call, return, get, set, del, raise +def trace_print_hook(event, label, obj, attr_name, + args=(), kwargs={}, result=_UNSET): + fargs = (event.ljust(6), time.time(), label.rjust(10), + obj.__class__.__name__, attr_name) + if event == 'get': + tmpl = '%s %s - %s - %s.%s -> %s' + fargs += (brief_repr(result),) + elif event == 'set': + tmpl = '%s %s - %s - %s.%s = %s' + fargs += (brief_repr(args[0]),) + elif event == 'del': + tmpl = '%s %s - %s - %s.%s' + else: # call/return/raise + tmpl = '%s %s - %s - %s.%s(%s)' + fargs += (', '.join([brief_repr(a) for a in args]),) + if kwargs: + tmpl = '%s %s - %s - %s.%s(%s, %s)' + fargs += (', '.join([f'{k}={brief_repr(v)}' + for k, v in kwargs.items()]),) + if result is not _UNSET: + tmpl += ' -> %s' + fargs += (brief_repr(result),) + print(tmpl % fargs) + return + + +def wrap_trace(obj, hook=trace_print_hook, + which=None, events=None, label=None): + """Monitor an object for interactions. Whenever code calls a method, + gets an attribute, or sets an attribute, an event is called. By + default the trace output is printed, but a custom tracing *hook* + can be passed. + + Args: + obj (object): New- or old-style object to be traced. Built-in + objects like lists and dicts also supported. + hook (callable): A function called once for every event. See + below for details. + which (str): One or more attribute names to trace, or a + function accepting attribute name and value, and returning + True/False. + events (str): One or more kinds of events to call *hook* + on. Expected values are ``['get', 'set', 'del', 'call', + 'raise', 'return']``. Defaults to all events. + label (str): A name to associate with the traced object + Defaults to hexadecimal memory address, similar to repr. + + The object returned is not the same object as the one passed + in. It will not pass identity checks. However, it will pass + :func:`isinstance` checks, as it is a new instance of a new + subtype of the object passed. + + """ + # other actions: pdb.set_trace, print, aggregate, aggregate_return + # (like aggregate but with the return value) + + # TODO: test classmethod/staticmethod/property + # TODO: wrap __dict__ for old-style classes? + + if isinstance(which, str): + which_func = lambda attr_name, attr_val: attr_name == which + elif callable(getattr(which, '__contains__', None)): + which_func = lambda attr_name, attr_val: attr_name in which + elif which is None or callable(which): + which_func = which + else: + raise TypeError('expected attr name(s) or callable, not: %r' % which) + + label = label or hex(id(obj)) + + if isinstance(events, str): + events = [events] + do_get = not events or 'get' in events + do_set = not events or 'set' in events + do_del = not events or 'del' in events + do_call = not events or 'call' in events + do_raise = not events or 'raise' in events + do_return = not events or 'return' in events + + def wrap_method(attr_name, func, _hook=hook, _label=label): + def wrapped(*a, **kw): + a = a[1:] + if do_call: + hook(event='call', label=_label, obj=obj, + attr_name=attr_name, args=a, kwargs=kw) + if do_raise: + try: + ret = func(*a, **kw) + except Exception: + if not hook(event='raise', label=_label, obj=obj, + attr_name=attr_name, args=a, kwargs=kw, + result=sys.exc_info()): + raise + else: + ret = func(*a, **kw) + if do_return: + hook(event='return', label=_label, obj=obj, + attr_name=attr_name, args=a, kwargs=kw, result=ret) + return ret + + wrapped.__name__ = func.__name__ + wrapped.__doc__ = func.__doc__ + try: + wrapped.__module__ = func.__module__ + except Exception: + pass + try: + if func.__dict__: + wrapped.__dict__.update(func.__dict__) + except Exception: + pass + return wrapped + + def __getattribute__(self, attr_name): + ret = type(obj).__getattribute__(obj, attr_name) + if callable(ret): # wrap any bound methods + ret = type(obj).__getattribute__(self, attr_name) + if do_get: + hook('get', label, obj, attr_name, (), {}, result=ret) + return ret + + def __setattr__(self, attr_name, value): + type(obj).__setattr__(obj, attr_name, value) + if do_set: + hook('set', label, obj, attr_name, (value,), {}) + return + + def __delattr__(self, attr_name): + type(obj).__delattr__(obj, attr_name) + if do_del: + hook('del', label, obj, attr_name, (), {}) + return + + attrs = {} + for attr_name in dir(obj): + try: + attr_val = getattr(obj, attr_name) + except Exception: + continue + + if not callable(attr_val) or attr_name in ('__new__',): + continue + elif which_func and not which_func(attr_name, attr_val): + continue + + if attr_name == '__getattribute__': + wrapped_method = __getattribute__ + elif attr_name == '__setattr__': + wrapped_method = __setattr__ + elif attr_name == '__delattr__': + wrapped_method = __delattr__ + else: + wrapped_method = wrap_method(attr_name, attr_val) + attrs[attr_name] = wrapped_method + + cls_name = obj.__class__.__name__ + if cls_name == cls_name.lower(): + type_name = 'traced_' + cls_name + else: + type_name = 'Traced' + cls_name + + if hasattr(obj, '__mro__'): + bases = (obj.__class__,) + else: + # need new-style class for even basic wrapping of callables to + # work. getattribute won't work for old-style classes of course. + bases = (obj.__class__, object) + + trace_type = type(type_name, bases, attrs) + for cls in trace_type.__mro__: + try: + return cls.__new__(trace_type) + except Exception: + pass + raise TypeError('unable to wrap_trace %r instance %r' + % (obj.__class__, obj)) + + diff --git a/data/miniconda3/lib/python3.13/site-packages/boltons/deprutils.py b/data/miniconda3/lib/python3.13/site-packages/boltons/deprutils.py new file mode 100644 index 0000000000000000000000000000000000000000..6c56736f98156e3b1aa63d867f23f400601bab8a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/boltons/deprutils.py @@ -0,0 +1,63 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# * The names of the contributors may not be used to endorse or +# promote products derived from this software without specific +# prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +import sys +from types import ModuleType +from warnings import warn + +# todo: only warn once + + +class DeprecatableModule(ModuleType): + def __init__(self, module): + name = module.__name__ + super().__init__(name=name) + self.__dict__.update(module.__dict__) + + def __getattribute__(self, name): + get_attribute = super().__getattribute__ + try: + depros = get_attribute('_deprecated_members') + except AttributeError: + self._deprecated_members = depros = {} + ret = get_attribute(name) + message = depros.get(name) + if message is not None: + warn(message, DeprecationWarning, stacklevel=2) + return ret + + +def deprecate_module_member(mod_name, name, message): + module = sys.modules[mod_name] + if not isinstance(module, DeprecatableModule): + sys.modules[mod_name] = module = DeprecatableModule(module) + module._deprecated_members[name] = message + return diff --git a/data/miniconda3/lib/python3.13/site-packages/boltons/dictutils.py b/data/miniconda3/lib/python3.13/site-packages/boltons/dictutils.py new file mode 100644 index 0000000000000000000000000000000000000000..f913f29f61fc4e1d2f5f5ef6dc32936817ab33f2 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/boltons/dictutils.py @@ -0,0 +1,1120 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# * The names of the contributors may not be used to endorse or +# promote products derived from this software without specific +# prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Python has a very powerful mapping type at its core: the :class:`dict` +type. While versatile and featureful, the :class:`dict` prioritizes +simplicity and performance. As a result, it does not retain the order +of item insertion [1]_, nor does it store multiple values per key. It +is a fast, unordered 1:1 mapping. + +The :class:`OrderedMultiDict` contrasts to the built-in :class:`dict`, +as a relatively maximalist, ordered 1:n subtype of +:class:`dict`. Virtually every feature of :class:`dict` has been +retooled to be intuitive in the face of this added +complexity. Additional methods have been added, such as +:class:`collections.Counter`-like functionality. + +A prime advantage of the :class:`OrderedMultiDict` (OMD) is its +non-destructive nature. Data can be added to an :class:`OMD` without being +rearranged or overwritten. The property can allow the developer to +work more freely with the data, as well as make more assumptions about +where input data will end up in the output, all without any extra +work. + +One great example of this is the :meth:`OMD.inverted()` method, which +returns a new OMD with the values as keys and the keys as values. All +the data and the respective order is still represented in the inverted +form, all from an operation which would be outright wrong and reckless +with a built-in :class:`dict` or :class:`collections.OrderedDict`. + +The OMD has been performance tuned to be suitable for a wide range of +usages, including as a basic unordered MultiDict. Special +thanks to `Mark Williams`_ for all his help. + +.. [1] As of 2015, `basic dicts on PyPy are ordered + `_, + and as of December 2017, `basic dicts in CPython 3 are now ordered + `_, as + well. +.. _Mark Williams: https://github.com/markrwilliams + +""" + +from collections.abc import KeysView, ValuesView, ItemsView +from itertools import zip_longest + +try: + from .typeutils import make_sentinel + _MISSING = make_sentinel(var_name='_MISSING') +except ImportError: + _MISSING = object() + + +PREV, NEXT, KEY, VALUE, SPREV, SNEXT = range(6) + + +__all__ = ['MultiDict', 'OMD', 'OrderedMultiDict', 'OneToOne', 'ManyToMany', 'subdict', 'FrozenDict'] + + +class OrderedMultiDict(dict): + """A MultiDict is a dictionary that can have multiple values per key + and the OrderedMultiDict (OMD) is a MultiDict that retains + original insertion order. Common use cases include: + + * handling query strings parsed from URLs + * inverting a dictionary to create a reverse index (values to keys) + * stacking data from multiple dictionaries in a non-destructive way + + The OrderedMultiDict constructor is identical to the built-in + :class:`dict`, and overall the API constitutes an intuitive + superset of the built-in type: + + >>> omd = OrderedMultiDict() + >>> omd['a'] = 1 + >>> omd['b'] = 2 + >>> omd.add('a', 3) + >>> omd.get('a') + 3 + >>> omd.getlist('a') + [1, 3] + + Some non-:class:`dict`-like behaviors also make an appearance, + such as support for :func:`reversed`: + + >>> list(reversed(omd)) + ['b', 'a'] + + Note that unlike some other MultiDicts, this OMD gives precedence + to the most recent value added. ``omd['a']`` refers to ``3``, not + ``1``. + + >>> omd + OrderedMultiDict([('a', 1), ('b', 2), ('a', 3)]) + >>> omd.poplast('a') + 3 + >>> omd + OrderedMultiDict([('a', 1), ('b', 2)]) + >>> omd.pop('a') + 1 + >>> omd + OrderedMultiDict([('b', 2)]) + + If you want a safe-to-modify or flat dictionary, use + :meth:`OrderedMultiDict.todict()`. + + >>> from pprint import pprint as pp # preserve printed ordering + >>> omd = OrderedMultiDict([('a', 1), ('b', 2), ('a', 3)]) + >>> pp(omd.todict()) + {'a': 3, 'b': 2} + >>> pp(omd.todict(multi=True)) + {'a': [1, 3], 'b': [2]} + + With ``multi=False``, items appear with the keys in to original + insertion order, alongside the most-recently inserted value for + that key. + + >>> OrderedMultiDict([('a', 1), ('b', 2), ('a', 3)]).items(multi=False) + [('a', 3), ('b', 2)] + + .. warning:: + + ``dict(omd)`` changed behavior `in Python 3.7 + `_ due to changes made to + support the transition from :class:`collections.OrderedDict` to + the built-in dictionary being ordered. Before 3.7, the result + would be a new dictionary, with values that were lists, similar + to ``omd.todict(multi=True)`` (but only shallow-copy; the lists + were direct references to OMD internal structures). From 3.7 + onward, the values became singular, like + ``omd.todict(multi=False)``. For reliable cross-version + behavior, just use :meth:`~OrderedMultiDict.todict()`. + + """ + def __new__(cls, *a, **kw): + ret = super().__new__(cls) + ret._clear_ll() + return ret + + def __init__(self, *args, **kwargs): + if len(args) > 1: + raise TypeError('%s expected at most 1 argument, got %s' + % (self.__class__.__name__, len(args))) + super().__init__() + + if args: + self.update_extend(args[0]) + if kwargs: + self.update(kwargs) + + def __getstate__(self): + return list(self.iteritems(multi=True)) + + def __setstate__(self, state): + self.clear() + self.update_extend(state) + + def _clear_ll(self): + try: + _map = self._map + except AttributeError: + _map = self._map = {} + self.root = [] + _map.clear() + self.root[:] = [self.root, self.root, None] + + def _insert(self, k, v): + root = self.root + cells = self._map.setdefault(k, []) + last = root[PREV] + cell = [last, root, k, v] + last[NEXT] = root[PREV] = cell + cells.append(cell) + + def add(self, k, v): + """Add a single value *v* under a key *k*. Existing values under *k* + are preserved. + """ + values = super().setdefault(k, []) + self._insert(k, v) + values.append(v) + + def addlist(self, k, v): + """Add an iterable of values underneath a specific key, preserving + any values already under that key. + + >>> omd = OrderedMultiDict([('a', -1)]) + >>> omd.addlist('a', range(3)) + >>> omd + OrderedMultiDict([('a', -1), ('a', 0), ('a', 1), ('a', 2)]) + + Called ``addlist`` for consistency with :meth:`getlist`, but + tuples and other sequences and iterables work. + """ + if not v: + return + self_insert = self._insert + values = super().setdefault(k, []) + for subv in v: + self_insert(k, subv) + values.extend(v) + + def get(self, k, default=None): + """Return the value for key *k* if present in the dictionary, else + *default*. If *default* is not given, ``None`` is returned. + This method never raises a :exc:`KeyError`. + + To get all values under a key, use :meth:`OrderedMultiDict.getlist`. + """ + return super().get(k, [default])[-1] + + def getlist(self, k, default=_MISSING): + """Get all values for key *k* as a list, if *k* is in the + dictionary, else *default*. The list returned is a copy and + can be safely mutated. If *default* is not given, an empty + :class:`list` is returned. + """ + try: + return super().__getitem__(k)[:] + except KeyError: + if default is _MISSING: + return [] + return default + + def clear(self): + "Empty the dictionary." + super().clear() + self._clear_ll() + + def setdefault(self, k, default=_MISSING): + """If key *k* is in the dictionary, return its value. If not, insert + *k* with a value of *default* and return *default*. *default* + defaults to ``None``. See :meth:`dict.setdefault` for more + information. + """ + if not super().__contains__(k): + self[k] = None if default is _MISSING else default + return self[k] + + def copy(self): + "Return a shallow copy of the dictionary." + return self.__class__(self.iteritems(multi=True)) + + @classmethod + def fromkeys(cls, keys, default=None): + """Create a dictionary from a list of keys, with all the values + set to *default*, or ``None`` if *default* is not set. + """ + return cls([(k, default) for k in keys]) + + def update(self, E, **F): + """Add items from a dictionary or iterable (and/or keyword arguments), + overwriting values under an existing key. See + :meth:`dict.update` for more details. + """ + # E and F are throwback names to the dict() __doc__ + if E is self: + return + self_add = self.add + if isinstance(E, OrderedMultiDict): + for k in E: + if k in self: + del self[k] + for k, v in E.iteritems(multi=True): + self_add(k, v) + elif callable(getattr(E, 'keys', None)): + for k in E.keys(): + self[k] = E[k] + else: + seen = set() + seen_add = seen.add + for k, v in E: + if k not in seen and k in self: + del self[k] + seen_add(k) + self_add(k, v) + for k in F: + self[k] = F[k] + return + + def update_extend(self, E, **F): + """Add items from a dictionary, iterable, and/or keyword + arguments without overwriting existing items present in the + dictionary. Like :meth:`update`, but adds to existing keys + instead of overwriting them. + """ + if E is self: + iterator = iter(E.items()) + elif isinstance(E, OrderedMultiDict): + iterator = E.iteritems(multi=True) + elif hasattr(E, 'keys'): + iterator = ((k, E[k]) for k in E.keys()) + else: + iterator = E + + self_add = self.add + for k, v in iterator: + self_add(k, v) + + def __setitem__(self, k, v): + if super().__contains__(k): + self._remove_all(k) + self._insert(k, v) + super().__setitem__(k, [v]) + + def __getitem__(self, k): + return super().__getitem__(k)[-1] + + def __delitem__(self, k): + super().__delitem__(k) + self._remove_all(k) + + def __eq__(self, other): + if self is other: + return True + try: + if len(other) != len(self): + return False + except TypeError: + return False + if isinstance(other, OrderedMultiDict): + selfi = self.iteritems(multi=True) + otheri = other.iteritems(multi=True) + zipped_items = zip_longest(selfi, otheri, fillvalue=(None, None)) + for (selfk, selfv), (otherk, otherv) in zipped_items: + if selfk != otherk or selfv != otherv: + return False + if not(next(selfi, _MISSING) is _MISSING + and next(otheri, _MISSING) is _MISSING): + # leftovers (TODO: watch for StopIteration?) + return False + return True + elif hasattr(other, 'keys'): + for selfk in self: + try: + other[selfk] == self[selfk] + except KeyError: + return False + return True + return False + + def __ne__(self, other): + return not (self == other) + + def __ior__(self, other): + self.update(other) + return self + + def pop(self, k, default=_MISSING): + """Remove all values under key *k*, returning the most-recently + inserted value. Raises :exc:`KeyError` if the key is not + present and no *default* is provided. + """ + try: + return self.popall(k)[-1] + except KeyError: + if default is _MISSING: + raise KeyError(k) + return default + + def popall(self, k, default=_MISSING): + """Remove all values under key *k*, returning them in the form of + a list. Raises :exc:`KeyError` if the key is not present and no + *default* is provided. + """ + super_self = super() + if super_self.__contains__(k): + self._remove_all(k) + if default is _MISSING: + return super_self.pop(k) + return super_self.pop(k, default) + + def poplast(self, k=_MISSING, default=_MISSING): + """Remove and return the most-recently inserted value under the key + *k*, or the most-recently inserted key if *k* is not + provided. If no values remain under *k*, it will be removed + from the OMD. Raises :exc:`KeyError` if *k* is not present in + the dictionary, or the dictionary is empty. + """ + if k is _MISSING: + if self: + k = self.root[PREV][KEY] + else: + if default is _MISSING: + raise KeyError('empty %r' % type(self)) + return default + try: + self._remove(k) + except KeyError: + if default is _MISSING: + raise KeyError(k) + return default + values = super().__getitem__(k) + v = values.pop() + if not values: + super().__delitem__(k) + return v + + def _remove(self, k): + values = self._map[k] + cell = values.pop() + cell[PREV][NEXT], cell[NEXT][PREV] = cell[NEXT], cell[PREV] + if not values: + del self._map[k] + + def _remove_all(self, k): + values = self._map[k] + while values: + cell = values.pop() + cell[PREV][NEXT], cell[NEXT][PREV] = cell[NEXT], cell[PREV] + del self._map[k] + + def iteritems(self, multi=False): + """Iterate over the OMD's items in insertion order. By default, + yields only the most-recently inserted value for each key. Set + *multi* to ``True`` to get all inserted items. + """ + root = self.root + curr = root[NEXT] + if multi: + while curr is not root: + yield curr[KEY], curr[VALUE] + curr = curr[NEXT] + else: + for key in self.iterkeys(): + yield key, self[key] + + def iterkeys(self, multi=False): + """Iterate over the OMD's keys in insertion order. By default, yields + each key once, according to the most recent insertion. Set + *multi* to ``True`` to get all keys, including duplicates, in + insertion order. + """ + root = self.root + curr = root[NEXT] + if multi: + while curr is not root: + yield curr[KEY] + curr = curr[NEXT] + else: + yielded = set() + yielded_add = yielded.add + while curr is not root: + k = curr[KEY] + if k not in yielded: + yielded_add(k) + yield k + curr = curr[NEXT] + + def itervalues(self, multi=False): + """Iterate over the OMD's values in insertion order. By default, + yields the most-recently inserted value per unique key. Set + *multi* to ``True`` to get all values according to insertion + order. + """ + for k, v in self.iteritems(multi=multi): + yield v + + def todict(self, multi=False): + """Gets a basic :class:`dict` of the items in this dictionary. Keys + are the same as the OMD, values are the most recently inserted + values for each key. + + Setting the *multi* arg to ``True`` is yields the same + result as calling :class:`dict` on the OMD, except that all the + value lists are copies that can be safely mutated. + """ + if multi: + return {k: self.getlist(k) for k in self} + return {k: self[k] for k in self} + + def sorted(self, key=None, reverse=False): + """Similar to the built-in :func:`sorted`, except this method returns + a new :class:`OrderedMultiDict` sorted by the provided key + function, optionally reversed. + + Args: + key (callable): A callable to determine the sort key of + each element. The callable should expect an **item** + (key-value pair tuple). + reverse (bool): Set to ``True`` to reverse the ordering. + + >>> omd = OrderedMultiDict(zip(range(3), range(3))) + >>> omd.sorted(reverse=True) + OrderedMultiDict([(2, 2), (1, 1), (0, 0)]) + + Note that the key function receives an **item** (key-value + tuple), so the recommended signature looks like: + + >>> omd = OrderedMultiDict(zip('hello', 'world')) + >>> omd.sorted(key=lambda i: i[1]) # i[0] is the key, i[1] is the val + OrderedMultiDict([('o', 'd'), ('l', 'l'), ('e', 'o'), ('l', 'r'), ('h', 'w')]) + """ + cls = self.__class__ + return cls(sorted(self.iteritems(multi=True), key=key, reverse=reverse)) + + def sortedvalues(self, key=None, reverse=False): + """Returns a copy of the :class:`OrderedMultiDict` with the same keys + in the same order as the original OMD, but the values within + each keyspace have been sorted according to *key* and + *reverse*. + + Args: + key (callable): A single-argument callable to determine + the sort key of each element. The callable should expect + an **item** (key-value pair tuple). + reverse (bool): Set to ``True`` to reverse the ordering. + + >>> omd = OrderedMultiDict() + >>> omd.addlist('even', [6, 2]) + >>> omd.addlist('odd', [1, 5]) + >>> omd.add('even', 4) + >>> omd.add('odd', 3) + >>> somd = omd.sortedvalues() + >>> somd.getlist('even') + [2, 4, 6] + >>> somd.keys(multi=True) == omd.keys(multi=True) + True + >>> omd == somd + False + >>> somd + OrderedMultiDict([('even', 2), ('even', 4), ('odd', 1), ('odd', 3), ('even', 6), ('odd', 5)]) + + As demonstrated above, contents and key order are + retained. Only value order changes. + """ + try: + superself_iteritems = super().iteritems() + except AttributeError: + superself_iteritems = super().items() + # (not reverse) because they pop off in reverse order for reinsertion + sorted_val_map = {k: sorted(v, key=key, reverse=(not reverse)) + for k, v in superself_iteritems} + ret = self.__class__() + for k in self.iterkeys(multi=True): + ret.add(k, sorted_val_map[k].pop()) + return ret + + def inverted(self): + """Returns a new :class:`OrderedMultiDict` with values and keys + swapped, like creating dictionary transposition or reverse + index. Insertion order is retained and all keys and values + are represented in the output. + + >>> omd = OMD([(0, 2), (1, 2)]) + >>> omd.inverted().getlist(2) + [0, 1] + + Inverting twice yields a copy of the original: + + >>> omd.inverted().inverted() + OrderedMultiDict([(0, 2), (1, 2)]) + """ + return self.__class__((v, k) for k, v in self.iteritems(multi=True)) + + def counts(self): + """Returns a mapping from key to number of values inserted under that + key. Like :py:class:`collections.Counter`, but returns a new + :class:`OrderedMultiDict`. + """ + # Returns an OMD because Counter/OrderedDict may not be + # available, and neither Counter nor dict maintain order. + super_getitem = super().__getitem__ + return self.__class__((k, len(super_getitem(k))) for k in self) + + def keys(self, multi=False): + """Returns a list containing the output of :meth:`iterkeys`. See + that method's docs for more details. + """ + return list(self.iterkeys(multi=multi)) + + def values(self, multi=False): + """Returns a list containing the output of :meth:`itervalues`. See + that method's docs for more details. + """ + return list(self.itervalues(multi=multi)) + + def items(self, multi=False): + """Returns a list containing the output of :meth:`iteritems`. See + that method's docs for more details. + """ + return list(self.iteritems(multi=multi)) + + def __iter__(self): + return self.iterkeys() + + def __reversed__(self): + root = self.root + curr = root[PREV] + lengths = {} + lengths_sd = lengths.setdefault + get_values = super().__getitem__ + while curr is not root: + k = curr[KEY] + vals = get_values(k) + if lengths_sd(k, 1) == len(vals): + yield k + lengths[k] += 1 + curr = curr[PREV] + + def __repr__(self): + cn = self.__class__.__name__ + kvs = ', '.join([repr((k, v)) for k, v in self.iteritems(multi=True)]) + return f'{cn}([{kvs}])' + + def viewkeys(self): + "OMD.viewkeys() -> a set-like object providing a view on OMD's keys" + return KeysView(self) + + def viewvalues(self): + "OMD.viewvalues() -> an object providing a view on OMD's values" + return ValuesView(self) + + def viewitems(self): + "OMD.viewitems() -> a set-like object providing a view on OMD's items" + return ItemsView(self) + + +# A couple of convenient aliases +OMD = OrderedMultiDict +MultiDict = OrderedMultiDict + + +class FastIterOrderedMultiDict(OrderedMultiDict): + """An OrderedMultiDict backed by a skip list. Iteration over keys + is faster and uses constant memory but adding duplicate key-value + pairs is slower. Brainchild of Mark Williams. + """ + def _clear_ll(self): + # TODO: always reset objects? (i.e., no else block below) + try: + _map = self._map + except AttributeError: + _map = self._map = {} + self.root = [] + _map.clear() + self.root[:] = [self.root, self.root, + None, None, + self.root, self.root] + + def _insert(self, k, v): + root = self.root + empty = [] + cells = self._map.setdefault(k, empty) + last = root[PREV] + + if cells is empty: + cell = [last, root, + k, v, + last, root] + # was the last one skipped? + if last[SPREV][SNEXT] is root: + last[SPREV][SNEXT] = cell + last[NEXT] = last[SNEXT] = root[PREV] = root[SPREV] = cell + cells.append(cell) + else: + # if the previous was skipped, go back to the cell that + # skipped it + sprev = last[SPREV] if (last[SPREV][SNEXT] is not last) else last + cell = [last, root, + k, v, + sprev, root] + # skip me + last[SNEXT] = root + last[NEXT] = root[PREV] = root[SPREV] = cell + cells.append(cell) + + def _remove(self, k): + cells = self._map[k] + cell = cells.pop() + if not cells: + del self._map[k] + cell[PREV][SNEXT] = cell[SNEXT] + + if cell[PREV][SPREV][SNEXT] is cell: + cell[PREV][SPREV][SNEXT] = cell[NEXT] + elif cell[SNEXT] is cell[NEXT]: + cell[SPREV][SNEXT], cell[SNEXT][SPREV] = cell[SNEXT], cell[SPREV] + + cell[PREV][NEXT], cell[NEXT][PREV] = cell[NEXT], cell[PREV] + + def _remove_all(self, k): + cells = self._map.pop(k) + while cells: + cell = cells.pop() + if cell[PREV][SPREV][SNEXT] is cell: + cell[PREV][SPREV][SNEXT] = cell[NEXT] + elif cell[SNEXT] is cell[NEXT]: + cell[SPREV][SNEXT], cell[SNEXT][SPREV] = cell[SNEXT], cell[SPREV] + + cell[PREV][NEXT], cell[NEXT][PREV] = cell[NEXT], cell[PREV] + cell[PREV][SNEXT] = cell[SNEXT] + + def iteritems(self, multi=False): + next_link = NEXT if multi else SNEXT + root = self.root + curr = root[next_link] + while curr is not root: + yield curr[KEY], curr[VALUE] + curr = curr[next_link] + + def iterkeys(self, multi=False): + next_link = NEXT if multi else SNEXT + root = self.root + curr = root[next_link] + while curr is not root: + yield curr[KEY] + curr = curr[next_link] + + def __reversed__(self): + root = self.root + curr = root[PREV] + while curr is not root: + if curr[SPREV][SNEXT] is not curr: + curr = curr[SPREV] + if curr is root: + break + yield curr[KEY] + curr = curr[PREV] + + +_OTO_INV_MARKER = object() +_OTO_UNIQUE_MARKER = object() + + +class OneToOne(dict): + """Implements a one-to-one mapping dictionary. In addition to + inheriting from and behaving exactly like the builtin + :class:`dict`, all values are automatically added as keys on a + reverse mapping, available as the `inv` attribute. This + arrangement keeps key and value namespaces distinct. + + Basic operations are intuitive: + + >>> oto = OneToOne({'a': 1, 'b': 2}) + >>> print(oto['a']) + 1 + >>> print(oto.inv[1]) + a + >>> len(oto) + 2 + + Overwrites happens in both directions: + + >>> oto.inv[1] = 'c' + >>> print(oto.get('a')) + None + >>> len(oto) + 2 + + For a very similar project, with even more one-to-one + functionality, check out `bidict `_. + """ + __slots__ = ('inv',) + + def __init__(self, *a, **kw): + raise_on_dupe = False + if a: + if a[0] is _OTO_INV_MARKER: + self.inv = a[1] + dict.__init__(self, [(v, k) for k, v in self.inv.items()]) + return + elif a[0] is _OTO_UNIQUE_MARKER: + a, raise_on_dupe = a[1:], True + + dict.__init__(self, *a, **kw) + self.inv = self.__class__(_OTO_INV_MARKER, self) + + if len(self) == len(self.inv): + # if lengths match, that means everything's unique + return + + if not raise_on_dupe: + dict.clear(self) + dict.update(self, [(v, k) for k, v in self.inv.items()]) + return + + # generate an error message if the values aren't 1:1 + + val_multidict = {} + for k, v in self.items(): + val_multidict.setdefault(v, []).append(k) + + dupes = {v: k_list for v, k_list in + val_multidict.items() if len(k_list) > 1} + + raise ValueError('expected unique values, got multiple keys for' + ' the following values: %r' % dupes) + + @classmethod + def unique(cls, *a, **kw): + """This alternate constructor for OneToOne will raise an exception + when input values overlap. For instance: + + >>> OneToOne.unique({'a': 1, 'b': 1}) + Traceback (most recent call last): + ... + ValueError: expected unique values, got multiple keys for the following values: ... + + This even works across inputs: + + >>> a_dict = {'a': 2} + >>> OneToOne.unique(a_dict, b=2) + Traceback (most recent call last): + ... + ValueError: expected unique values, got multiple keys for the following values: ... + """ + return cls(_OTO_UNIQUE_MARKER, *a, **kw) + + def __setitem__(self, key, val): + hash(val) # ensure val is a valid key + if key in self: + dict.__delitem__(self.inv, self[key]) + if val in self.inv: + del self.inv[val] + dict.__setitem__(self, key, val) + dict.__setitem__(self.inv, val, key) + + def __delitem__(self, key): + dict.__delitem__(self.inv, self[key]) + dict.__delitem__(self, key) + + def clear(self): + dict.clear(self) + dict.clear(self.inv) + + def copy(self): + return self.__class__(self) + + def pop(self, key, default=_MISSING): + if key in self: + dict.__delitem__(self.inv, self[key]) + return dict.pop(self, key) + if default is not _MISSING: + return default + raise KeyError() + + def popitem(self): + key, val = dict.popitem(self) + dict.__delitem__(self.inv, val) + return key, val + + def setdefault(self, key, default=None): + if key not in self: + self[key] = default + return self[key] + + def update(self, dict_or_iterable, **kw): + keys_vals = [] + if isinstance(dict_or_iterable, dict): + for val in dict_or_iterable.values(): + hash(val) + keys_vals = list(dict_or_iterable.items()) + else: + for key, val in dict_or_iterable: + hash(key) + hash(val) + keys_vals = list(dict_or_iterable) + for val in kw.values(): + hash(val) + keys_vals.extend(kw.items()) + for key, val in keys_vals: + self[key] = val + + def __repr__(self): + cn = self.__class__.__name__ + dict_repr = dict.__repr__(self) + return f"{cn}({dict_repr})" + + +# marker for the secret handshake used internally to set up the invert ManyToMany +_PAIRING = object() + + +class ManyToMany: + """ + a dict-like entity that represents a many-to-many relationship + between two groups of objects + + behaves like a dict-of-tuples; also has .inv which is kept + up to date which is a dict-of-tuples in the other direction + + also, can be used as a directed graph among hashable python objects + """ + def __init__(self, items=None): + self.data = {} + if type(items) is tuple and items and items[0] is _PAIRING: + self.inv = items[1] + else: + self.inv = self.__class__((_PAIRING, self)) + if items: + self.update(items) + return + + def get(self, key, default=frozenset()): + try: + return self[key] + except KeyError: + return default + + def __getitem__(self, key): + return frozenset(self.data[key]) + + def __setitem__(self, key, vals): + vals = set(vals) + if key in self: + to_remove = self.data[key] - vals + vals -= self.data[key] + for val in to_remove: + self.remove(key, val) + for val in vals: + self.add(key, val) + + def __delitem__(self, key): + for val in self.data.pop(key): + self.inv.data[val].remove(key) + if not self.inv.data[val]: + del self.inv.data[val] + + def update(self, iterable): + """given an iterable of (key, val), add them all""" + if type(iterable) is type(self): + other = iterable + for k in other.data: + if k not in self.data: + self.data[k] = other.data[k] + else: + self.data[k].update(other.data[k]) + for k in other.inv.data: + if k not in self.inv.data: + self.inv.data[k] = other.inv.data[k] + else: + self.inv.data[k].update(other.inv.data[k]) + elif callable(getattr(iterable, 'keys', None)): + for k in iterable.keys(): + self.add(k, iterable[k]) + else: + for key, val in iterable: + self.add(key, val) + return + + def add(self, key, val): + if key not in self.data: + self.data[key] = set() + self.data[key].add(val) + if val not in self.inv.data: + self.inv.data[val] = set() + self.inv.data[val].add(key) + + def remove(self, key, val): + self.data[key].remove(val) + if not self.data[key]: + del self.data[key] + self.inv.data[val].remove(key) + if not self.inv.data[val]: + del self.inv.data[val] + + def replace(self, key, newkey): + """ + replace instances of key by newkey + """ + if key not in self.data: + return + self.data[newkey] = fwdset = self.data.pop(key) + for val in fwdset: + revset = self.inv.data[val] + revset.remove(key) + revset.add(newkey) + + def iteritems(self): + for key in self.data: + for val in self.data[key]: + yield key, val + + def keys(self): + return self.data.keys() + + def __contains__(self, key): + return key in self.data + + def __iter__(self): + return self.data.__iter__() + + def __len__(self): + return self.data.__len__() + + def __eq__(self, other): + return type(self) == type(other) and self.data == other.data + + def __repr__(self): + cn = self.__class__.__name__ + return f'{cn}({list(self.iteritems())!r})' + + +def subdict(d, keep=None, drop=None): + """Compute the "subdictionary" of a dict, *d*. + + A subdict is to a dict what a subset is a to set. If *A* is a + subdict of *B*, that means that all keys of *A* are present in + *B*. + + Returns a new dict with any keys in *drop* removed, and any keys + in *keep* still present, provided they were in the original + dict. *keep* defaults to all keys, *drop* defaults to empty, so + without one of these arguments, calling this function is + equivalent to calling ``dict()``. + + >>> from pprint import pprint as pp + >>> pp(subdict({'a': 1, 'b': 2})) + {'a': 1, 'b': 2} + >>> subdict({'a': 1, 'b': 2, 'c': 3}, drop=['b', 'c']) + {'a': 1} + >>> pp(subdict({'a': 1, 'b': 2, 'c': 3}, keep=['a', 'c'])) + {'a': 1, 'c': 3} + + """ + if keep is None: + keep = d.keys() + if drop is None: + drop = [] + + keys = set(keep) - set(drop) + + return type(d)([(k, v) for k, v in d.items() if k in keys]) + + +class FrozenHashError(TypeError): + pass + + +class FrozenDict(dict): + """An immutable dict subtype that is hashable and can itself be used + as a :class:`dict` key or :class:`set` entry. What + :class:`frozenset` is to :class:`set`, FrozenDict is to + :class:`dict`. + + There was once an attempt to introduce such a type to the standard + library, but it was rejected: `PEP 416 `_. + + Because FrozenDict is a :class:`dict` subtype, it automatically + works everywhere a dict would, including JSON serialization. + + """ + __slots__ = ('_hash',) + + def updated(self, *a, **kw): + """Make a copy and add items from a dictionary or iterable (and/or + keyword arguments), overwriting values under an existing + key. See :meth:`dict.update` for more details. + """ + data = dict(self) + data.update(*a, **kw) + return type(self)(data) + + @classmethod + def fromkeys(cls, keys, value=None): + # one of the lesser known and used/useful dict methods + return cls(dict.fromkeys(keys, value)) + + def __repr__(self): + cn = self.__class__.__name__ + return f'{cn}({dict.__repr__(self)})' + + def __reduce_ex__(self, protocol): + return type(self), (dict(self),) + + def __hash__(self): + try: + ret = self._hash + except AttributeError: + try: + ret = self._hash = hash(frozenset(self.items())) + except Exception as e: + ret = self._hash = FrozenHashError(e) + + if ret.__class__ is FrozenHashError: + raise ret + + return ret + + def __copy__(self): + return self # immutable types don't copy, see tuple's behavior + + # block everything else + def _raise_frozen_typeerror(self, *a, **kw): + "raises a TypeError, because FrozenDicts are immutable" + raise TypeError('%s object is immutable' % self.__class__.__name__) + + __ior__ = __setitem__ = __delitem__ = update = _raise_frozen_typeerror + setdefault = pop = popitem = clear = _raise_frozen_typeerror + + del _raise_frozen_typeerror + + +# end dictutils.py diff --git a/data/miniconda3/lib/python3.13/site-packages/boltons/easterutils.py b/data/miniconda3/lib/python3.13/site-packages/boltons/easterutils.py new file mode 100644 index 0000000000000000000000000000000000000000..02a930a6b26d714b1037fff3059293a6a23ac0e6 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/boltons/easterutils.py @@ -0,0 +1,44 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# * The names of the contributors may not be used to endorse or +# promote products derived from this software without specific +# prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + + +def gobs_program(): + """ + A pure-Python implementation of Gob's Algorithm (2006). A brief + explanation can be found here: + https://www.youtube.com/watch?v=JbnjusltDHk + """ + while True: + print("Penus", end=" ") + + +if __name__ == '__main__': + gobs_program() diff --git a/data/miniconda3/lib/python3.13/site-packages/boltons/ecoutils.py b/data/miniconda3/lib/python3.13/site-packages/boltons/ecoutils.py new file mode 100644 index 0000000000000000000000000000000000000000..23fb25fbf329a4b10ea5c4fa5c3fd250257b12ee --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/boltons/ecoutils.py @@ -0,0 +1,479 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# * The names of the contributors may not be used to endorse or +# promote products derived from this software without specific +# prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""As a programming ecosystem grows, so do the chances of runtime +variability. + +Python boasts one of the widest deployments for a high-level +programming environment, making it a viable target for all manner of +application. But with breadth comes variance, so it's important to +know what you're working with. + +Some basic variations that are common among development machines: + +* **Executable runtime**: CPython, PyPy, Jython, etc., plus build date and compiler +* **Language version**: 2.7 through 3.12 +* **Host operating system**: Windows, OS X, Ubuntu, Debian, CentOS, RHEL, etc. +* **Features**: 64-bit, IPv6, Unicode character support (UCS-2/UCS-4) +* **Built-in library support**: OpenSSL, threading, SQLite, zlib +* **User environment**: umask, ulimit, working directory path +* **Machine info**: CPU count, hostname, filesystem encoding + +See the full example profile below for more. + +ecoutils was created to quantify that variability. ecoutils quickly +produces an information-dense description of critical runtime factors, +with minimal side effects. In short, ecoutils is like browser and user +agent analytics, but for Python environments. + +Transmission and collection +--------------------------- + +The data is all JSON serializable, and is suitable for sending to a +central analytics server. An HTTP-backed service for this can be found +at: https://github.com/mahmoud/espymetrics/ + +Notable omissions +----------------- + +Due to space constraints (and possibly latency constraints), the +following information is deemed not dense enough, and thus omitted: + +* :data:`sys.path` +* full :mod:`sysconfig` +* environment variables (:data:`os.environ`) + +Compatibility +------------- + +So far ecoutils has has been tested on Python 3.7+ and PyPy3. +Various versions have been tested on Ubuntu, Debian, +RHEL, OS X, FreeBSD, and Windows 7. + +.. note:: + + ``boltons.ecoutils`` historically supported back to Python 2.4, but in 2024, + due to increasing testing burden, ecoutils support tracks the same + versions of Python as the rest of the boltons package. + For older Pythons, see `this version`_ from boltons 23.0.0. + +.. _this version: https://github.com/mahmoud/boltons/blob/4b1d728f31a8378b193be9c966c853be0a57527d/boltons/ecoutils.py + +Profile generation +------------------ + +Profiles are generated by :func:`ecoutils.get_profile`. + +When run as a module, ecoutils will call :func:`~ecoutils.get_profile` +and print a profile in JSON format:: + + $ python -m boltons.ecoutils + { + "_eco_version": "1.0.0", + "cpu_count": 4, + "cwd": "/home/mahmoud/projects/boltons", + "fs_encoding": "UTF-8", + "guid": "6b139e7bbf5ad4ed8d4063bf6235b4d2", + "hostfqdn": "mahmoud-host", + "hostname": "mahmoud-host", + "linux_dist_name": "Ubuntu", + "linux_dist_version": "14.04", + "python": { + "argv": "boltons/ecoutils.py", + "bin": "/usr/bin/python", + "build_date": "Jun 22 2015 17:58:13", + "compiler": "GCC 4.8.2", + "features": { + "64bit": true, + "expat": "expat_2.1.0", + "ipv6": true, + "openssl": "OpenSSL 1.0.1f 6 Jan 2014", + "readline": true, + "sqlite": "3.8.2", + "threading": true, + "tkinter": "8.6", + "unicode_wide": true, + "zlib": "1.2.8" + }, + "version": "2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2]", + "version_info": [ + 2, + 7, + 6, + "final", + 0 + ] + }, + "time_utc": "2016-05-24 07:59:40.473140", + "time_utc_offset": -8.0, + "ulimit_hard": 4096, + "ulimit_soft": 1024, + "umask": "002", + "uname": { + "machine": "x86_64", + "node": "mahmoud-host", + "processor": "x86_64", + "release": "3.13.0-85-generic", + "system": "Linux", + "version": "#129-Ubuntu SMP Thu Mar 17 20:50:15 UTC 2016" + }, + "username": "mahmoud" + } + +``pip install boltons`` and try it yourself! + +""" + +import re +import os +import sys +import json +import time +import random +import socket +import struct +import getpass +import datetime +import platform + +ECO_VERSION = '1.1.0' # see version history below + + +try: + getrandbits = random.SystemRandom().getrandbits + HAVE_URANDOM = True +except Exception: + HAVE_URANDOM = False + getrandbits = random.getrandbits + + +# 128-bit GUID just like a UUID, but backwards compatible to 2.4 +INSTANCE_ID = hex(getrandbits(128))[2:-1].lower() + +IS_64BIT = struct.calcsize("P") > 4 +HAVE_UCS4 = getattr(sys, 'maxunicode', 0) > 65536 +HAVE_READLINE = True + +try: + import readline +except Exception: + HAVE_READLINE = False + +try: + import sqlite3 + SQLITE_VERSION = sqlite3.sqlite_version +except Exception: + # note: 2.5 and older have sqlite, but not sqlite3 + SQLITE_VERSION = '' + + +try: + + import ssl + try: + OPENSSL_VERSION = ssl.OPENSSL_VERSION + except AttributeError: + # This is a conservative estimate for Python <2.6 + # SSL module added in 2006, when 0.9.7 was standard + OPENSSL_VERSION = 'OpenSSL >0.8.0' +except Exception: + OPENSSL_VERSION = '' + + +try: + import tkinter + TKINTER_VERSION = str(tkinter.TkVersion) +except Exception: + TKINTER_VERSION = '' + + +try: + import zlib + ZLIB_VERSION = zlib.ZLIB_VERSION +except Exception: + ZLIB_VERSION = '' + + +try: + from xml.parsers import expat + EXPAT_VERSION = expat.EXPAT_VERSION +except Exception: + EXPAT_VERSION = '' + + +try: + from multiprocessing import cpu_count + CPU_COUNT = cpu_count() +except Exception: + CPU_COUNT = 0 + +try: + import threading + HAVE_THREADING = True +except Exception: + HAVE_THREADING = False + + +try: + HAVE_IPV6 = socket.has_ipv6 +except Exception: + HAVE_IPV6 = False + + +try: + from resource import getrlimit, RLIMIT_NOFILE + RLIMIT_FDS_SOFT, RLIMIT_FDS_HARD = getrlimit(RLIMIT_NOFILE) +except Exception: + RLIMIT_FDS_SOFT, RLIMIT_FDS_HARD = 0, 0 + + +START_TIME_INFO = {'time_utc': str(datetime.datetime.now(datetime.timezone.utc)), + 'time_utc_offset': -time.timezone / 3600.0} + + +def get_python_info(): + ret = {} + ret['argv'] = _escape_shell_args(sys.argv) + ret['bin'] = sys.executable + + # Even though compiler/build_date are already here, they're + # actually parsed from the version string. So, in the rare case of + # the unparsable version string, we're still transmitting it. + ret['version'] = ' '.join(sys.version.split()) + + ret['compiler'] = platform.python_compiler() + ret['build_date'] = platform.python_build()[1] + ret['version_info'] = list(sys.version_info) + + ret['features'] = {'openssl': OPENSSL_VERSION, + 'expat': EXPAT_VERSION, + 'sqlite': SQLITE_VERSION, + 'tkinter': TKINTER_VERSION, + 'zlib': ZLIB_VERSION, + 'unicode_wide': HAVE_UCS4, + 'readline': HAVE_READLINE, + '64bit': IS_64BIT, + 'ipv6': HAVE_IPV6, + 'threading': HAVE_THREADING, + 'urandom': HAVE_URANDOM} + + return ret + + +def get_profile(**kwargs): + """The main entrypoint to ecoutils. Calling this will return a + JSON-serializable dictionary of information about the current + process. + + It is very unlikely that the information returned will change + during the lifetime of the process, and in most cases the majority + of the information stays the same between runs as well. + + :func:`get_profile` takes one optional keyword argument, *scrub*, + a :class:`bool` that, if True, blanks out identifiable + information. This includes current working directory, hostname, + Python executable path, command-line arguments, and + username. Values are replaced with '-', but for compatibility keys + remain in place. + + """ + scrub = kwargs.pop('scrub', False) + if kwargs: + raise TypeError(f'unexpected keyword arguments: {kwargs.keys()!r}') + ret = {} + try: + ret['username'] = getpass.getuser() + except Exception: + ret['username'] = '' + ret['guid'] = str(INSTANCE_ID) + ret['hostname'] = socket.gethostname() + ret['hostfqdn'] = socket.getfqdn() + uname = platform.uname() + ret['uname'] = {'system': uname[0], + 'node': uname[1], + 'release': uname[2], # linux: distro name + 'version': uname[3], # linux: kernel version + 'machine': uname[4], + 'processor': uname[5]} + try: + # TODO: removed in 3.7, replaced with freedesktop_os_release in 3.10 + linux_dist = platform.linux_distribution() + except Exception: + linux_dist = ('', '', '') + ret['linux_dist_name'] = linux_dist[0] + ret['linux_dist_version'] = linux_dist[1] + ret['cpu_count'] = CPU_COUNT + + ret['fs_encoding'] = sys.getfilesystemencoding() + ret['ulimit_soft'] = RLIMIT_FDS_SOFT + ret['ulimit_hard'] = RLIMIT_FDS_HARD + ret['cwd'] = os.getcwd() + ret['umask'] = oct(os.umask(os.umask(2))).rjust(3, '0') + + ret['python'] = get_python_info() + ret.update(START_TIME_INFO) + ret['_eco_version'] = ECO_VERSION + + if scrub: + # mask identifiable information + ret['cwd'] = '-' + ret['hostname'] = '-' + ret['hostfqdn'] = '-' + ret['python']['bin'] = '-' + ret['python']['argv'] = '-' + ret['uname']['node'] = '-' + ret['username'] = '-' + + return ret + + +def dumps(val, indent): + if indent: + return json.dumps(val, sort_keys=True, indent=indent) + return json.dumps(val, sort_keys=True) + + +def get_profile_json(indent=False): + if indent: + indent = 2 + else: + indent = 0 + + data_dict = get_profile() + return dumps(data_dict, indent) + + +def main(): + print(get_profile_json(indent=True)) + +############################################# +# The shell escaping copied in from strutils +############################################# + + +def _escape_shell_args(args, sep=' ', style=None): + if not style: + if sys.platform == 'win32': + style = 'cmd' + else: + style = 'sh' + + if style == 'sh': + return _args2sh(args, sep=sep) + elif style == 'cmd': + return _args2cmd(args, sep=sep) + + raise ValueError("style expected one of 'cmd' or 'sh', not %r" % style) + + +_find_sh_unsafe = re.compile(r'[^a-zA-Z0-9_@%+=:,./-]').search + + +def _args2sh(args, sep=' '): + # see strutils + ret_list = [] + + for arg in args: + if not arg: + ret_list.append("''") + continue + if _find_sh_unsafe(arg) is None: + ret_list.append(arg) + continue + # use single quotes, and put single quotes into double quotes + # the string $'b is then quoted as '$'"'"'b' + ret_list.append("'" + arg.replace("'", "'\"'\"'") + "'") + + return ' '.join(ret_list) + + +def _args2cmd(args, sep=' '): + # see strutils + result = [] + needquote = False + for arg in args: + bs_buf = [] + + # Add a space to separate this argument from the others + if result: + result.append(' ') + + needquote = (" " in arg) or ("\t" in arg) or not arg + if needquote: + result.append('"') + + for c in arg: + if c == '\\': + # Don't know if we need to double yet. + bs_buf.append(c) + elif c == '"': + # Double backslashes. + result.append('\\' * len(bs_buf)*2) + bs_buf = [] + result.append('\\"') + else: + # Normal char + if bs_buf: + result.extend(bs_buf) + bs_buf = [] + result.append(c) + + # Add remaining backslashes, if any. + if bs_buf: + result.extend(bs_buf) + + if needquote: + result.extend(bs_buf) + result.append('"') + + return ''.join(result) + + +############################ +# End shell escaping code +############################ + +if __name__ == '__main__': + main() + + +""" + +ecoutils protocol version history +--------------------------------- + +The version is ECO_VERSION module-level constant, and _eco_version key +in the dictionary returned from ecoutils.get_profile(). + +1.1.0 - (boltons version 24.0.0+) Drop Python <=3.6 compat +1.0.1 - (boltons version 16.3.2+) Remove uuid dependency and add HAVE_URANDOM +1.0.0 - (boltons version 16.3.0-16.3.1) Initial release + +""" diff --git a/data/miniconda3/lib/python3.13/site-packages/boltons/excutils.py b/data/miniconda3/lib/python3.13/site-packages/boltons/excutils.py new file mode 100644 index 0000000000000000000000000000000000000000..fa3262d4d8d21207341f3f1ae4ec9b26eb866fea --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/boltons/excutils.py @@ -0,0 +1,287 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# * The names of the contributors may not be used to endorse or +# promote products derived from this software without specific +# prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +import sys +import traceback +import linecache +from collections import namedtuple + +# TODO: last arg or first arg? (last arg makes it harder to *args +# into, but makes it more readable in the default exception +# __repr__ output) +# TODO: Multiexception wrapper + + +__all__ = ['ExceptionCauseMixin'] + + +class ExceptionCauseMixin(Exception): + """ + A mixin class for wrapping an exception in another exception, or + otherwise indicating an exception was caused by another exception. + + This is most useful in concurrent or failure-intolerant scenarios, + where just because one operation failed, doesn't mean the remainder + should be aborted, or that it's the appropriate time to raise + exceptions. + + This is still a work in progress, but an example use case at the + bottom of this module. + + NOTE: when inheriting, you will probably want to put the + ExceptionCauseMixin first. Builtin exceptions are not good about + calling super() + """ + + cause = None + + def __new__(cls, *args, **kw): + cause = None + if args and isinstance(args[0], Exception): + cause, args = args[0], args[1:] + ret = super().__new__(cls, *args, **kw) + ret.cause = cause + if cause is None: + return ret + root_cause = getattr(cause, 'root_cause', None) + if root_cause is None: + ret.root_cause = cause + else: + ret.root_cause = root_cause + + full_trace = getattr(cause, 'full_trace', None) + if full_trace is not None: + ret.full_trace = list(full_trace) + ret._tb = list(cause._tb) + ret._stack = list(cause._stack) + return ret + + try: + exc_type, exc_value, exc_tb = sys.exc_info() + if exc_type is None and exc_value is None: + return ret + if cause is exc_value or root_cause is exc_value: + # handles when cause is the current exception or when + # there are multiple wraps while handling the original + # exception, but a cause was never provided + ret._tb = _extract_from_tb(exc_tb) + ret._stack = _extract_from_frame(exc_tb.tb_frame) + ret.full_trace = ret._stack[:-1] + ret._tb + finally: + del exc_tb + return ret + + def get_str(self): + """ + Get formatted the formatted traceback and exception + message. This function exists separately from __str__() + because __str__() is somewhat specialized for the built-in + traceback module's particular usage. + """ + ret = [] + trace_str = self._get_trace_str() + if trace_str: + ret.extend(['Traceback (most recent call last):\n', trace_str]) + ret.append(self._get_exc_str()) + return ''.join(ret) + + def _get_message(self): + args = getattr(self, 'args', []) + if self.cause: + args = args[1:] + if args and args[0]: + return args[0] + return '' + + def _get_trace_str(self): + if not self.cause: + return super().__repr__() + if self.full_trace: + return ''.join(traceback.format_list(self.full_trace)) + return '' + + def _get_exc_str(self, incl_name=True): + cause_str = _format_exc(self.root_cause) + message = self._get_message() + ret = [] + if incl_name: + ret = [self.__class__.__name__, ': '] + if message: + ret.extend([message, ' (caused by ', cause_str, ')']) + else: + ret.extend([' caused by ', cause_str]) + return ''.join(ret) + + def __str__(self): + if not self.cause: + return super().__str__() + trace_str = self._get_trace_str() + ret = [] + if trace_str: + message = self._get_message() + if message: + ret.extend([message, ' --- ']) + ret.extend(['Wrapped traceback (most recent call last):\n', + trace_str, + self._get_exc_str(incl_name=True)]) + return ''.join(ret) + else: + return self._get_exc_str(incl_name=False) + + +def _format_exc(exc, message=None): + if message is None: + message = exc + exc_str = traceback._format_final_exc_line(exc.__class__.__name__, message) + return exc_str.rstrip() + + +_BaseTBItem = namedtuple('_BaseTBItem', 'filename, lineno, name, line') + + +class _TBItem(_BaseTBItem): + def __repr__(self): + ret = super().__repr__() + ret += ' <%r>' % self.frame_id + return ret + + +class _DeferredLine: + def __init__(self, filename, lineno, module_globals=None): + self.filename = filename + self.lineno = lineno + module_globals = module_globals or {} + self.module_globals = {k: v for k, v in module_globals.items() + if k in ('__name__', '__loader__')} + + def __eq__(self, other): + return (self.lineno, self.filename) == (other.lineno, other.filename) + + def __ne__(self, other): + return (self.lineno, self.filename) != (other.lineno, other.filename) + + def __str__(self): + if hasattr(self, '_line'): + return self._line + linecache.checkcache(self.filename) + line = linecache.getline(self.filename, + self.lineno, + self.module_globals) + if line: + line = line.strip() + else: + line = None + self._line = line + return line + + def __repr__(self): + return repr(str(self)) + + def __len__(self): + return len(str(self)) + + def strip(self): + return str(self).strip() + + +def _extract_from_frame(f=None, limit=None): + ret = [] + if f is None: + f = sys._getframe(1) # cross-impl yadayada + if limit is None: + limit = getattr(sys, 'tracebacklimit', 1000) + n = 0 + while f is not None and n < limit: + filename = f.f_code.co_filename + lineno = f.f_lineno + name = f.f_code.co_name + line = _DeferredLine(filename, lineno, f.f_globals) + item = _TBItem(filename, lineno, name, line) + item.frame_id = id(f) + ret.append(item) + f = f.f_back + n += 1 + ret.reverse() + return ret + + +def _extract_from_tb(tb, limit=None): + ret = [] + if limit is None: + limit = getattr(sys, 'tracebacklimit', 1000) + n = 0 + while tb is not None and n < limit: + filename = tb.tb_frame.f_code.co_filename + lineno = tb.tb_lineno + name = tb.tb_frame.f_code.co_name + line = _DeferredLine(filename, lineno, tb.tb_frame.f_globals) + item = _TBItem(filename, lineno, name, line) + item.frame_id = id(tb.tb_frame) + ret.append(item) + tb = tb.tb_next + n += 1 + return ret + + +# An Example/Prototest: + + +class MathError(ExceptionCauseMixin, ValueError): + pass + + +def whoops_math(): + return 1/0 + + +def math_lol(n=0): + if n < 3: + return math_lol(n=n+1) + try: + return whoops_math() + except ZeroDivisionError as zde: + exc = MathError(zde, 'ya done messed up') + raise exc + +def main(): + try: + math_lol() + except ValueError as me: + exc = MathError(me, 'hi') + raise exc + + +if __name__ == '__main__': + try: + main() + except Exception: + import pdb;pdb.post_mortem() + raise diff --git a/data/miniconda3/lib/python3.13/site-packages/boltons/fileutils.py b/data/miniconda3/lib/python3.13/site-packages/boltons/fileutils.py new file mode 100644 index 0000000000000000000000000000000000000000..2a0577047d11697e2eba6cd639f6a3319100c243 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/boltons/fileutils.py @@ -0,0 +1,727 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# * The names of the contributors may not be used to endorse or +# promote products derived from this software without specific +# prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Virtually every Python programmer has used Python for wrangling +disk contents, and ``fileutils`` collects solutions to some of the +most commonly-found gaps in the standard library. +""" + + +import os +import re +import sys +import stat +import errno +import fnmatch +from shutil import copy2, copystat, Error + + +__all__ = ['mkdir_p', 'atomic_save', 'AtomicSaver', 'FilePerms', + 'iter_find_files', 'copytree'] + + +FULL_PERMS = 0o777 +RW_PERMS = 438 +_SINGLE_FULL_PERM = 7 + + +def mkdir_p(path): + """Creates a directory and any parent directories that may need to + be created along the way, without raising errors for any existing + directories. This function mimics the behavior of the ``mkdir -p`` + command available in Linux/BSD environments, but also works on + Windows. + """ + try: + os.makedirs(path) + except OSError as exc: + if exc.errno == errno.EEXIST and os.path.isdir(path): + return + raise + return + + +class FilePerms: + """The :class:`FilePerms` type is used to represent standard POSIX + filesystem permissions: + + * Read + * Write + * Execute + + Across three classes of user: + + * Owning (u)ser + * Owner's (g)roup + * Any (o)ther user + + This class assists with computing new permissions, as well as + working with numeric octal ``777``-style and ``rwx``-style + permissions. Currently it only considers the bottom 9 permission + bits; it does not support sticky bits or more advanced permission + systems. + + Args: + user (str): A string in the 'rwx' format, omitting characters + for which owning user's permissions are not provided. + group (str): A string in the 'rwx' format, omitting characters + for which owning group permissions are not provided. + other (str): A string in the 'rwx' format, omitting characters + for which owning other/world permissions are not provided. + + There are many ways to use :class:`FilePerms`: + + >>> FilePerms(user='rwx', group='xrw', other='wxr') # note character order + FilePerms(user='rwx', group='rwx', other='rwx') + >>> int(FilePerms('r', 'r', '')) + 288 + >>> oct(288)[-3:] # XXX Py3k + '440' + + See also the :meth:`FilePerms.from_int` and + :meth:`FilePerms.from_path` classmethods for useful alternative + ways to construct :class:`FilePerms` objects. + """ + # TODO: consider more than the lower 9 bits + class _FilePermProperty: + _perm_chars = 'rwx' + _perm_set = frozenset('rwx') + _perm_val = {'r': 4, 'w': 2, 'x': 1} # for sorting + + def __init__(self, attribute, offset): + self.attribute = attribute + self.offset = offset + + def __get__(self, fp_obj, type_=None): + if fp_obj is None: + return self + return getattr(fp_obj, self.attribute) + + def __set__(self, fp_obj, value): + cur = getattr(fp_obj, self.attribute) + if cur == value: + return + try: + invalid_chars = set(str(value)) - self._perm_set + except TypeError: + raise TypeError('expected string, not %r' % value) + if invalid_chars: + raise ValueError('got invalid chars %r in permission' + ' specification %r, expected empty string' + ' or one or more of %r' + % (invalid_chars, value, self._perm_chars)) + + def sort_key(c): return self._perm_val[c] + new_value = ''.join(sorted(set(value), + key=sort_key, reverse=True)) + setattr(fp_obj, self.attribute, new_value) + self._update_integer(fp_obj, new_value) + + def _update_integer(self, fp_obj, value): + mode = 0 + key = 'xwr' + for symbol in value: + bit = 2 ** key.index(symbol) + mode |= (bit << (self.offset * 3)) + fp_obj._integer |= mode + + def __init__(self, user='', group='', other=''): + self._user, self._group, self._other = '', '', '' + self._integer = 0 + self.user = user + self.group = group + self.other = other + + @classmethod + def from_int(cls, i): + """Create a :class:`FilePerms` object from an integer. + + >>> FilePerms.from_int(0o644) # note the leading zero-oh for octal + FilePerms(user='rw', group='r', other='r') + """ + i &= FULL_PERMS + key = ('', 'x', 'w', 'xw', 'r', 'rx', 'rw', 'rwx') + parts = [] + while i: + parts.append(key[i & _SINGLE_FULL_PERM]) + i >>= 3 + parts.reverse() + return cls(*parts) + + @classmethod + def from_path(cls, path): + """Make a new :class:`FilePerms` object based on the permissions + assigned to the file or directory at *path*. + + Args: + path (str): Filesystem path of the target file. + + Here's an example that holds true on most systems: + + >>> import tempfile + >>> 'r' in FilePerms.from_path(tempfile.gettempdir()).user + True + """ + stat_res = os.stat(path) + return cls.from_int(stat.S_IMODE(stat_res.st_mode)) + + def __int__(self): + return self._integer + + # Sphinx tip: attribute docstrings come after the attribute + user = _FilePermProperty('_user', 2) + "Stores the ``rwx``-formatted *user* permission." + group = _FilePermProperty('_group', 1) + "Stores the ``rwx``-formatted *group* permission." + other = _FilePermProperty('_other', 0) + "Stores the ``rwx``-formatted *other* permission." + + def __repr__(self): + cn = self.__class__.__name__ + return ('%s(user=%r, group=%r, other=%r)' + % (cn, self.user, self.group, self.other)) + +#### + + +_TEXT_OPENFLAGS = os.O_RDWR | os.O_CREAT | os.O_EXCL +if hasattr(os, 'O_NOINHERIT'): + _TEXT_OPENFLAGS |= os.O_NOINHERIT +if hasattr(os, 'O_NOFOLLOW'): + _TEXT_OPENFLAGS |= os.O_NOFOLLOW +_BIN_OPENFLAGS = _TEXT_OPENFLAGS +if hasattr(os, 'O_BINARY'): + _BIN_OPENFLAGS |= os.O_BINARY + + +try: + import fcntl as fcntl +except ImportError: + def set_cloexec(fd): + "Dummy set_cloexec for platforms without fcntl support" + pass +else: + def set_cloexec(fd): + """Does a best-effort :func:`fcntl.fcntl` call to set a fd to be + automatically closed by any future child processes. + + Implementation from the :mod:`tempfile` module. + """ + try: + flags = fcntl.fcntl(fd, fcntl.F_GETFD, 0) + except OSError: + pass + else: + # flags read successfully, modify + flags |= fcntl.FD_CLOEXEC + fcntl.fcntl(fd, fcntl.F_SETFD, flags) + return + + +def atomic_save(dest_path, **kwargs): + """A convenient interface to the :class:`AtomicSaver` type. Example: + + >>> try: + ... with atomic_save("file.txt", text_mode=True) as fo: + ... _ = fo.write('bye') + ... 1/0 # will error + ... fo.write('bye') + ... except ZeroDivisionError: + ... pass # at least our file.txt didn't get overwritten + + See the :class:`AtomicSaver` documentation for details. + """ + return AtomicSaver(dest_path, **kwargs) + + +def path_to_unicode(path): + if isinstance(path, str): + return path + encoding = sys.getfilesystemencoding() or sys.getdefaultencoding() + return path.decode(encoding) + + +if os.name == 'nt': + import ctypes + from ctypes import c_wchar_p + from ctypes.wintypes import DWORD, LPVOID + + _ReplaceFile = ctypes.windll.kernel32.ReplaceFile + _ReplaceFile.argtypes = [c_wchar_p, c_wchar_p, c_wchar_p, + DWORD, LPVOID, LPVOID] + + def replace(src, dst): + # argument names match stdlib docs, docstring below + try: + # ReplaceFile fails if the dest file does not exist, so + # first try to rename it into position + os.rename(src, dst) + return + except OSError as we: + if we.errno == errno.EEXIST: + pass # continue with the ReplaceFile logic below + else: + raise + + src = path_to_unicode(src) + dst = path_to_unicode(dst) + res = _ReplaceFile(c_wchar_p(dst), c_wchar_p(src), + None, 0, None, None) + if not res: + raise OSError(f'failed to replace {dst!r} with {src!r}') + return + + def atomic_rename(src, dst, overwrite=False): + "Rename *src* to *dst*, replacing *dst* if *overwrite is True" + if overwrite: + replace(src, dst) + else: + os.rename(src, dst) + return +else: + # wrapper func for cross compat + docs + def replace(src, dst): + # os.replace does the same thing on unix + return os.rename(src, dst) + + def atomic_rename(src, dst, overwrite=False): + "Rename *src* to *dst*, replacing *dst* if *overwrite is True" + if overwrite: + os.rename(src, dst) + else: + os.link(src, dst) + os.unlink(src) + return + + +_atomic_rename = atomic_rename # backwards compat + +replace.__doc__ = """Similar to :func:`os.replace` in Python 3.3+, +this function will atomically create or replace the file at path +*dst* with the file at path *src*. + +On Windows, this function uses the ReplaceFile API for maximum +possible atomicity on a range of filesystems. +""" + + +class AtomicSaver: + """``AtomicSaver`` is a configurable `context manager`_ that provides + a writable :class:`file` which will be moved into place as long as + no exceptions are raised within the context manager's block. These + "part files" are created in the same directory as the destination + path to ensure atomic move operations (i.e., no cross-filesystem + moves occur). + + Args: + dest_path (str): The path where the completed file will be + written. + overwrite (bool): Whether to overwrite the destination file if + it exists at completion time. Defaults to ``True``. + file_perms (int): Integer representation of file permissions + for the newly-created file. Defaults are, when the + destination path already exists, to copy the permissions + from the previous file, or if the file did not exist, to + respect the user's configured `umask`_, usually resulting + in octal 0644 or 0664. + text_mode (bool): Whether to open the destination file in text + mode (i.e., ``'w'`` not ``'wb'``). Defaults to ``False`` (``wb``). + part_file (str): Name of the temporary *part_file*. Defaults + to *dest_path* + ``.part``. Note that this argument is + just the filename, and not the full path of the part + file. To guarantee atomic saves, part files are always + created in the same directory as the destination path. + overwrite_part (bool): Whether to overwrite the *part_file*, + should it exist at setup time. Defaults to ``False``, + which results in an :exc:`OSError` being raised on + pre-existing part files. Be careful of setting this to + ``True`` in situations when multiple threads or processes + could be writing to the same part file. + rm_part_on_exc (bool): Remove *part_file* on exception cases. + Defaults to ``True``, but ``False`` can be useful for + recovery in some cases. Note that resumption is not + automatic and by default an :exc:`OSError` is raised if + the *part_file* exists. + + Practically, the AtomicSaver serves a few purposes: + + * Avoiding overwriting an existing, valid file with a partially + written one. + * Providing a reasonable guarantee that a part file only has one + writer at a time. + * Optional recovery of partial data in failure cases. + + .. _context manager: https://docs.python.org/2/reference/compound_stmts.html#with + .. _umask: https://en.wikipedia.org/wiki/Umask + + """ + _default_file_perms = RW_PERMS + + # TODO: option to abort if target file modify date has changed since start? + def __init__(self, dest_path, **kwargs): + self.dest_path = dest_path + self.overwrite = kwargs.pop('overwrite', True) + self.file_perms = kwargs.pop('file_perms', None) + self.overwrite_part = kwargs.pop('overwrite_part', False) + self.part_filename = kwargs.pop('part_file', None) + self.rm_part_on_exc = kwargs.pop('rm_part_on_exc', True) + self.text_mode = kwargs.pop('text_mode', False) + self.buffering = kwargs.pop('buffering', -1) + if kwargs: + raise TypeError(f'unexpected kwargs: {kwargs.keys()!r}') + + self.dest_path = os.path.abspath(self.dest_path) + self.dest_dir = os.path.dirname(self.dest_path) + if not self.part_filename: + self.part_path = dest_path + '.part' + else: + self.part_path = os.path.join(self.dest_dir, self.part_filename) + self.mode = 'w+' if self.text_mode else 'w+b' + self.open_flags = _TEXT_OPENFLAGS if self.text_mode else _BIN_OPENFLAGS + + self.part_file = None + + def _open_part_file(self): + do_chmod = True + file_perms = self.file_perms + if file_perms is None: + try: + # try to copy from file being replaced + stat_res = os.stat(self.dest_path) + file_perms = stat.S_IMODE(stat_res.st_mode) + except OSError: + # default if no destination file exists + file_perms = self._default_file_perms + do_chmod = False # respect the umask + + fd = os.open(self.part_path, self.open_flags, file_perms) + set_cloexec(fd) + self.part_file = os.fdopen(fd, self.mode, self.buffering) + + # if default perms are overridden by the user or previous dest_path + # chmod away the effects of the umask + if do_chmod: + try: + os.chmod(self.part_path, file_perms) + except OSError: + self.part_file.close() + raise + return + + def setup(self): + """Called on context manager entry (the :keyword:`with` statement), + the ``setup()`` method creates the temporary file in the same + directory as the destination file. + + ``setup()`` tests for a writable directory with rename permissions + early, as the part file may not be written to immediately (not + using :func:`os.access` because of the potential issues of + effective vs. real privileges). + + If the caller is not using the :class:`AtomicSaver` as a + context manager, this method should be called explicitly + before writing. + """ + if os.path.lexists(self.dest_path): + if not self.overwrite: + raise OSError(errno.EEXIST, + 'Overwrite disabled and file already exists', + self.dest_path) + if self.overwrite_part and os.path.lexists(self.part_path): + os.unlink(self.part_path) + self._open_part_file() + return + + def __enter__(self): + self.setup() + return self.part_file + + def __exit__(self, exc_type, exc_val, exc_tb): + if self.part_file: + # Ensure data is flushed and synced to disk before closing + self.part_file.flush() + os.fsync(self.part_file.fileno()) + self.part_file.close() + if exc_type: + if self.rm_part_on_exc: + try: + os.unlink(self.part_path) + except Exception: + pass # avoid masking original error + return + try: + atomic_rename(self.part_path, self.dest_path, + overwrite=self.overwrite) + except OSError: + if self.rm_part_on_exc: + try: + os.unlink(self.part_path) + except Exception: + pass # avoid masking original error + raise # could not save destination file + return + + +def iter_find_files(directory, patterns, ignored=None, include_dirs=False, max_depth=None): + """Returns a generator that yields file paths under a *directory*, + matching *patterns* using `glob`_ syntax (e.g., ``*.txt``). Also + supports *ignored* patterns. + + Args: + directory (str): Path that serves as the root of the + search. Yielded paths will include this as a prefix. + patterns (str or list): A single pattern or list of + glob-formatted patterns to find under *directory*. + ignored (str or list): A single pattern or list of + glob-formatted patterns to ignore. + include_dirs (bool): Whether to include directories that match + patterns, as well. Defaults to ``False``. + max_depth (int): traverse up to this level of subdirectory. + I.e., 0 for the specified *directory* only, 1 for *directory* + and one level of subdirectory. + + For example, finding Python files in the current directory: + + >>> _CUR_DIR = os.path.dirname(os.path.abspath(__file__)) + >>> filenames = sorted(iter_find_files(_CUR_DIR, '*.py')) + >>> os.path.basename(filenames[-1]) + 'urlutils.py' + + Or, Python files while ignoring emacs lockfiles: + + >>> filenames = iter_find_files(_CUR_DIR, '*.py', ignored='.#*') + + .. _glob: https://en.wikipedia.org/wiki/Glob_%28programming%29 + + """ + if isinstance(patterns, str): + patterns = [patterns] + pats_re = re.compile('|'.join([fnmatch.translate(p) for p in patterns])) + + if not ignored: + ignored = [] + elif isinstance(ignored, str): + ignored = [ignored] + ign_re = re.compile('|'.join([fnmatch.translate(p) for p in ignored])) + start_depth = len(directory.split(os.path.sep)) + for root, dirs, files in os.walk(directory): + if max_depth is not None and (len(root.split(os.path.sep)) - start_depth) > max_depth: + continue + if include_dirs: + for basename in dirs: + if pats_re.match(basename): + if ignored and ign_re.match(basename): + continue + filename = os.path.join(root, basename) + yield filename + + for basename in files: + if pats_re.match(basename): + if ignored and ign_re.match(basename): + continue + filename = os.path.join(root, basename) + yield filename + return + + +def copy_tree(src, dst, symlinks=False, ignore=None): + """The ``copy_tree`` function is an exact copy of the built-in + :func:`shutil.copytree`, with one key difference: it will not + raise an exception if part of the tree already exists. It achieves + this by using :func:`mkdir_p`. + + As of Python 3.8, you may pass :func:`shutil.copytree` the + `dirs_exist_ok=True` flag to achieve the same effect. + + Args: + src (str): Path of the source directory to copy. + dst (str): Destination path. Existing directories accepted. + symlinks (bool): If ``True``, copy symlinks rather than their + contents. + ignore (callable): A callable that takes a path and directory + listing, returning the files within the listing to be ignored. + + For more details, check out :func:`shutil.copytree` and + :func:`shutil.copy2`. + + """ + names = os.listdir(src) + if ignore is not None: + ignored_names = ignore(src, names) + else: + ignored_names = set() + + mkdir_p(dst) + errors = [] + for name in names: + if name in ignored_names: + continue + srcname = os.path.join(src, name) + dstname = os.path.join(dst, name) + try: + if symlinks and os.path.islink(srcname): + linkto = os.readlink(srcname) + os.symlink(linkto, dstname) + elif os.path.isdir(srcname): + copytree(srcname, dstname, symlinks, ignore) + else: + # Will raise a SpecialFileError for unsupported file types + copy2(srcname, dstname) + # catch the Error from the recursive copytree so that we can + # continue with other files + except Error as e: + errors.extend(e.args[0]) + except OSError as why: + errors.append((srcname, dstname, str(why))) + try: + copystat(src, dst) + except OSError as why: + errors.append((src, dst, str(why))) + if errors: + raise Error(errors) + + +copytree = copy_tree # alias for drop-in replacement of shutil + + +# like open(os.devnull) but with even fewer side effects +class DummyFile: + # TODO: raise ValueErrors on closed for all methods? + # TODO: enforce read/write + def __init__(self, path, mode='r', buffering=None): + self.name = path + self.mode = mode + self.closed = False + self.errors = None + self.isatty = False + self.encoding = None + self.newlines = None + self.softspace = 0 + + def close(self): + self.closed = True + + def fileno(self): + return -1 + + def flush(self): + if self.closed: + raise ValueError('I/O operation on a closed file') + return + + def next(self): + raise StopIteration() + + def read(self, size=0): + if self.closed: + raise ValueError('I/O operation on a closed file') + return '' + + def readline(self, size=0): + if self.closed: + raise ValueError('I/O operation on a closed file') + return '' + + def readlines(self, size=0): + if self.closed: + raise ValueError('I/O operation on a closed file') + return [] + + def seek(self): + if self.closed: + raise ValueError('I/O operation on a closed file') + return + + def tell(self): + if self.closed: + raise ValueError('I/O operation on a closed file') + return 0 + + def truncate(self): + if self.closed: + raise ValueError('I/O operation on a closed file') + return + + def write(self, string): + if self.closed: + raise ValueError('I/O operation on a closed file') + return + + def writelines(self, list_of_strings): + if self.closed: + raise ValueError('I/O operation on a closed file') + return + + def __next__(self): + raise StopIteration() + + def __enter__(self): + if self.closed: + raise ValueError('I/O operation on a closed file') + return + + def __exit__(self, exc_type, exc_val, exc_tb): + return + + +def rotate_file(filename, *, keep: int = 5): + """ + If *filename.ext* exists, it will be moved to *filename.1.ext*, + with all conflicting filenames being moved up by one, dropping any files beyond *keep*. + + After rotation, *filename* will be available for creation as a new file. + + Fails if *filename* is not a file or if *keep* is not > 0. + """ + if keep < 1: + raise ValueError(f'expected "keep" to be >=1, not {keep}') + if not os.path.exists(filename): + return + if not os.path.isfile(filename): + raise ValueError(f'expected {filename} to be a file') + + fn_root, fn_ext = os.path.splitext(filename) + kept_names = [] + for i in range(1, keep + 1): + if fn_ext: + kept_names.append(f'{fn_root}.{i}{fn_ext}') + else: + kept_names.append(f'{fn_root}.{i}') + + fns = [filename] + kept_names + for orig_name, kept_name in reversed(list(zip(fns, fns[1:]))): + if not os.path.exists(orig_name): + continue + os.rename(orig_name, kept_name) + + if os.path.exists(kept_names[-1]): + os.remove(kept_names[-1]) + + return diff --git a/data/miniconda3/lib/python3.13/site-packages/boltons/formatutils.py b/data/miniconda3/lib/python3.13/site-packages/boltons/formatutils.py new file mode 100644 index 0000000000000000000000000000000000000000..303403493c2421f5950285b012f777e3742ec463 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/boltons/formatutils.py @@ -0,0 +1,356 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# * The names of the contributors may not be used to endorse or +# promote products derived from this software without specific +# prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""`PEP 3101`_ introduced the :meth:`str.format` method, and what +would later be called "new-style" string formatting. For the sake of +explicit correctness, it is probably best to refer to Python's dual +string formatting capabilities as *bracket-style* and +*percent-style*. There is overlap, but one does not replace the +other. + + * Bracket-style is more pluggable, slower, and uses a method. + * Percent-style is simpler, faster, and uses an operator. + +Bracket-style formatting brought with it a much more powerful toolbox, +but it was far from a full one. :meth:`str.format` uses `more powerful +syntax`_, but `the tools and idioms`_ for working with +that syntax are not well-developed nor well-advertised. + +``formatutils`` adds several functions for working with bracket-style +format strings: + + * :class:`DeferredValue`: Defer fetching or calculating a value + until format time. + * :func:`get_format_args`: Parse the positional and keyword + arguments out of a format string. + * :func:`tokenize_format_str`: Tokenize a format string into + literals and :class:`BaseFormatField` objects. + * :func:`construct_format_field_str`: Assists in programmatic + construction of format strings. + * :func:`infer_positional_format_args`: Converts anonymous + references in 2.7+ format strings to explicit positional arguments + suitable for usage with Python 2.6. + +.. _more powerful syntax: https://docs.python.org/2/library/string.html#format-string-syntax +.. _the tools and idioms: https://docs.python.org/2/library/string.html#string-formatting +.. _PEP 3101: https://www.python.org/dev/peps/pep-3101/ +""" +# TODO: also include percent-formatting utils? +# TODO: include lithoxyl.formatters.Formatter (or some adaptation)? + + +import re +from string import Formatter + +__all__ = ['DeferredValue', 'get_format_args', 'tokenize_format_str', + 'construct_format_field_str', 'infer_positional_format_args', + 'BaseFormatField'] + + +_pos_farg_re = re.compile('({{)|' # escaped open-brace + '(}})|' # escaped close-brace + r'({[:!.\[}])') # anon positional format arg + + +def construct_format_field_str(fname, fspec, conv): + """ + Constructs a format field string from the field name, spec, and + conversion character (``fname``, ``fspec``, ``conv``). See Python + String Formatting for more info. + """ + if fname is None: + return '' + ret = '{' + fname + if conv: + ret += '!' + conv + if fspec: + ret += ':' + fspec + ret += '}' + return ret + + +def split_format_str(fstr): + """Does very basic splitting of a format string, returns a list of + strings. For full tokenization, see :func:`tokenize_format_str`. + + """ + ret = [] + + for lit, fname, fspec, conv in Formatter().parse(fstr): + if fname is None: + ret.append((lit, None)) + continue + field_str = construct_format_field_str(fname, fspec, conv) + ret.append((lit, field_str)) + return ret + + +def infer_positional_format_args(fstr): + """Takes format strings with anonymous positional arguments, (e.g., + "{}" and {:d}), and converts them into numbered ones for explicitness and + compatibility with 2.6. + + Returns a string with the inferred positional arguments. + """ + # TODO: memoize + ret, max_anon = '', 0 + # look for {: or {! or {. or {[ or {} + start, end, prev_end = 0, 0, 0 + for match in _pos_farg_re.finditer(fstr): + start, end, group = match.start(), match.end(), match.group() + if prev_end < start: + ret += fstr[prev_end:start] + prev_end = end + if group == '{{' or group == '}}': + ret += group + continue + ret += f'{{{max_anon}{group[1:]}' + max_anon += 1 + ret += fstr[prev_end:] + return ret + + +# This approach is hardly exhaustive but it works for most builtins +_INTCHARS = 'bcdoxXn' +_FLOATCHARS = 'eEfFgGn%' +_TYPE_MAP = dict([(x, int) for x in _INTCHARS] + + [(x, float) for x in _FLOATCHARS]) +_TYPE_MAP['s'] = str + + +def get_format_args(fstr): + """ + Turn a format string into two lists of arguments referenced by the + format string. One is positional arguments, and the other is named + arguments. Each element of the list includes the name and the + nominal type of the field. + + # >>> get_format_args("{noun} is {1:d} years old{punct}") + # ([(1, )], [('noun', ), ('punct', )]) + + # XXX: Py3k + >>> get_format_args("{noun} is {1:d} years old{punct}") == \ + ([(1, int)], [('noun', str), ('punct', str)]) + True + """ + # TODO: memoize + formatter = Formatter() + fargs, fkwargs, _dedup = [], [], set() + + def _add_arg(argname, type_char='s'): + if argname not in _dedup: + _dedup.add(argname) + argtype = _TYPE_MAP.get(type_char, str) # TODO: unicode + try: + fargs.append((int(argname), argtype)) + except ValueError: + fkwargs.append((argname, argtype)) + + for lit, fname, fspec, conv in formatter.parse(fstr): + if fname is not None: + type_char = fspec[-1:] + fname_list = re.split('[.[]', fname) + if len(fname_list) > 1: + raise ValueError('encountered compound format arg: %r' % fname) + try: + base_fname = fname_list[0] + assert base_fname + except (IndexError, AssertionError): + raise ValueError('encountered anonymous positional argument') + _add_arg(fname, type_char) + for sublit, subfname, _, _ in formatter.parse(fspec): + # TODO: positional and anon args not allowed here. + if subfname is not None: + _add_arg(subfname) + return fargs, fkwargs + + +def tokenize_format_str(fstr, resolve_pos=True): + """Takes a format string, turns it into a list of alternating string + literals and :class:`BaseFormatField` tokens. By default, also + infers anonymous positional references into explicit, numbered + positional references. To disable this behavior set *resolve_pos* + to ``False``. + """ + ret = [] + if resolve_pos: + fstr = infer_positional_format_args(fstr) + formatter = Formatter() + for lit, fname, fspec, conv in formatter.parse(fstr): + if lit: + ret.append(lit) + if fname is None: + continue + ret.append(BaseFormatField(fname, fspec, conv)) + return ret + + +class BaseFormatField: + """A class representing a reference to an argument inside of a + bracket-style format string. For instance, in ``"{greeting}, + world!"``, there is a field named "greeting". + + These fields can have many options applied to them. See the + Python docs on `Format String Syntax`_ for the full details. + + .. _Format String Syntax: https://docs.python.org/2/library/string.html#string-formatting + """ + def __init__(self, fname, fspec='', conv=None): + self.set_fname(fname) + self.set_fspec(fspec) + self.set_conv(conv) + + def set_fname(self, fname): + "Set the field name." + + path_list = re.split('[.[]', fname) # TODO + + self.base_name = path_list[0] + self.fname = fname + self.subpath = path_list[1:] + self.is_positional = not self.base_name or self.base_name.isdigit() + + def set_fspec(self, fspec): + "Set the field spec." + fspec = fspec or '' + subfields = [] + for sublit, subfname, _, _ in Formatter().parse(fspec): + if subfname is not None: + subfields.append(subfname) + self.subfields = subfields + self.fspec = fspec + self.type_char = fspec[-1:] + self.type_func = _TYPE_MAP.get(self.type_char, str) + + def set_conv(self, conv): + """There are only two built-in converters: ``s`` and ``r``. They are + somewhat rare and appearlike ``"{ref!r}"``.""" + # TODO + self.conv = conv + self.conv_func = None # TODO + + @property + def fstr(self): + "The current state of the field in string format." + return construct_format_field_str(self.fname, self.fspec, self.conv) + + def __repr__(self): + cn = self.__class__.__name__ + args = [self.fname] + if self.conv is not None: + args.extend([self.fspec, self.conv]) + elif self.fspec != '': + args.append(self.fspec) + args_repr = ', '.join([repr(a) for a in args]) + return f'{cn}({args_repr})' + + def __str__(self): + return self.fstr + + +_UNSET = object() + + +class DeferredValue: + """:class:`DeferredValue` is a wrapper type, used to defer computing + values which would otherwise be expensive to stringify and + format. This is most valuable in areas like logging, where one + would not want to waste time formatting a value for a log message + which will subsequently be filtered because the message's log + level was DEBUG and the logger was set to only emit CRITICAL + messages. + + The :class:``DeferredValue`` is initialized with a callable that + takes no arguments and returns the value, which can be of any + type. By default DeferredValue only calls that callable once, and + future references will get a cached value. This behavior can be + disabled by setting *cache_value* to ``False``. + + Args: + + func (function): A callable that takes no arguments and + computes the value being represented. + cache_value (bool): Whether subsequent usages will call *func* + again. Defaults to ``True``. + + >>> import sys + >>> dv = DeferredValue(lambda: len(sys._current_frames())) + >>> output = "works great in all {0} threads!".format(dv) + + PROTIP: To keep lines shorter, use: ``from formatutils import + DeferredValue as DV`` + """ + def __init__(self, func, cache_value=True): + self.func = func + self.cache_value = cache_value + self._value = _UNSET + + def get_value(self): + """Computes, optionally caches, and returns the value of the + *func*. If ``get_value()`` has been called before, a cached + value may be returned depending on the *cache_value* option + passed to the constructor. + """ + if self._value is not _UNSET and self.cache_value: + value = self._value + else: + value = self.func() + if self.cache_value: + self._value = value + return value + + def __int__(self): + return int(self.get_value()) + + def __float__(self): + return float(self.get_value()) + + def __str__(self): + return str(self.get_value()) + + def __unicode__(self): + return str(self.get_value()) + + def __repr__(self): + return repr(self.get_value()) + + def __format__(self, fmt): + value = self.get_value() + + pt = fmt[-1:] # presentation type + type_conv = _TYPE_MAP.get(pt, str) + + try: + return value.__format__(fmt) + except (ValueError, TypeError): + # TODO: this may be overkill + return type_conv(value).__format__(fmt) + +# end formatutils.py diff --git a/data/miniconda3/lib/python3.13/site-packages/boltons/funcutils.py b/data/miniconda3/lib/python3.13/site-packages/boltons/funcutils.py new file mode 100644 index 0000000000000000000000000000000000000000..0bdc28e9bf54bef76741eae72ae838517e0a87d9 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/boltons/funcutils.py @@ -0,0 +1,1007 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# * The names of the contributors may not be used to endorse or +# promote products derived from this software without specific +# prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Python's built-in :mod:`functools` module builds several useful +utilities on top of Python's first-class function +support. ``funcutils`` generally stays in the same vein, adding to and +correcting Python's standard metaprogramming facilities. +""" + +import sys +import re +import inspect +import functools +import itertools +from inspect import formatannotation +from types import FunctionType, MethodType + +# For legacy compatibility. +# boltons used to offer an implementation of total_ordering for Python <2.7 +from functools import total_ordering as total_ordering + +try: + from .typeutils import make_sentinel + NO_DEFAULT = make_sentinel(var_name='NO_DEFAULT') +except ImportError: + NO_DEFAULT = object() + + +def inspect_formatargspec( + args, varargs=None, varkw=None, defaults=None, + kwonlyargs=(), kwonlydefaults={}, annotations={}, + formatarg=str, + formatvarargs=lambda name: '*' + name, + formatvarkw=lambda name: '**' + name, + formatvalue=lambda value: '=' + repr(value), + formatreturns=lambda text: ' -> ' + text, + formatannotation=formatannotation): + """Copy formatargspec from python 3.7 standard library. + Python 3 has deprecated formatargspec and requested that Signature + be used instead, however this requires a full reimplementation + of formatargspec() in terms of creating Parameter objects and such. + Instead of introducing all the object-creation overhead and having + to reinvent from scratch, just copy their compatibility routine. + """ + + def formatargandannotation(arg): + result = formatarg(arg) + if arg in annotations: + result += ': ' + formatannotation(annotations[arg]) + return result + specs = [] + if defaults: + firstdefault = len(args) - len(defaults) + for i, arg in enumerate(args): + spec = formatargandannotation(arg) + if defaults and i >= firstdefault: + spec = spec + formatvalue(defaults[i - firstdefault]) + specs.append(spec) + if varargs is not None: + specs.append(formatvarargs(formatargandannotation(varargs))) + else: + if kwonlyargs: + specs.append('*') + if kwonlyargs: + for kwonlyarg in kwonlyargs: + spec = formatargandannotation(kwonlyarg) + if kwonlydefaults and kwonlyarg in kwonlydefaults: + spec += formatvalue(kwonlydefaults[kwonlyarg]) + specs.append(spec) + if varkw is not None: + specs.append(formatvarkw(formatargandannotation(varkw))) + result = '(' + ', '.join(specs) + ')' + if 'return' in annotations: + result += formatreturns(formatannotation(annotations['return'])) + return result + + +def get_module_callables(mod, ignore=None): + """Returns two maps of (*types*, *funcs*) from *mod*, optionally + ignoring based on the :class:`bool` return value of the *ignore* + callable. *mod* can be a string name of a module in + :data:`sys.modules` or the module instance itself. + """ + if isinstance(mod, str): + mod = sys.modules[mod] + types, funcs = {}, {} + for attr_name in dir(mod): + if ignore and ignore(attr_name): + continue + try: + attr = getattr(mod, attr_name) + except Exception: + continue + try: + attr_mod_name = attr.__module__ + except AttributeError: + continue + if attr_mod_name != mod.__name__: + continue + if isinstance(attr, type): + types[attr_name] = attr + elif callable(attr): + funcs[attr_name] = attr + return types, funcs + + +def mro_items(type_obj): + """Takes a type and returns an iterator over all class variables + throughout the type hierarchy (respecting the MRO). + + >>> sorted(set([k for k, v in mro_items(int) if not k.startswith('__') and 'bytes' not in k and not callable(v)])) + ['denominator', 'imag', 'numerator', 'real'] + """ + # TODO: handle slots? + return itertools.chain.from_iterable(ct.__dict__.items() + for ct in type_obj.__mro__) + + +def dir_dict(obj, raise_exc=False): + """Return a dictionary of attribute names to values for a given + object. Unlike ``obj.__dict__``, this function returns all + attributes on the object, including ones on parent classes. + """ + # TODO: separate function for handling descriptors on types? + ret = {} + for k in dir(obj): + try: + ret[k] = getattr(obj, k) + except Exception: + if raise_exc: + raise + return ret + + +def copy_function(orig, copy_dict=True): + """Returns a shallow copy of the function, including code object, + globals, closure, etc. + + >>> func = lambda: func + >>> func() is func + True + >>> func_copy = copy_function(func) + >>> func_copy() is func + True + >>> func_copy is not func + True + + Args: + orig (function): The function to be copied. Must be a + function, not just any method or callable. + copy_dict (bool): Also copy any attributes set on the function + instance. Defaults to ``True``. + """ + ret = FunctionType(orig.__code__, + orig.__globals__, + name=orig.__name__, + argdefs=getattr(orig, "__defaults__", None), + closure=getattr(orig, "__closure__", None)) + if hasattr(orig, "__kwdefaults__"): + ret.__kwdefaults__ = orig.__kwdefaults__ + if copy_dict: + ret.__dict__.update(orig.__dict__) + return ret + + +def partial_ordering(cls): + """Class decorator, similar to :func:`functools.total_ordering`, + except it is used to define `partial orderings`_ (i.e., it is + possible that *x* is neither greater than, equal to, or less than + *y*). It assumes the presence of the ``__le__()`` and ``__ge__()`` + method, but nothing else. It will not override any existing + additional comparison methods. + + .. _partial orderings: https://en.wikipedia.org/wiki/Partially_ordered_set + + >>> @partial_ordering + ... class MySet(set): + ... def __le__(self, other): + ... return self.issubset(other) + ... def __ge__(self, other): + ... return self.issuperset(other) + ... + >>> a = MySet([1,2,3]) + >>> b = MySet([1,2]) + >>> c = MySet([1,2,4]) + >>> b < a + True + >>> b > a + False + >>> b < c + True + >>> a < c + False + >>> c > a + False + """ + def __lt__(self, other): return self <= other and not self >= other + def __gt__(self, other): return self >= other and not self <= other + def __eq__(self, other): return self >= other and self <= other + + if not hasattr(cls, '__lt__'): cls.__lt__ = __lt__ + if not hasattr(cls, '__gt__'): cls.__gt__ = __gt__ + if not hasattr(cls, '__eq__'): cls.__eq__ = __eq__ + + return cls + + +class InstancePartial(functools.partial): + """:class:`functools.partial` is a huge convenience for anyone + working with Python's great first-class functions. It allows + developers to curry arguments and incrementally create simpler + callables for a variety of use cases. + + Unfortunately there's one big gap in its usefulness: + methods. Partials just don't get bound as methods and + automatically handed a reference to ``self``. The + ``InstancePartial`` type remedies this by inheriting from + :class:`functools.partial` and implementing the necessary + descriptor protocol. There are no other differences in + implementation or usage. :class:`CachedInstancePartial`, below, + has the same ability, but is slightly more efficient. + + """ + @property + def _partialmethod(self): + # py3.13 switched from _partialmethod to __partialmethod__, this is kept for backwards compat <=py3.12 + return self.__partialmethod__ + + @property + def __partialmethod__(self): + return functools.partialmethod(self.func, *self.args, **self.keywords) + + def __get__(self, obj, obj_type): + return MethodType(self, obj) + + + +class CachedInstancePartial(functools.partial): + """The ``CachedInstancePartial`` is virtually the same as + :class:`InstancePartial`, adding support for method-usage to + :class:`functools.partial`, except that upon first access, it + caches the bound method on the associated object, speeding it up + for future accesses, and bringing the method call overhead to + about the same as non-``partial`` methods. + + See the :class:`InstancePartial` docstring for more details. + """ + @property + def _partialmethod(self): + # py3.13 switched from _partialmethod to __partialmethod__, this is kept for backwards compat <=py3.12 + return self.__partialmethod__ + + @property + def __partialmethod__(self): + return functools.partialmethod(self.func, *self.args, **self.keywords) + + def __set_name__(self, obj_type, name): + self.__name__ = name + + def __get__(self, obj, obj_type): + # These assignments could've been in __init__, but there was + # no simple way to do it without breaking one of PyPy or Py3. + self.__name__ = getattr(self, "__name__", None) + self.__doc__ = self.func.__doc__ + self.__module__ = self.func.__module__ + + name = self.__name__ + + if obj is None: + return MethodType(self, obj) + try: + # since this is a data descriptor, this block + # is probably only hit once (per object) + return obj.__dict__[name] + except KeyError: + obj.__dict__[name] = ret = MethodType(self, obj) + return ret + + +partial = CachedInstancePartial + + +def format_invocation(name='', args=(), kwargs=None, **kw): + """Given a name, positional arguments, and keyword arguments, format + a basic Python-style function call. + + >>> print(format_invocation('func', args=(1, 2), kwargs={'c': 3})) + func(1, 2, c=3) + >>> print(format_invocation('a_func', args=(1,))) + a_func(1) + >>> print(format_invocation('kw_func', kwargs=[('a', 1), ('b', 2)])) + kw_func(a=1, b=2) + + """ + _repr = kw.pop('repr', repr) + if kw: + raise TypeError('unexpected keyword args: %r' % ', '.join(kw.keys())) + kwargs = kwargs or {} + a_text = ', '.join([_repr(a) for a in args]) + if isinstance(kwargs, dict): + kwarg_items = [(k, kwargs[k]) for k in sorted(kwargs)] + else: + kwarg_items = kwargs + kw_text = ', '.join([f'{k}={_repr(v)}' for k, v in kwarg_items]) + + all_args_text = a_text + if all_args_text and kw_text: + all_args_text += ', ' + all_args_text += kw_text + + return f'{name}({all_args_text})' + + +def format_exp_repr(obj, pos_names, req_names=None, opt_names=None, opt_key=None): + """Render an expression-style repr of an object, based on attribute + names, which are assumed to line up with arguments to an initializer. + + >>> class Flag(object): + ... def __init__(self, length, width, depth=None): + ... self.length = length + ... self.width = width + ... self.depth = depth + ... + + That's our Flag object, here are some example reprs for it: + + >>> flag = Flag(5, 10) + >>> print(format_exp_repr(flag, ['length', 'width'], [], ['depth'])) + Flag(5, 10) + >>> flag2 = Flag(5, 15, 2) + >>> print(format_exp_repr(flag2, ['length'], ['width', 'depth'])) + Flag(5, width=15, depth=2) + + By picking the pos_names, req_names, opt_names, and opt_key, you + can fine-tune how you want the repr to look. + + Args: + obj (object): The object whose type name will be used and + attributes will be checked + pos_names (list): Required list of attribute names which will be + rendered as positional arguments in the output repr. + req_names (list): List of attribute names which will always + appear in the keyword arguments in the output repr. Defaults to None. + opt_names (list): List of attribute names which may appear in + the keyword arguments in the output repr, provided they pass + the *opt_key* check. Defaults to None. + opt_key (callable): A function or callable which checks whether + an opt_name should be in the repr. Defaults to a + ``None``-check. + + """ + cn = type(obj).__name__ + req_names = req_names or [] + opt_names = opt_names or [] + uniq_names, all_names = set(), [] + for name in req_names + opt_names: + if name in uniq_names: + continue + uniq_names.add(name) + all_names.append(name) + + if opt_key is None: + opt_key = lambda v: v is None + assert callable(opt_key) + + args = [getattr(obj, name, None) for name in pos_names] + + kw_items = [(name, getattr(obj, name, None)) for name in all_names] + kw_items = [(name, val) for name, val in kw_items + if not (name in opt_names and opt_key(val))] + + return format_invocation(cn, args, kw_items) + + +def format_nonexp_repr(obj, req_names=None, opt_names=None, opt_key=None): + """Format a non-expression-style repr + + Some object reprs look like object instantiation, e.g., App(r=[], mw=[]). + + This makes sense for smaller, lower-level objects whose state + roundtrips. But a lot of objects contain values that don't + roundtrip, like types and functions. + + For those objects, there is the non-expression style repr, which + mimic's Python's default style to make a repr like so: + + >>> class Flag(object): + ... def __init__(self, length, width, depth=None): + ... self.length = length + ... self.width = width + ... self.depth = depth + ... + >>> flag = Flag(5, 10) + >>> print(format_nonexp_repr(flag, ['length', 'width'], ['depth'])) + + + If no attributes are specified or set, utilizes the id, not unlike Python's + built-in behavior. + + >>> print(format_nonexp_repr(flag)) + + """ + cn = obj.__class__.__name__ + req_names = req_names or [] + opt_names = opt_names or [] + uniq_names, all_names = set(), [] + for name in req_names + opt_names: + if name in uniq_names: + continue + uniq_names.add(name) + all_names.append(name) + + if opt_key is None: + opt_key = lambda v: v is None + assert callable(opt_key) + + items = [(name, getattr(obj, name, None)) for name in all_names] + labels = [f'{name}={val!r}' for name, val in items + if not (name in opt_names and opt_key(val))] + if not labels: + labels = ['id=%s' % id(obj)] + ret = '<{} {}>'.format(cn, ' '.join(labels)) + return ret + + + +# # # +# # # Function builder +# # # + + +def wraps(func, injected=None, expected=None, **kw): + """Decorator factory to apply update_wrapper() to a wrapper function. + + Modeled after built-in :func:`functools.wraps`. Returns a decorator + that invokes update_wrapper() with the decorated function as the wrapper + argument and the arguments to wraps() as the remaining arguments. + Default arguments are as for update_wrapper(). This is a convenience + function to simplify applying partial() to update_wrapper(). + + Same example as in update_wrapper's doc but with wraps: + + >>> from boltons.funcutils import wraps + >>> + >>> def print_return(func): + ... @wraps(func) + ... def wrapper(*args, **kwargs): + ... ret = func(*args, **kwargs) + ... print(ret) + ... return ret + ... return wrapper + ... + >>> @print_return + ... def example(): + ... '''docstring''' + ... return 'example return value' + >>> + >>> val = example() + example return value + >>> example.__name__ + 'example' + >>> example.__doc__ + 'docstring' + """ + return partial(update_wrapper, func=func, build_from=None, + injected=injected, expected=expected, **kw) + + +def update_wrapper(wrapper, func, injected=None, expected=None, build_from=None, **kw): + """Modeled after the built-in :func:`functools.update_wrapper`, + this function is used to make your wrapper function reflect the + wrapped function's: + + * Name + * Documentation + * Module + * Signature + + The built-in :func:`functools.update_wrapper` copies the first three, but + does not copy the signature. This version of ``update_wrapper`` can copy + the inner function's signature exactly, allowing seamless usage + and :mod:`introspection `. Usage is identical to the + built-in version:: + + >>> from boltons.funcutils import update_wrapper + >>> + >>> def print_return(func): + ... def wrapper(*args, **kwargs): + ... ret = func(*args, **kwargs) + ... print(ret) + ... return ret + ... return update_wrapper(wrapper, func) + ... + >>> @print_return + ... def example(): + ... '''docstring''' + ... return 'example return value' + >>> + >>> val = example() + example return value + >>> example.__name__ + 'example' + >>> example.__doc__ + 'docstring' + + In addition, the boltons version of update_wrapper supports + modifying the outer signature. By passing a list of + *injected* argument names, those arguments will be removed from + the outer wrapper's signature, allowing your decorator to provide + arguments that aren't passed in. + + Args: + + wrapper (function) : The callable to which the attributes of + *func* are to be copied. + func (function): The callable whose attributes are to be copied. + injected (list): An optional list of argument names which + should not appear in the new wrapper's signature. + expected (list): An optional list of argument names (or (name, + default) pairs) representing new arguments introduced by + the wrapper (the opposite of *injected*). See + :meth:`FunctionBuilder.add_arg()` for more details. + build_from (function): The callable from which the new wrapper + is built. Defaults to *func*, unless *wrapper* is partial object + built from *func*, in which case it defaults to *wrapper*. + Useful in some specific cases where *wrapper* and *func* have the + same arguments but differ on which are keyword-only and positional-only. + update_dict (bool): Whether to copy other, non-standard + attributes of *func* over to the wrapper. Defaults to True. + inject_to_varkw (bool): Ignore missing arguments when a + ``**kwargs``-type catch-all is present. Defaults to True. + hide_wrapped (bool): Remove reference to the wrapped function(s) + in the updated function. + + In opposition to the built-in :func:`functools.update_wrapper` bolton's + version returns a copy of the function and does not modify anything in place. + For more in-depth wrapping of functions, see the + :class:`FunctionBuilder` type, on which update_wrapper was built. + """ + if injected is None: + injected = [] + elif isinstance(injected, str): + injected = [injected] + else: + injected = list(injected) + + expected_items = _parse_wraps_expected(expected) + + if isinstance(func, (classmethod, staticmethod)): + raise TypeError('wraps does not support wrapping classmethods and' + ' staticmethods, change the order of wrapping to' + ' wrap the underlying function: %r' + % (getattr(func, '__func__', None),)) + + update_dict = kw.pop('update_dict', True) + inject_to_varkw = kw.pop('inject_to_varkw', True) + hide_wrapped = kw.pop('hide_wrapped', False) + if kw: + raise TypeError('unexpected kwargs: %r' % kw.keys()) + + if isinstance(wrapper, functools.partial) and func is wrapper.func: + build_from = build_from or wrapper + + fb = FunctionBuilder.from_func(build_from or func) + + for arg in injected: + try: + fb.remove_arg(arg) + except MissingArgument: + if inject_to_varkw and fb.varkw is not None: + continue # keyword arg will be caught by the varkw + raise + + for arg, default in expected_items: + fb.add_arg(arg, default) # may raise ExistingArgument + + if fb.is_async: + fb.body = 'return await _call(%s)' % fb.get_invocation_str() + else: + fb.body = 'return _call(%s)' % fb.get_invocation_str() + + execdict = dict(_call=wrapper, _func=func) + fully_wrapped = fb.get_func(execdict, with_dict=update_dict) + + if hide_wrapped and hasattr(fully_wrapped, '__wrapped__'): + del fully_wrapped.__dict__['__wrapped__'] + elif not hide_wrapped: + fully_wrapped.__wrapped__ = func # ref to the original function (#115) + + return fully_wrapped + + +def _parse_wraps_expected(expected): + # expected takes a pretty powerful argument, it's processed + # here. admittedly this would be less trouble if I relied on + # OrderedDict (there's an impl of that in the commit history if + # you look + if expected is None: + expected = [] + elif isinstance(expected, str): + expected = [(expected, NO_DEFAULT)] + + expected_items = [] + try: + expected_iter = iter(expected) + except TypeError as e: + raise ValueError('"expected" takes string name, sequence of string names,' + ' iterable of (name, default) pairs, or a mapping of ' + ' {name: default}, not %r (got: %r)' % (expected, e)) + for argname in expected_iter: + if isinstance(argname, str): + # dict keys and bare strings + try: + default = expected[argname] + except TypeError: + default = NO_DEFAULT + else: + # pairs + try: + argname, default = argname + except (TypeError, ValueError): + raise ValueError('"expected" takes string name, sequence of string names,' + ' iterable of (name, default) pairs, or a mapping of ' + ' {name: default}, not %r') + if not isinstance(argname, str): + raise ValueError(f'all "expected" argnames must be strings, not {argname!r}') + + expected_items.append((argname, default)) + + return expected_items + + +class FunctionBuilder: + """The FunctionBuilder type provides an interface for programmatically + creating new functions, either based on existing functions or from + scratch. + + Values are passed in at construction or set as attributes on the + instance. For creating a new function based of an existing one, + see the :meth:`~FunctionBuilder.from_func` classmethod. At any + point, :meth:`~FunctionBuilder.get_func` can be called to get a + newly compiled function, based on the values configured. + + >>> fb = FunctionBuilder('return_five', doc='returns the integer 5', + ... body='return 5') + >>> f = fb.get_func() + >>> f() + 5 + >>> fb.varkw = 'kw' + >>> f_kw = fb.get_func() + >>> f_kw(ignored_arg='ignored_val') + 5 + + Note that function signatures themselves changed quite a bit in + Python 3, so several arguments are only applicable to + FunctionBuilder in Python 3. Except for *name*, all arguments to + the constructor are keyword arguments. + + Args: + name (str): Name of the function. + doc (str): `Docstring`_ for the function, defaults to empty. + module (str): Name of the module from which this function was + imported. Defaults to None. + body (str): String version of the code representing the body + of the function. Defaults to ``'pass'``, which will result + in a function which does nothing and returns ``None``. + args (list): List of argument names, defaults to empty list, + denoting no arguments. + varargs (str): Name of the catch-all variable for positional + arguments. E.g., "args" if the resultant function is to have + ``*args`` in the signature. Defaults to None. + varkw (str): Name of the catch-all variable for keyword + arguments. E.g., "kwargs" if the resultant function is to have + ``**kwargs`` in the signature. Defaults to None. + defaults (tuple): A tuple containing default argument values for + those arguments that have defaults. + kwonlyargs (list): Argument names which are only valid as + keyword arguments. **Python 3 only.** + kwonlydefaults (dict): A mapping, same as normal *defaults*, + but only for the *kwonlyargs*. **Python 3 only.** + annotations (dict): Mapping of type hints and so + forth. **Python 3 only.** + filename (str): The filename that will appear in + tracebacks. Defaults to "boltons.funcutils.FunctionBuilder". + indent (int): Number of spaces with which to indent the + function *body*. Values less than 1 will result in an error. + dict (dict): Any other attributes which should be added to the + functions compiled with this FunctionBuilder. + + All of these arguments are also made available as attributes which + can be mutated as necessary. + + .. _Docstring: https://en.wikipedia.org/wiki/Docstring#Python + + """ + + _argspec_defaults = {'args': list, + 'varargs': lambda: None, + 'varkw': lambda: None, + 'defaults': lambda: None, + 'kwonlyargs': list, + 'kwonlydefaults': dict, + 'annotations': dict} + + @classmethod + def _argspec_to_dict(cls, f): + argspec = inspect.getfullargspec(f) + return {attr: getattr(argspec, attr) + for attr in cls._argspec_defaults} + + _defaults = {'doc': str, + 'dict': dict, + 'is_async': lambda: False, + 'module': lambda: None, + 'body': lambda: 'pass', + 'indent': lambda: 4, + "annotations": dict, + 'filename': lambda: 'boltons.funcutils.FunctionBuilder'} + + _defaults.update(_argspec_defaults) + + _compile_count = itertools.count() + + def __init__(self, name, **kw): + self.name = name + for a, default_factory in self._defaults.items(): + val = kw.pop(a, None) + if val is None: + val = default_factory() + setattr(self, a, val) + + if kw: + raise TypeError('unexpected kwargs: %r' % kw.keys()) + return + + # def get_argspec(self): # TODO + + def get_sig_str(self, with_annotations=True): + """Return function signature as a string. + + with_annotations is ignored on Python 2. On Python 3 signature + will omit annotations if it is set to False. + """ + if with_annotations: + annotations = self.annotations + else: + annotations = {} + + return inspect_formatargspec(self.args, + self.varargs, + self.varkw, + [], + self.kwonlyargs, + {}, + annotations) + + _KWONLY_MARKER = re.compile(r""" + \* # a star + \s* # followed by any amount of whitespace + , # followed by a comma + \s* # followed by any amount of whitespace + """, re.VERBOSE) + + def get_invocation_str(self): + kwonly_pairs = None + formatters = {} + if self.kwonlyargs: + kwonly_pairs = {arg: arg + for arg in self.kwonlyargs} + formatters['formatvalue'] = lambda value: '=' + value + + sig = inspect_formatargspec(self.args, + self.varargs, + self.varkw, + [], + kwonly_pairs, + kwonly_pairs, + {}, + **formatters) + sig = self._KWONLY_MARKER.sub('', sig) + return sig[1:-1] + + @classmethod + def from_func(cls, func): + """Create a new FunctionBuilder instance based on an existing + function. The original function will not be stored or + modified. + """ + # TODO: copy_body? gonna need a good signature regex. + # TODO: might worry about __closure__? + if not callable(func): + raise TypeError(f'expected callable object, not {func!r}') + + if isinstance(func, functools.partial): + kwargs = {'name': func.func.__name__, + 'doc': func.func.__doc__, + 'module': getattr(func.func, '__module__', None), # e.g., method_descriptor + 'annotations': getattr(func.func, "__annotations__", {}), + 'dict': getattr(func.func, '__dict__', {})} + else: + kwargs = {'name': func.__name__, + 'doc': func.__doc__, + 'module': getattr(func, '__module__', None), # e.g., method_descriptor + 'annotations': getattr(func, "__annotations__", {}), + 'dict': getattr(func, '__dict__', {})} + + kwargs.update(cls._argspec_to_dict(func)) + + if inspect.iscoroutinefunction(func): + kwargs['is_async'] = True + + return cls(**kwargs) + + def get_func(self, execdict=None, add_source=True, with_dict=True): + """Compile and return a new function based on the current values of + the FunctionBuilder. + + Args: + execdict (dict): The dictionary representing the scope in + which the compilation should take place. Defaults to an empty + dict. + add_source (bool): Whether to add the source used to a + special ``__source__`` attribute on the resulting + function. Defaults to True. + with_dict (bool): Add any custom attributes, if + applicable. Defaults to True. + + To see an example of usage, see the implementation of + :func:`~boltons.funcutils.wraps`. + """ + execdict = execdict or {} + body = self.body or self._default_body + + tmpl = 'def {name}{sig_str}:' + tmpl += '\n{body}' + + if self.is_async: + tmpl = 'async ' + tmpl + + body = _indent(self.body, ' ' * self.indent) + + name = self.name.replace('<', '_').replace('>', '_') # lambdas + src = tmpl.format(name=name, sig_str=self.get_sig_str(with_annotations=False), + doc=self.doc, body=body) + self._compile(src, execdict) + func = execdict[name] + + func.__name__ = self.name + func.__doc__ = self.doc + func.__defaults__ = self.defaults + func.__kwdefaults__ = self.kwonlydefaults + func.__annotations__ = self.annotations + + if with_dict: + func.__dict__.update(self.dict) + func.__module__ = self.module + # TODO: caller module fallback? + + if add_source: + func.__source__ = src + + return func + + def get_defaults_dict(self): + """Get a dictionary of function arguments with defaults and the + respective values. + """ + ret = dict(reversed(list(zip(reversed(self.args), + reversed(self.defaults or []))))) + kwonlydefaults = getattr(self, 'kwonlydefaults', None) + if kwonlydefaults: + ret.update(kwonlydefaults) + return ret + + def get_arg_names(self, only_required=False): + arg_names = tuple(self.args) + tuple(getattr(self, 'kwonlyargs', ())) + if only_required: + defaults_dict = self.get_defaults_dict() + arg_names = tuple([an for an in arg_names if an not in defaults_dict]) + return arg_names + + def add_arg(self, arg_name, default=NO_DEFAULT, kwonly=False): + """Add an argument with optional *default* (defaults to + ``funcutils.NO_DEFAULT``). Pass *kwonly=True* to add a + keyword-only argument + """ + if arg_name in self.args: + raise ExistingArgument(f'arg {arg_name!r} already in func {self.name} arg list') + if arg_name in self.kwonlyargs: + raise ExistingArgument(f'arg {arg_name!r} already in func {self.name} kwonly arg list') + if not kwonly: + self.args.append(arg_name) + if default is not NO_DEFAULT: + self.defaults = (self.defaults or ()) + (default,) + else: + self.kwonlyargs.append(arg_name) + if default is not NO_DEFAULT: + self.kwonlydefaults[arg_name] = default + + def remove_arg(self, arg_name): + """Remove an argument from this FunctionBuilder's argument list. The + resulting function will have one less argument per call to + this function. + + Args: + arg_name (str): The name of the argument to remove. + + Raises a :exc:`ValueError` if the argument is not present. + + """ + args = self.args + d_dict = self.get_defaults_dict() + try: + args.remove(arg_name) + except ValueError: + try: + self.kwonlyargs.remove(arg_name) + except (AttributeError, ValueError): + # missing from both + exc = MissingArgument('arg %r not found in %s argument list:' + ' %r' % (arg_name, self.name, args)) + exc.arg_name = arg_name + raise exc + else: + self.kwonlydefaults.pop(arg_name, None) + else: + d_dict.pop(arg_name, None) + self.defaults = tuple([d_dict[a] for a in args if a in d_dict]) + return + + def _compile(self, src, execdict): + + filename = ('<%s-%d>' + % (self.filename, next(self._compile_count),)) + try: + code = compile(src, filename, 'single') + exec(code, execdict) + except Exception: + raise + return execdict + + +class MissingArgument(ValueError): + pass + + +class ExistingArgument(ValueError): + pass + + +def _indent(text, margin, newline='\n', key=bool): + "based on boltons.strutils.indent" + indented_lines = [(margin + line if key(line) else line) + for line in text.splitlines()] + return newline.join(indented_lines) + + +def noop(*args, **kwargs): + """ + Simple function that should be used when no effect is desired. + An alternative to checking for an optional function type parameter. + + e.g. + def decorate(func, pre_func=None, post_func=None): + if pre_func: + pre_func() + func() + if post_func: + post_func() + + vs + + def decorate(func, pre_func=noop, post_func=noop): + pre_func() + func() + post_func() + """ + return None + +# end funcutils.py diff --git a/data/miniconda3/lib/python3.13/site-packages/boltons/gcutils.py b/data/miniconda3/lib/python3.13/site-packages/boltons/gcutils.py new file mode 100644 index 0000000000000000000000000000000000000000..1db18b462ae47ec4a53ba990634d539b1cfe1c8e --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/boltons/gcutils.py @@ -0,0 +1,164 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# * The names of the contributors may not be used to endorse or +# promote products derived from this software without specific +# prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""The Python Garbage Collector (`GC`_) doesn't usually get too much +attention, probably because: + + - Python's `reference counting`_ effectively handles the vast majority of + unused objects + - People are slowly learning to avoid implementing `object.__del__()`_ + - The collection itself strikes a good balance between simplicity and + power (`tunable generation sizes`_) + - The collector itself is fast and rarely the cause of long pauses + associated with GC in other runtimes + +Even so, for many applications, the time will come when the developer +will need to track down: + + - Circular references + - Misbehaving objects (locks, ``__del__()``) + - Memory leaks + - Or just ways to shave off a couple percent of execution time + +Thanks to the :mod:`gc` module, the GC is a well-instrumented entry +point for exactly these tasks, and ``gcutils`` aims to facilitate it +further. + +.. _GC: https://docs.python.org/2/glossary.html#term-garbage-collection +.. _reference counting: https://docs.python.org/2/glossary.html#term-reference-count +.. _object.__del__(): https://docs.python.org/2/glossary.html#term-reference-count +.. _tunable generation sizes: https://docs.python.org/2/library/gc.html#gc.set_threshold +""" +# TODO: type survey + + +import gc +import sys + +__all__ = ['get_all', 'GCToggler', 'toggle_gc', 'toggle_gc_postcollect'] + + +def get_all(type_obj, include_subtypes=True): + """Get a list containing all instances of a given type. This will + work for the vast majority of types out there. + + >>> class Ratking(object): pass + >>> wiki, hak, sport = Ratking(), Ratking(), Ratking() + >>> len(get_all(Ratking)) + 3 + + However, there are some exceptions. For example, ``get_all(bool)`` + returns an empty list because ``True`` and ``False`` are + themselves built-in and not tracked. + + >>> get_all(bool) + [] + + Still, it's not hard to see how this functionality can be used to + find all instances of a leaking type and track them down further + using :func:`gc.get_referrers` and :func:`gc.get_referents`. + + ``get_all()`` is optimized such that getting instances of + user-created types is quite fast. Setting *include_subtypes* to + ``False`` will further increase performance in cases where + instances of subtypes aren't required. + + .. note:: + + There are no guarantees about the state of objects returned by + ``get_all()``, especially in concurrent environments. For + instance, it is possible for an object to be in the middle of + executing its ``__init__()`` and be only partially constructed. + """ + # TODO: old-style classes + if not isinstance(type_obj, type): + raise TypeError('expected a type, not %r' % type_obj) + try: + type_is_tracked = gc.is_tracked(type_obj) + except AttributeError: + type_is_tracked = False # Python 2.6 and below don't get the speedup + if type_is_tracked: + to_check = gc.get_referrers(type_obj) + else: + to_check = gc.get_objects() + + if include_subtypes: + ret = [x for x in to_check if isinstance(x, type_obj)] + else: + ret = [x for x in to_check if type(x) is type_obj] + return ret + + +_IS_PYPY = '__pypy__' in sys.builtin_module_names +if _IS_PYPY: + # pypy's gc is just different, y'all + del get_all + + +class GCToggler: + """The ``GCToggler`` is a context-manager that allows one to safely + take more control of your garbage collection schedule. Anecdotal + experience says certain object-creation-heavy tasks see speedups + of around 10% by simply doing one explicit collection at the very + end, especially if most of the objects will stay resident. + + Two GCTogglers are already present in the ``gcutils`` module: + + - :data:`toggle_gc` simply turns off GC at context entrance, and + re-enables at exit + - :data:`toggle_gc_postcollect` does the same, but triggers an + explicit collection after re-enabling. + + >>> with toggle_gc: + ... x = [object() for i in range(1000)] + + Between those two instances, the ``GCToggler`` type probably won't + be used much directly, but is documented for inheritance purposes. + """ + def __init__(self, postcollect=False): + self.postcollect = postcollect + + def __enter__(self): + gc.disable() + + def __exit__(self, exc_type, exc_val, exc_tb): + gc.enable() + if self.postcollect: + gc.collect() + + +toggle_gc = GCToggler() +"""A context manager for disabling GC for a code block. See +:class:`GCToggler` for more details.""" + + +toggle_gc_postcollect = GCToggler(postcollect=True) +"""A context manager for disabling GC for a code block, and collecting +before re-enabling. See :class:`GCToggler` for more details.""" diff --git a/data/miniconda3/lib/python3.13/site-packages/boltons/ioutils.py b/data/miniconda3/lib/python3.13/site-packages/boltons/ioutils.py new file mode 100644 index 0000000000000000000000000000000000000000..bfcaf3fc1923eedf788b4fb403d699f7743d8d09 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/boltons/ioutils.py @@ -0,0 +1,587 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# * The names of the contributors may not be used to endorse or +# promote products derived from this software without specific +# prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +# Coding decl above needed for rendering the emdash properly in the +# documentation. + +""" +Module ``ioutils`` implements a number of helper classes and functions which +are useful when dealing with input, output, and bytestreams in a variety of +ways. +""" +import os +from io import BytesIO, IOBase +from abc import ( + ABCMeta, + abstractmethod, + abstractproperty, +) +from errno import EINVAL +from codecs import EncodedFile +from tempfile import TemporaryFile +from itertools import zip_longest + +READ_CHUNK_SIZE = 21333 +""" +Number of bytes to read at a time. The value is ~ 1/3rd of 64k which means that +the value will easily fit in the L2 cache of most processors even if every +codepoint in a string is three bytes long which makes it a nice fast default +value. +""" + + +class SpooledIOBase(IOBase): + """ + A base class shared by the SpooledBytesIO and SpooledStringIO classes. + + The SpooledTemporaryFile class is missing several attributes and methods + present in the StringIO implementation. This brings the api as close to + parity as possible so that classes derived from SpooledIOBase can be used + as near drop-in replacements to save memory. + """ + __metaclass__ = ABCMeta + + def __init__(self, max_size=5000000, dir=None): + self._max_size = max_size + self._dir = dir + + def _checkClosed(self, msg=None): + """Raise a ValueError if file is closed""" + if self.closed: + raise ValueError('I/O operation on closed file.' + if msg is None else msg) + @abstractmethod + def read(self, n=-1): + """Read n characters from the buffer""" + + @abstractmethod + def write(self, s): + """Write into the buffer""" + + @abstractmethod + def seek(self, pos, mode=0): + """Seek to a specific point in a file""" + + @abstractmethod + def readline(self, length=None): + """Returns the next available line""" + + @abstractmethod + def readlines(self, sizehint=0): + """Returns a list of all lines from the current position forward""" + + def writelines(self, lines): + """ + Write lines to the file from an interable. + + NOTE: writelines() does NOT add line separators. + """ + self._checkClosed() + for line in lines: + self.write(line) + + @abstractmethod + def rollover(self): + """Roll file-like-object over into a real temporary file""" + + @abstractmethod + def tell(self): + """Return the current position""" + + @abstractproperty + def buffer(self): + """Should return a flo instance""" + + @abstractproperty + def _rolled(self): + """Returns whether the file has been rolled to a real file or not""" + + @abstractproperty + def len(self): + """Returns the length of the data""" + + def _get_softspace(self): + return self.buffer.softspace + + def _set_softspace(self, val): + self.buffer.softspace = val + + softspace = property(_get_softspace, _set_softspace) + + @property + def _file(self): + return self.buffer + + def close(self): + return self.buffer.close() + + def flush(self): + self._checkClosed() + return self.buffer.flush() + + def isatty(self): + self._checkClosed() + return self.buffer.isatty() + + @property + def closed(self): + return self.buffer.closed + + @property + def pos(self): + return self.tell() + + @property + def buf(self): + return self.getvalue() + + def fileno(self): + self.rollover() + return self.buffer.fileno() + + def truncate(self, size=None): + """ + Truncate the contents of the buffer. + + Custom version of truncate that takes either no arguments (like the + real SpooledTemporaryFile) or a single argument that truncates the + value to a certain index location. + """ + self._checkClosed() + if size is None: + return self.buffer.truncate() + + if size < 0: + raise OSError(EINVAL, "Negative size not allowed") + + # Emulate truncation to a particular location + pos = self.tell() + self.seek(size) + self.buffer.truncate() + if pos < size: + self.seek(pos) + + def getvalue(self): + """Return the entire files contents.""" + self._checkClosed() + pos = self.tell() + self.seek(0) + val = self.read() + self.seek(pos) + return val + + def seekable(self): + return True + + def readable(self): + return True + + def writable(self): + return True + + def __next__(self): + self._checkClosed() + line = self.readline() + if not line: + pos = self.buffer.tell() + self.buffer.seek(0, os.SEEK_END) + if pos == self.buffer.tell(): + raise StopIteration + else: + self.buffer.seek(pos) + return line + + next = __next__ + + def __len__(self): + return self.len + + def __iter__(self): + self._checkClosed() + return self + + def __enter__(self): + self._checkClosed() + return self + + def __exit__(self, *args): + self._file.close() + + def __eq__(self, other): + if isinstance(other, self.__class__): + self_pos = self.tell() + other_pos = other.tell() + try: + self.seek(0) + other.seek(0) + eq = True + for self_line, other_line in zip_longest(self, other): + if self_line != other_line: + eq = False + break + self.seek(self_pos) + other.seek(other_pos) + except Exception: + # Attempt to return files to original position if there were any errors + try: + self.seek(self_pos) + except Exception: + pass + try: + other.seek(other_pos) + except Exception: + pass + raise + else: + return eq + return False + + def __ne__(self, other): + return not self.__eq__(other) + + def __bool__(self): + return True + + def __del__(self): + """Can fail when called at program exit so suppress traceback.""" + try: + self.close() + except Exception: + pass + + +class SpooledBytesIO(SpooledIOBase): + """ + SpooledBytesIO is a spooled file-like-object that only accepts bytes. On + Python 2.x this means the 'str' type; on Python 3.x this means the 'bytes' + type. Bytes are written in and retrieved exactly as given, but it will + raise TypeErrors if something other than bytes are written. + + Example:: + + >>> from boltons import ioutils + >>> with ioutils.SpooledBytesIO() as f: + ... f.write(b"Happy IO") + ... _ = f.seek(0) + ... isinstance(f.getvalue(), bytes) + True + """ + + def read(self, n=-1): + self._checkClosed() + return self.buffer.read(n) + + def write(self, s): + self._checkClosed() + if not isinstance(s, bytes): + raise TypeError("bytes expected, got {}".format( + type(s).__name__ + )) + + if self.tell() + len(s) >= self._max_size: + self.rollover() + self.buffer.write(s) + + def seek(self, pos, mode=0): + self._checkClosed() + return self.buffer.seek(pos, mode) + + def readline(self, length=None): + self._checkClosed() + if length: + return self.buffer.readline(length) + else: + return self.buffer.readline() + + def readlines(self, sizehint=0): + return self.buffer.readlines(sizehint) + + def rollover(self): + """Roll the StringIO over to a TempFile""" + if not self._rolled: + tmp = TemporaryFile(dir=self._dir) + pos = self.buffer.tell() + tmp.write(self.buffer.getvalue()) + tmp.seek(pos) + self.buffer.close() + self._buffer = tmp + + @property + def _rolled(self): + return not isinstance(self.buffer, BytesIO) + + @property + def buffer(self): + try: + return self._buffer + except AttributeError: + self._buffer = BytesIO() + return self._buffer + + @property + def len(self): + """Determine the length of the file""" + pos = self.tell() + if self._rolled: + self.seek(0) + val = os.fstat(self.fileno()).st_size + else: + self.seek(0, os.SEEK_END) + val = self.tell() + self.seek(pos) + return val + + def tell(self): + self._checkClosed() + return self.buffer.tell() + + +class SpooledStringIO(SpooledIOBase): + """ + SpooledStringIO is a spooled file-like-object that only accepts unicode + values. On Python 2.x this means the 'unicode' type and on Python 3.x this + means the 'str' type. Values are accepted as unicode and then coerced into + utf-8 encoded bytes for storage. On retrieval, the values are returned as + unicode. + + Example:: + + >>> from boltons import ioutils + >>> with ioutils.SpooledStringIO() as f: + ... f.write(u"\u2014 Hey, an emdash!") + ... _ = f.seek(0) + ... isinstance(f.read(), str) + True + + """ + def __init__(self, *args, **kwargs): + self._tell = 0 + super().__init__(*args, **kwargs) + + def read(self, n=-1): + self._checkClosed() + ret = self.buffer.reader.read(n, n) + self._tell = self.tell() + len(ret) + return ret + + def write(self, s): + self._checkClosed() + if not isinstance(s, str): + raise TypeError("str expected, got {}".format( + type(s).__name__ + )) + current_pos = self.tell() + if self.buffer.tell() + len(s.encode('utf-8')) >= self._max_size: + self.rollover() + self.buffer.write(s.encode('utf-8')) + self._tell = current_pos + len(s) + + def _traverse_codepoints(self, current_position, n): + """Traverse from current position to the right n codepoints""" + dest = current_position + n + while True: + if current_position == dest: + # By chance we've landed on the right position, break + break + + # If the read would take us past the intended position then + # seek only enough to cover the offset + if current_position + READ_CHUNK_SIZE > dest: + self.read(dest - current_position) + break + else: + ret = self.read(READ_CHUNK_SIZE) + + # Increment our current position + current_position += READ_CHUNK_SIZE + + # If we kept reading but there was nothing here, break + # as we are at the end of the file + if not ret: + break + + return dest + + def seek(self, pos, mode=0): + """Traverse from offset to the specified codepoint""" + self._checkClosed() + # Seek to position from the start of the file + if mode == os.SEEK_SET: + self.buffer.seek(0) + self._traverse_codepoints(0, pos) + self._tell = pos + # Seek to new position relative to current position + elif mode == os.SEEK_CUR: + start_pos = self.tell() + self._traverse_codepoints(self.tell(), pos) + self._tell = start_pos + pos + elif mode == os.SEEK_END: + self.buffer.seek(0) + dest_position = self.len - pos + self._traverse_codepoints(0, dest_position) + self._tell = dest_position + else: + raise ValueError( + f"Invalid whence ({mode}, should be 0, 1, or 2)" + ) + return self.tell() + + def readline(self, length=None): + self._checkClosed() + ret = self.buffer.readline(length).decode('utf-8') + self._tell = self.tell() + len(ret) + return ret + + def readlines(self, sizehint=0): + ret = [x.decode('utf-8') for x in self.buffer.readlines(sizehint)] + self._tell = self.tell() + sum(len(x) for x in ret) + return ret + + @property + def buffer(self): + try: + return self._buffer + except AttributeError: + self._buffer = EncodedFile(BytesIO(), data_encoding='utf-8') + return self._buffer + + @property + def _rolled(self): + return not isinstance(self.buffer.stream, BytesIO) + + def rollover(self): + """Roll the buffer over to a TempFile""" + if not self._rolled: + tmp = EncodedFile(TemporaryFile(dir=self._dir), + data_encoding='utf-8') + pos = self.buffer.tell() + tmp.write(self.buffer.getvalue()) + tmp.seek(pos) + self.buffer.close() + self._buffer = tmp + + def tell(self): + """Return the codepoint position""" + self._checkClosed() + return self._tell + + @property + def len(self): + """Determine the number of codepoints in the file""" + pos = self.buffer.tell() + self.buffer.seek(0) + total = 0 + while True: + ret = self.read(READ_CHUNK_SIZE) + if not ret: + break + total += len(ret) + self.buffer.seek(pos) + return total + + +def is_text_fileobj(fileobj): + if getattr(fileobj, 'encoding', False): + # codecs.open and io.TextIOBase + return True + if getattr(fileobj, 'getvalue', False): + # StringIO.StringIO / io.StringIO + try: + if isinstance(fileobj.getvalue(), str): + return True + except Exception: + pass + return False + + +class MultiFileReader: + """Takes a list of open files or file-like objects and provides an + interface to read from them all contiguously. Like + :func:`itertools.chain()`, but for reading files. + + >>> mfr = MultiFileReader(BytesIO(b'ab'), BytesIO(b'cd'), BytesIO(b'e')) + >>> mfr.read(3).decode('ascii') + u'abc' + >>> mfr.read(3).decode('ascii') + u'de' + + The constructor takes as many fileobjs as you hand it, and will + raise a TypeError on non-file-like objects. A ValueError is raised + when file-like objects are a mix of bytes- and text-handling + objects (for instance, BytesIO and StringIO). + """ + + def __init__(self, *fileobjs): + if not all([callable(getattr(f, 'read', None)) and + callable(getattr(f, 'seek', None)) for f in fileobjs]): + raise TypeError('MultiFileReader expected file-like objects' + ' with .read() and .seek()') + if all([is_text_fileobj(f) for f in fileobjs]): + # codecs.open and io.TextIOBase + self._joiner = '' + elif any([is_text_fileobj(f) for f in fileobjs]): + raise ValueError('All arguments to MultiFileReader must handle' + ' bytes OR text, not a mix') + else: + # open/file and io.BytesIO + self._joiner = b'' + self._fileobjs = fileobjs + self._index = 0 + + def read(self, amt=None): + """Read up to the specified *amt*, seamlessly bridging across + files. Returns the appropriate type of string (bytes or text) + for the input, and returns an empty string when the files are + exhausted. + """ + if not amt: + return self._joiner.join(f.read() for f in self._fileobjs) + parts = [] + while amt > 0 and self._index < len(self._fileobjs): + parts.append(self._fileobjs[self._index].read(amt)) + got = len(parts[-1]) + if got < amt: + self._index += 1 + amt -= got + return self._joiner.join(parts) + + def seek(self, offset, whence=os.SEEK_SET): + """Enables setting position of the file cursor to a given + *offset*. Currently only supports ``offset=0``. + """ + if whence != os.SEEK_SET: + raise NotImplementedError( + 'MultiFileReader.seek() only supports os.SEEK_SET') + if offset != 0: + raise NotImplementedError( + 'MultiFileReader only supports seeking to start at this time') + for f in self._fileobjs: + f.seek(0) diff --git a/data/miniconda3/lib/python3.13/site-packages/boltons/iterutils.py b/data/miniconda3/lib/python3.13/site-packages/boltons/iterutils.py new file mode 100644 index 0000000000000000000000000000000000000000..e0a5b900173d93689acf0e6b09dd75d87924da5b --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/boltons/iterutils.py @@ -0,0 +1,1609 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# * The names of the contributors may not be used to endorse or +# promote products derived from this software without specific +# prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +""":mod:`itertools` is full of great examples of Python generator +usage. However, there are still some critical gaps. ``iterutils`` +fills many of those gaps with featureful, tested, and Pythonic +solutions. + +Many of the functions below have two versions, one which +returns an iterator (denoted by the ``*_iter`` naming pattern), and a +shorter-named convenience form that returns a list. Some of the +following are based on examples in itertools docs. +""" + +import os +import math +import time +import codecs +import random +import itertools +from itertools import zip_longest +from collections.abc import Mapping, Sequence, Set, ItemsView, Iterable + + +try: + from .typeutils import make_sentinel + _UNSET = make_sentinel('_UNSET') + _REMAP_EXIT = make_sentinel('_REMAP_EXIT') +except ImportError: + _REMAP_EXIT = object() + _UNSET = object() + + +def is_iterable(obj): + """Similar in nature to :func:`callable`, ``is_iterable`` returns + ``True`` if an object is `iterable`_, ``False`` if not. + + >>> is_iterable([]) + True + >>> is_iterable(object()) + False + + .. _iterable: https://docs.python.org/2/glossary.html#term-iterable + """ + try: + iter(obj) + except TypeError: + return False + return True + + +def is_scalar(obj): + """A near-mirror of :func:`is_iterable`. Returns ``False`` if an + object is an iterable container type. Strings are considered + scalar as well, because strings are more often treated as whole + values as opposed to iterables of 1-character substrings. + + >>> is_scalar(object()) + True + >>> is_scalar(range(10)) + False + >>> is_scalar('hello') + True + """ + return not is_iterable(obj) or isinstance(obj, (str, bytes)) + + +def is_collection(obj): + """The opposite of :func:`is_scalar`. Returns ``True`` if an object + is an iterable other than a string. + + >>> is_collection(object()) + False + >>> is_collection(range(10)) + True + >>> is_collection('hello') + False + """ + return is_iterable(obj) and not isinstance(obj, (str, bytes)) + + +def split(src, sep=None, maxsplit=None): + """Splits an iterable based on a separator. Like :meth:`str.split`, + but for all iterables. Returns a list of lists. + + >>> split(['hi', 'hello', None, None, 'sup', None, 'soap', None]) + [['hi', 'hello'], ['sup'], ['soap']] + + See :func:`split_iter` docs for more info. + """ + return list(split_iter(src, sep, maxsplit)) + + +def split_iter(src, sep=None, maxsplit=None): + """Splits an iterable based on a separator, *sep*, a max of + *maxsplit* times (no max by default). *sep* can be: + + * a single value + * an iterable of separators + * a single-argument callable that returns True when a separator is + encountered + + ``split_iter()`` yields lists of non-separator values. A separator will + never appear in the output. + + >>> list(split_iter(['hi', 'hello', None, None, 'sup', None, 'soap', None])) + [['hi', 'hello'], ['sup'], ['soap']] + + Note that ``split_iter`` is based on :func:`str.split`, so if + *sep* is ``None``, ``split()`` **groups** separators. If empty lists + are desired between two contiguous ``None`` values, simply use + ``sep=[None]``: + + >>> list(split_iter(['hi', 'hello', None, None, 'sup', None])) + [['hi', 'hello'], ['sup']] + >>> list(split_iter(['hi', 'hello', None, None, 'sup', None], sep=[None])) + [['hi', 'hello'], [], ['sup'], []] + + Using a callable separator: + + >>> falsy_sep = lambda x: not x + >>> list(split_iter(['hi', 'hello', None, '', 'sup', False], falsy_sep)) + [['hi', 'hello'], [], ['sup'], []] + + See :func:`split` for a list-returning version. + + """ + if not is_iterable(src): + raise TypeError('expected an iterable') + + if maxsplit is not None: + maxsplit = int(maxsplit) + if maxsplit == 0: + yield [src] + return + + if callable(sep): + sep_func = sep + elif not is_scalar(sep): + sep = frozenset(sep) + def sep_func(x): return x in sep + else: + def sep_func(x): return x == sep + + cur_group = [] + split_count = 0 + for s in src: + if maxsplit is not None and split_count >= maxsplit: + def sep_func(x): return False + if sep_func(s): + if sep is None and not cur_group: + # If sep is none, str.split() "groups" separators + # check the str.split() docs for more info + continue + split_count += 1 + yield cur_group + cur_group = [] + else: + cur_group.append(s) + + if cur_group or sep is not None: + yield cur_group + return + + +def lstrip(iterable, strip_value=None): + """Strips values from the beginning of an iterable. Stripped items will + match the value of the argument strip_value. Functionality is analogous + to that of the method str.lstrip. Returns a list. + + >>> lstrip(['Foo', 'Bar', 'Bam'], 'Foo') + ['Bar', 'Bam'] + + """ + return list(lstrip_iter(iterable, strip_value)) + + +def lstrip_iter(iterable, strip_value=None): + """Strips values from the beginning of an iterable. Stripped items will + match the value of the argument strip_value. Functionality is analogous + to that of the method str.lstrip. Returns a generator. + + >>> list(lstrip_iter(['Foo', 'Bar', 'Bam'], 'Foo')) + ['Bar', 'Bam'] + + """ + iterator = iter(iterable) + for i in iterator: + if i != strip_value: + yield i + break + for i in iterator: + yield i + + +def rstrip(iterable, strip_value=None): + """Strips values from the end of an iterable. Stripped items will + match the value of the argument strip_value. Functionality is analogous + to that of the method str.rstrip. Returns a list. + + >>> rstrip(['Foo', 'Bar', 'Bam'], 'Bam') + ['Foo', 'Bar'] + + """ + return list(rstrip_iter(iterable, strip_value)) + + +def rstrip_iter(iterable, strip_value=None): + """Strips values from the end of an iterable. Stripped items will + match the value of the argument strip_value. Functionality is analogous + to that of the method str.rstrip. Returns a generator. + + >>> list(rstrip_iter(['Foo', 'Bar', 'Bam'], 'Bam')) + ['Foo', 'Bar'] + + """ + iterator = iter(iterable) + for i in iterator: + if i == strip_value: + cache = list() + cache.append(i) + broken = False + for i in iterator: + if i == strip_value: + cache.append(i) + else: + broken = True + break + if not broken: # Return to caller here because the end of the + return # iterator has been reached + yield from cache + yield i + + +def strip(iterable, strip_value=None): + """Strips values from the beginning and end of an iterable. Stripped items + will match the value of the argument strip_value. Functionality is + analogous to that of the method str.strip. Returns a list. + + >>> strip(['Fu', 'Foo', 'Bar', 'Bam', 'Fu'], 'Fu') + ['Foo', 'Bar', 'Bam'] + + """ + return list(strip_iter(iterable, strip_value)) + + +def strip_iter(iterable, strip_value=None): + """Strips values from the beginning and end of an iterable. Stripped items + will match the value of the argument strip_value. Functionality is + analogous to that of the method str.strip. Returns a generator. + + >>> list(strip_iter(['Fu', 'Foo', 'Bar', 'Bam', 'Fu'], 'Fu')) + ['Foo', 'Bar', 'Bam'] + + """ + return rstrip_iter(lstrip_iter(iterable, strip_value), strip_value) + + +def chunked(src, size, count=None, **kw): + """Returns a list of *count* chunks, each with *size* elements, + generated from iterable *src*. If *src* is not evenly divisible by + *size*, the final chunk will have fewer than *size* elements. + Provide the *fill* keyword argument to provide a pad value and + enable padding, otherwise no padding will take place. + + >>> chunked(range(10), 3) + [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]] + >>> chunked(range(10), 3, fill=None) + [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, None, None]] + >>> chunked(range(10), 3, count=2) + [[0, 1, 2], [3, 4, 5]] + + See :func:`chunked_iter` for more info. + """ + chunk_iter = chunked_iter(src, size, **kw) + if count is None: + return list(chunk_iter) + else: + return list(itertools.islice(chunk_iter, count)) + + +def _validate_positive_int(value, name, strictly_positive=True): + value = int(value) + if value < 0 or (strictly_positive and value == 0): + raise ValueError('expected a positive integer ' + name) + return value + + +def chunked_iter(src, size, **kw): + """Generates *size*-sized chunks from *src* iterable. Unless the + optional *fill* keyword argument is provided, iterables not evenly + divisible by *size* will have a final chunk that is smaller than + *size*. + + >>> list(chunked_iter(range(10), 3)) + [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]] + >>> list(chunked_iter(range(10), 3, fill=None)) + [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, None, None]] + + Note that ``fill=None`` in fact uses ``None`` as the fill value. + """ + # TODO: add count kwarg? + if not is_iterable(src): + raise TypeError('expected an iterable') + size = _validate_positive_int(size, 'chunk size') + do_fill = True + try: + fill_val = kw.pop('fill') + except KeyError: + do_fill = False + fill_val = None + if kw: + raise ValueError('got unexpected keyword arguments: %r' % kw.keys()) + if not src: + return + + def postprocess(chk): return chk + if isinstance(src, (str, bytes)): + def postprocess(chk, _sep=type(src)()): return _sep.join(chk) + if isinstance(src, bytes): + def postprocess(chk): return bytes(chk) + src_iter = iter(src) + while True: + cur_chunk = list(itertools.islice(src_iter, size)) + if not cur_chunk: + break + lc = len(cur_chunk) + if lc < size and do_fill: + cur_chunk[lc:] = [fill_val] * (size - lc) + yield postprocess(cur_chunk) + return + + +def chunk_ranges(input_size, chunk_size, input_offset=0, overlap_size=0, align=False): + """Generates *chunk_size*-sized chunk ranges for an input with length *input_size*. + Optionally, a start of the input can be set via *input_offset*, and + and overlap between the chunks may be specified via *overlap_size*. + Also, if *align* is set to *True*, any items with *i % (chunk_size-overlap_size) == 0* + are always at the beginning of the chunk. + + Returns an iterator of (start, end) tuples, one tuple per chunk. + + >>> list(chunk_ranges(input_offset=10, input_size=10, chunk_size=5)) + [(10, 15), (15, 20)] + >>> list(chunk_ranges(input_offset=10, input_size=10, chunk_size=5, overlap_size=1)) + [(10, 15), (14, 19), (18, 20)] + >>> list(chunk_ranges(input_offset=10, input_size=10, chunk_size=5, overlap_size=2)) + [(10, 15), (13, 18), (16, 20)] + + >>> list(chunk_ranges(input_offset=4, input_size=15, chunk_size=5, align=False)) + [(4, 9), (9, 14), (14, 19)] + >>> list(chunk_ranges(input_offset=4, input_size=15, chunk_size=5, align=True)) + [(4, 5), (5, 10), (10, 15), (15, 19)] + + >>> list(chunk_ranges(input_offset=2, input_size=15, chunk_size=5, overlap_size=1, align=False)) + [(2, 7), (6, 11), (10, 15), (14, 17)] + >>> list(chunk_ranges(input_offset=2, input_size=15, chunk_size=5, overlap_size=1, align=True)) + [(2, 5), (4, 9), (8, 13), (12, 17)] + >>> list(chunk_ranges(input_offset=3, input_size=15, chunk_size=5, overlap_size=1, align=True)) + [(3, 5), (4, 9), (8, 13), (12, 17), (16, 18)] + """ + input_size = _validate_positive_int( + input_size, 'input_size', strictly_positive=False) + chunk_size = _validate_positive_int(chunk_size, 'chunk_size') + input_offset = _validate_positive_int( + input_offset, 'input_offset', strictly_positive=False) + overlap_size = _validate_positive_int( + overlap_size, 'overlap_size', strictly_positive=False) + + input_stop = input_offset + input_size + + if align: + initial_chunk_len = chunk_size - \ + input_offset % (chunk_size - overlap_size) + if initial_chunk_len != overlap_size: + yield (input_offset, min(input_offset + initial_chunk_len, input_stop)) + if input_offset + initial_chunk_len >= input_stop: + return + input_offset = input_offset + initial_chunk_len - overlap_size + + for i in range(input_offset, input_stop, chunk_size - overlap_size): + yield (i, min(i + chunk_size, input_stop)) + + if i + chunk_size >= input_stop: + return + + +def pairwise(src, end=_UNSET): + """Convenience function for calling :func:`windowed` on *src*, with + *size* set to 2. + + >>> pairwise(range(5)) + [(0, 1), (1, 2), (2, 3), (3, 4)] + >>> pairwise([]) + [] + + Unless *end* is set, the number of pairs is always one less than + the number of elements in the iterable passed in, except on an empty input, + which will return an empty list. + + With *end* set, a number of pairs equal to the length of *src* is returned, + with the last item of the last pair being equal to *end*. + + >>> list(pairwise(range(3), end=None)) + [(0, 1), (1, 2), (2, None)] + + This way, *end* values can be useful as sentinels to signal the end of the iterable. + """ + return windowed(src, 2, fill=end) + + +def pairwise_iter(src, end=_UNSET): + """Convenience function for calling :func:`windowed_iter` on *src*, + with *size* set to 2. + + >>> list(pairwise_iter(range(5))) + [(0, 1), (1, 2), (2, 3), (3, 4)] + >>> list(pairwise_iter([])) + [] + + Unless *end* is set, the number of pairs is always one less + than the number of elements in the iterable passed in, + or zero, when *src* is empty. + + With *end* set, a number of pairs equal to the length of *src* is returned, + with the last item of the last pair being equal to *end*. + + >>> list(pairwise_iter(range(3), end=None)) + [(0, 1), (1, 2), (2, None)] + + This way, *end* values can be useful as sentinels to signal the end + of the iterable. For infinite iterators, setting *end* has no effect. + """ + return windowed_iter(src, 2, fill=end) + + +def windowed(src, size, fill=_UNSET): + """Returns tuples with exactly length *size*. If *fill* is unset + and the iterable is too short to make a window of length *size*, + no tuples are returned. See :func:`windowed_iter` for more. + """ + return list(windowed_iter(src, size, fill=fill)) + + +def windowed_iter(src, size, fill=_UNSET): + """Returns tuples with length *size* which represent a sliding + window over iterable *src*. + + >>> list(windowed_iter(range(7), 3)) + [(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6)] + + If *fill* is unset, and the iterable is too short to make a window + of length *size*, then no window tuples are returned. + + >>> list(windowed_iter(range(3), 5)) + [] + + With *fill* set, the iterator always yields a number of windows + equal to the length of the *src* iterable. + + >>> windowed(range(4), 3, fill=None) + [(0, 1, 2), (1, 2, 3), (2, 3, None), (3, None, None)] + + This way, *fill* values can be useful to signal the end of the iterable. + For infinite iterators, setting *fill* has no effect. + """ + tees = itertools.tee(src, size) + if fill is _UNSET: + try: + for i, t in enumerate(tees): + for _ in range(i): + next(t) + except StopIteration: + return zip([]) + return zip(*tees) + + for i, t in enumerate(tees): + for _ in range(i): + try: + next(t) + except StopIteration: + continue + return zip_longest(*tees, fillvalue=fill) + + +def xfrange(stop, start=None, step=1.0): + """Same as :func:`frange`, but generator-based instead of returning a + list. + + >>> tuple(xfrange(1, 3, step=0.75)) + (1.0, 1.75, 2.5) + + See :func:`frange` for more details. + """ + if not step: + raise ValueError('step must be non-zero') + if start is None: + start, stop = 0.0, stop * 1.0 + else: + # swap when all args are used + stop, start = start * 1.0, stop * 1.0 + cur = start + while cur < stop: + yield cur + cur += step + + +def frange(stop, start=None, step=1.0): + """A :func:`range` clone for float-based ranges. + + >>> frange(5) + [0.0, 1.0, 2.0, 3.0, 4.0] + >>> frange(6, step=1.25) + [0.0, 1.25, 2.5, 3.75, 5.0] + >>> frange(100.5, 101.5, 0.25) + [100.5, 100.75, 101.0, 101.25] + >>> frange(5, 0) + [] + >>> frange(5, 0, step=-1.25) + [5.0, 3.75, 2.5, 1.25] + """ + if not step: + raise ValueError('step must be non-zero') + if start is None: + start, stop = 0.0, stop * 1.0 + else: + # swap when all args are used + stop, start = start * 1.0, stop * 1.0 + count = int(math.ceil((stop - start) / step)) + ret = [None] * count + if not ret: + return ret + ret[0] = start + for i in range(1, count): + ret[i] = ret[i - 1] + step + return ret + + +def backoff(start, stop, count=None, factor=2.0, jitter=False): + """Returns a list of geometrically-increasing floating-point numbers, + suitable for usage with `exponential backoff`_. Exactly like + :func:`backoff_iter`, but without the ``'repeat'`` option for + *count*. See :func:`backoff_iter` for more details. + + .. _exponential backoff: https://en.wikipedia.org/wiki/Exponential_backoff + + >>> backoff(1, 10) + [1.0, 2.0, 4.0, 8.0, 10.0] + """ + if count == 'repeat': + raise ValueError("'repeat' supported in backoff_iter, not backoff") + return list(backoff_iter(start, stop, count=count, + factor=factor, jitter=jitter)) + + +def backoff_iter(start, stop, count=None, factor=2.0, jitter=False): + """Generates a sequence of geometrically-increasing floats, suitable + for usage with `exponential backoff`_. Starts with *start*, + increasing by *factor* until *stop* is reached, optionally + stopping iteration once *count* numbers are yielded. *factor* + defaults to 2. In general retrying with properly-configured + backoff creates a better-behaved component for a larger service + ecosystem. + + .. _exponential backoff: https://en.wikipedia.org/wiki/Exponential_backoff + + >>> list(backoff_iter(1.0, 10.0, count=5)) + [1.0, 2.0, 4.0, 8.0, 10.0] + >>> list(backoff_iter(1.0, 10.0, count=8)) + [1.0, 2.0, 4.0, 8.0, 10.0, 10.0, 10.0, 10.0] + >>> list(backoff_iter(0.25, 100.0, factor=10)) + [0.25, 2.5, 25.0, 100.0] + + A simplified usage example: + + .. code-block:: python + + for timeout in backoff_iter(0.25, 5.0): + try: + res = network_call() + break + except Exception as e: + log(e) + time.sleep(timeout) + + An enhancement for large-scale systems would be to add variation, + or *jitter*, to timeout values. This is done to avoid a thundering + herd on the receiving end of the network call. + + Finally, for *count*, the special value ``'repeat'`` can be passed to + continue yielding indefinitely. + + Args: + + start (float): Positive number for baseline. + stop (float): Positive number for maximum. + count (int): Number of steps before stopping + iteration. Defaults to the number of steps between *start* and + *stop*. Pass the string, `'repeat'`, to continue iteration + indefinitely. + factor (float): Rate of exponential increase. Defaults to `2.0`, + e.g., `[1, 2, 4, 8, 16]`. + jitter (float): A factor between `-1.0` and `1.0`, used to + uniformly randomize and thus spread out timeouts in a distributed + system, avoiding rhythm effects. Positive values use the base + backoff curve as a maximum, negative values use the curve as a + minimum. Set to 1.0 or `True` for a jitter approximating + Ethernet's time-tested backoff solution. Defaults to `False`. + + """ + start = float(start) + stop = float(stop) + factor = float(factor) + if start < 0.0: + raise ValueError('expected start >= 0, not %r' % start) + if factor < 1.0: + raise ValueError('expected factor >= 1.0, not %r' % factor) + if stop == 0.0: + raise ValueError('expected stop >= 0') + if stop < start: + raise ValueError('expected stop >= start, not %r' % stop) + if count is None: + denom = start if start else 1 + count = 1 + math.ceil(math.log(stop/denom, factor)) + count = count if start else count + 1 + if count != 'repeat' and count < 0: + raise ValueError('count must be positive or "repeat", not %r' % count) + if jitter: + jitter = float(jitter) + if not (-1.0 <= jitter <= 1.0): + raise ValueError('expected jitter -1 <= j <= 1, not: %r' % jitter) + + cur, i = start, 0 + while count == 'repeat' or i < count: + if not jitter: + cur_ret = cur + elif jitter: + cur_ret = cur - (cur * jitter * random.random()) + yield cur_ret + i += 1 + if cur == 0: + cur = 1 + elif cur < stop: + cur *= factor + if cur > stop: + cur = stop + return + + +def bucketize(src, key=bool, value_transform=None, key_filter=None): + """Group values in the *src* iterable by the value returned by *key*. + + >>> bucketize(range(5)) + {False: [0], True: [1, 2, 3, 4]} + >>> is_odd = lambda x: x % 2 == 1 + >>> bucketize(range(5), is_odd) + {False: [0, 2, 4], True: [1, 3]} + + *key* is :class:`bool` by default, but can either be a callable or a string or a list + if it is a string, it is the name of the attribute on which to bucketize objects. + + >>> bucketize([1+1j, 2+2j, 1, 2], key='real') + {1.0: [(1+1j), 1], 2.0: [(2+2j), 2]} + + if *key* is a list, it contains the buckets where to put each object + + >>> bucketize([1,2,365,4,98],key=[0,1,2,0,2]) + {0: [1, 4], 1: [2], 2: [365, 98]} + + + Value lists are not deduplicated: + + >>> bucketize([None, None, None, 'hello']) + {False: [None, None, None], True: ['hello']} + + Bucketize into more than 3 groups + + >>> bucketize(range(10), lambda x: x % 3) + {0: [0, 3, 6, 9], 1: [1, 4, 7], 2: [2, 5, 8]} + + ``bucketize`` has a couple of advanced options useful in certain + cases. *value_transform* can be used to modify values as they are + added to buckets, and *key_filter* will allow excluding certain + buckets from being collected. + + >>> bucketize(range(5), value_transform=lambda x: x*x) + {False: [0], True: [1, 4, 9, 16]} + + >>> bucketize(range(10), key=lambda x: x % 3, key_filter=lambda k: k % 3 != 1) + {0: [0, 3, 6, 9], 2: [2, 5, 8]} + + Note in some of these examples there were at most two keys, ``True`` and + ``False``, and each key present has a list with at least one + item. See :func:`partition` for a version specialized for binary + use cases. + + """ + if not is_iterable(src): + raise TypeError('expected an iterable') + elif isinstance(key, list): + if len(key) != len(src): + raise ValueError("key and src have to be the same length") + src = zip(key, src) + + if isinstance(key, str): + def key_func(x): return getattr(x, key, x) + elif callable(key): + key_func = key + elif isinstance(key, list): + def key_func(x): return x[0] + else: + raise TypeError('expected key to be callable or a string or a list') + + if value_transform is None: + def value_transform(x): return x + if not callable(value_transform): + raise TypeError('expected callable value transform function') + if isinstance(key, list): + f = value_transform + def value_transform(x): return f(x[1]) + + ret = {} + for val in src: + key_of_val = key_func(val) + if key_filter is None or key_filter(key_of_val): + ret.setdefault(key_of_val, []).append(value_transform(val)) + return ret + + +def partition(src, key=bool): + """No relation to :meth:`str.partition`, ``partition`` is like + :func:`bucketize`, but for added convenience returns a tuple of + ``(truthy_values, falsy_values)``. + + >>> nonempty, empty = partition(['', '', 'hi', '', 'bye']) + >>> nonempty + ['hi', 'bye'] + + *key* defaults to :class:`bool`, but can be carefully overridden to + use either a function that returns either ``True`` or ``False`` or + a string name of the attribute on which to partition objects. + + >>> import string + >>> is_digit = lambda x: x in string.digits + >>> decimal_digits, hexletters = partition(string.hexdigits, is_digit) + >>> ''.join(decimal_digits), ''.join(hexletters) + ('0123456789', 'abcdefABCDEF') + """ + bucketized = bucketize(src, key) + return bucketized.get(True, []), bucketized.get(False, []) + + +def unique(src, key=None): + """``unique()`` returns a list of unique values, as determined by + *key*, in the order they first appeared in the input iterable, + *src*. + + >>> ones_n_zeros = '11010110001010010101010' + >>> ''.join(unique(ones_n_zeros)) + '10' + + See :func:`unique_iter` docs for more details. + """ + return list(unique_iter(src, key)) + + +def unique_iter(src, key=None): + """Yield unique elements from the iterable, *src*, based on *key*, + in the order in which they first appeared in *src*. + + >>> repetitious = [1, 2, 3] * 10 + >>> list(unique_iter(repetitious)) + [1, 2, 3] + + By default, *key* is the object itself, but *key* can either be a + callable or, for convenience, a string name of the attribute on + which to uniqueify objects, falling back on identity when the + attribute is not present. + + >>> pleasantries = ['hi', 'hello', 'ok', 'bye', 'yes'] + >>> list(unique_iter(pleasantries, key=lambda x: len(x))) + ['hi', 'hello', 'bye'] + """ + if not is_iterable(src): + raise TypeError('expected an iterable, not %r' % type(src)) + if key is None: + def key_func(x): return x + elif callable(key): + key_func = key + elif isinstance(key, str): + def key_func(x): return getattr(x, key, x) + else: + raise TypeError('"key" expected a string or callable, not %r' % key) + seen = set() + for i in src: + k = key_func(i) + if k not in seen: + seen.add(k) + yield i + return + + +def redundant(src, key=None, groups=False): + """The complement of :func:`unique()`. + + By default returns non-unique/duplicate values as a list of the + *first* redundant value in *src*. Pass ``groups=True`` to get + groups of all values with redundancies, ordered by position of the + first redundant value. This is useful in conjunction with some + normalizing *key* function. + + >>> redundant([1, 2, 3, 4]) + [] + >>> redundant([1, 2, 3, 2, 3, 3, 4]) + [2, 3] + >>> redundant([1, 2, 3, 2, 3, 3, 4], groups=True) + [[2, 2], [3, 3, 3]] + + An example using a *key* function to do case-insensitive + redundancy detection. + + >>> redundant(['hi', 'Hi', 'HI', 'hello'], key=str.lower) + ['Hi'] + >>> redundant(['hi', 'Hi', 'HI', 'hello'], groups=True, key=str.lower) + [['hi', 'Hi', 'HI']] + + *key* should also be used when the values in *src* are not hashable. + + .. note:: + + This output of this function is designed for reporting + duplicates in contexts when a unique input is desired. Due to + the grouped return type, there is no streaming equivalent of + this function for the time being. + + """ + if key is None: + pass + elif callable(key): + key_func = key + elif isinstance(key, (str, bytes)): + def key_func(x): return getattr(x, key, x) + else: + raise TypeError('"key" expected a string or callable, not %r' % key) + seen = {} # key to first seen item + redundant_order = [] + redundant_groups = {} + for i in src: + k = key_func(i) if key else i + if k not in seen: + seen[k] = i + else: + if k in redundant_groups: + if groups: + redundant_groups[k].append(i) + else: + redundant_order.append(k) + redundant_groups[k] = [seen[k], i] + if not groups: + ret = [redundant_groups[k][1] for k in redundant_order] + else: + ret = [redundant_groups[k] for k in redundant_order] + return ret + + +def one(src, default=None, key=None): + """Along the same lines as builtins, :func:`all` and :func:`any`, and + similar to :func:`first`, ``one()`` returns the single object in + the given iterable *src* that evaluates to ``True``, as determined + by callable *key*. If unset, *key* defaults to :class:`bool`. If + no such objects are found, *default* is returned. If *default* is + not passed, ``None`` is returned. + + If *src* has more than one object that evaluates to ``True``, or + if there is no object that fulfills such condition, return + *default*. It's like an `XOR`_ over an iterable. + + >>> one((True, False, False)) + True + >>> one((True, False, True)) + >>> one((0, 0, 'a')) + 'a' + >>> one((0, False, None)) + >>> one((True, True), default=False) + False + >>> bool(one(('', 1))) + True + >>> one((10, 20, 30, 42), key=lambda i: i > 40) + 42 + + See `Martín Gaitán's original repo`_ for further use cases. + + .. _Martín Gaitán's original repo: https://github.com/mgaitan/one + .. _XOR: https://en.wikipedia.org/wiki/Exclusive_or + + """ + ones = list(itertools.islice(filter(key, src), 2)) + return ones[0] if len(ones) == 1 else default + + +def first(iterable, default=None, key=None): + """Return first element of *iterable* that evaluates to ``True``, else + return ``None`` or optional *default*. Similar to :func:`one`. + + >>> first([0, False, None, [], (), 42]) + 42 + >>> first([0, False, None, [], ()]) is None + True + >>> first([0, False, None, [], ()], default='ohai') + 'ohai' + >>> import re + >>> m = first(re.match(regex, 'abc') for regex in ['b.*', 'a(.*)']) + >>> m.group(1) + 'bc' + + The optional *key* argument specifies a one-argument predicate function + like that used for *filter()*. The *key* argument, if supplied, should be + in keyword form. For example, finding the first even number in an iterable: + + >>> first([1, 1, 3, 4, 5], key=lambda x: x % 2 == 0) + 4 + + Contributed by Hynek Schlawack, author of `the original standalone module`_. + + .. _the original standalone module: https://github.com/hynek/first + """ + return next(filter(key, iterable), default) + + +def flatten_iter(iterable): + """``flatten_iter()`` yields all the elements from *iterable* while + collapsing any nested iterables. + + >>> nested = [[1, 2], [[3], [4, 5]]] + >>> list(flatten_iter(nested)) + [1, 2, 3, 4, 5] + """ + for item in iterable: + if isinstance(item, Iterable) and not isinstance(item, (str, bytes)): + yield from flatten_iter(item) + else: + yield item + + +def flatten(iterable): + """``flatten()`` returns a collapsed list of all the elements from + *iterable* while collapsing any nested iterables. + + >>> nested = [[1, 2], [[3], [4, 5]]] + >>> flatten(nested) + [1, 2, 3, 4, 5] + """ + return list(flatten_iter(iterable)) + + +def same(iterable, ref=_UNSET): + """``same()`` returns ``True`` when all values in *iterable* are + equal to one another, or optionally a reference value, + *ref*. Similar to :func:`all` and :func:`any` in that it evaluates + an iterable and returns a :class:`bool`. ``same()`` returns + ``True`` for empty iterables. + + >>> same([]) + True + >>> same([1]) + True + >>> same(['a', 'a', 'a']) + True + >>> same(range(20)) + False + >>> same([[], []]) + True + >>> same([[], []], ref='test') + False + + """ + iterator = iter(iterable) + if ref is _UNSET: + ref = next(iterator, ref) + return all(val == ref for val in iterator) + + +def default_visit(path, key, value): + # print('visit(%r, %r, %r)' % (path, key, value)) + return key, value + + +# enable the extreme: monkeypatching iterutils with a different default_visit +_orig_default_visit = default_visit + + +def default_enter(path, key, value): + # print('enter(%r, %r)' % (key, value)) + if isinstance(value, (str, bytes)): + return value, False + elif isinstance(value, Mapping): + return value.__class__(), ItemsView(value) + elif isinstance(value, Sequence): + return value.__class__(), enumerate(value) + elif isinstance(value, Set): + return value.__class__(), enumerate(value) + else: + # files, strings, other iterables, and scalars are not + # traversed + return value, False + + +def default_exit(path, key, old_parent, new_parent, new_items): + # print('exit(%r, %r, %r, %r, %r)' + # % (path, key, old_parent, new_parent, new_items)) + ret = new_parent + if isinstance(new_parent, Mapping): + new_parent.update(new_items) + elif isinstance(new_parent, Sequence): + vals = [v for i, v in new_items] + try: + new_parent.extend(vals) + except AttributeError: + ret = new_parent.__class__(vals) # tuples + elif isinstance(new_parent, Set): + vals = [v for i, v in new_items] + try: + new_parent.update(vals) + except AttributeError: + ret = new_parent.__class__(vals) # frozensets + else: + raise RuntimeError('unexpected iterable type: %r' % type(new_parent)) + return ret + + +def remap(root, visit=default_visit, enter=default_enter, exit=default_exit, + **kwargs): + """The remap ("recursive map") function is used to traverse and + transform nested structures. Lists, tuples, sets, and dictionaries + are just a few of the data structures nested into heterogeneous + tree-like structures that are so common in programming. + Unfortunately, Python's built-in ways to manipulate collections + are almost all flat. List comprehensions may be fast and succinct, + but they do not recurse, making it tedious to apply quick changes + or complex transforms to real-world data. + + remap goes where list comprehensions cannot. + + Here's an example of removing all Nones from some data: + + >>> from pprint import pprint + >>> reviews = {'Star Trek': {'TNG': 10, 'DS9': 8.5, 'ENT': None}, + ... 'Babylon 5': 6, 'Dr. Who': None} + >>> pprint(remap(reviews, lambda p, k, v: v is not None)) + {'Babylon 5': 6, 'Star Trek': {'DS9': 8.5, 'TNG': 10}} + + Notice how both Nones have been removed despite the nesting in the + dictionary. Not bad for a one-liner, and that's just the beginning. + See `this remap cookbook`_ for more delicious recipes. + + .. _this remap cookbook: http://sedimental.org/remap.html + + remap takes four main arguments: the object to traverse and three + optional callables which determine how the remapped object will be + created. + + Args: + + root: The target object to traverse. By default, remap + supports iterables like :class:`list`, :class:`tuple`, + :class:`dict`, and :class:`set`, but any object traversable by + *enter* will work. + visit (callable): This function is called on every item in + *root*. It must accept three positional arguments, *path*, + *key*, and *value*. *path* is simply a tuple of parents' + keys. *visit* should return the new key-value pair. It may + also return ``True`` as shorthand to keep the old item + unmodified, or ``False`` to drop the item from the new + structure. *visit* is called after *enter*, on the new parent. + + The *visit* function is called for every item in root, + including duplicate items. For traversable values, it is + called on the new parent object, after all its children + have been visited. The default visit behavior simply + returns the key-value pair unmodified. + enter (callable): This function controls which items in *root* + are traversed. It accepts the same arguments as *visit*: the + path, the key, and the value of the current item. It returns a + pair of the blank new parent, and an iterator over the items + which should be visited. If ``False`` is returned instead of + an iterator, the value will not be traversed. + + The *enter* function is only called once per unique value. The + default enter behavior support mappings, sequences, and + sets. Strings and all other iterables will not be traversed. + exit (callable): This function determines how to handle items + once they have been visited. It gets the same three + arguments as the other functions -- *path*, *key*, *value* + -- plus two more: the blank new parent object returned + from *enter*, and a list of the new items, as remapped by + *visit*. + + Like *enter*, the *exit* function is only called once per + unique value. The default exit behavior is to simply add + all new items to the new parent, e.g., using + :meth:`list.extend` and :meth:`dict.update` to add to the + new parent. Immutable objects, such as a :class:`tuple` or + :class:`namedtuple`, must be recreated from scratch, but + use the same type as the new parent passed back from the + *enter* function. + reraise_visit (bool): A pragmatic convenience for the *visit* + callable. When set to ``False``, remap ignores any errors + raised by the *visit* callback. Items causing exceptions + are kept. See examples for more details. + trace (bool): Pass ``trace=True`` to print out the entire + traversal. Or pass a tuple of ``'visit'``, ``'enter'``, + or ``'exit'`` to print only the selected events. + + remap is designed to cover the majority of cases with just the + *visit* callable. While passing in multiple callables is very + empowering, remap is designed so very few cases should require + passing more than one function. + + When passing *enter* and *exit*, it's common and easiest to build + on the default behavior. Simply add ``from boltons.iterutils import + default_enter`` (or ``default_exit``), and have your enter/exit + function call the default behavior before or after your custom + logic. See `this example`_. + + Duplicate and self-referential objects (aka reference loops) are + automatically handled internally, `as shown here`_. + + .. _this example: http://sedimental.org/remap.html#sort_all_lists + .. _as shown here: http://sedimental.org/remap.html#corner_cases + + """ + # TODO: improve argument formatting in sphinx doc + # TODO: enter() return (False, items) to continue traverse but cancel copy? + if not callable(visit): + raise TypeError('visit expected callable, not: %r' % visit) + if not callable(enter): + raise TypeError('enter expected callable, not: %r' % enter) + if not callable(exit): + raise TypeError('exit expected callable, not: %r' % exit) + reraise_visit = kwargs.pop('reraise_visit', True) + trace = kwargs.pop('trace', ()) + if trace is True: + trace = ('visit', 'enter', 'exit') + elif isinstance(trace, str): + trace = (trace,) + if not isinstance(trace, (tuple, list, set)): + raise TypeError('trace expected tuple of event names, not: %r' % trace) + trace_enter, trace_exit, trace_visit = 'enter' in trace, 'exit' in trace, 'visit' in trace + + if kwargs: + raise TypeError('unexpected keyword arguments: %r' % kwargs.keys()) + + path, registry, stack = (), {}, [(None, root)] + new_items_stack = [] + while stack: + key, value = stack.pop() + id_value = id(value) + if key is _REMAP_EXIT: + key, new_parent, old_parent = value + id_value = id(old_parent) + path, new_items = new_items_stack.pop() + if trace_exit: + print(' .. remap exit:', path, '-', key, '-', + old_parent, '-', new_parent, '-', new_items) + value = exit(path, key, old_parent, new_parent, new_items) + if trace_exit: + print(' .. remap exit result:', value) + registry[id_value] = value + if not new_items_stack: + continue + elif id_value in registry: + value = registry[id_value] + else: + if trace_enter: + print(' .. remap enter:', path, '-', key, '-', value) + res = enter(path, key, value) + if trace_enter: + print(' .. remap enter result:', res) + try: + new_parent, new_items = res + except TypeError: + # TODO: handle False? + raise TypeError('enter should return a tuple of (new_parent,' + ' items_iterator), not: %r' % res) + if new_items is not False: + # traverse unless False is explicitly passed + registry[id_value] = new_parent + new_items_stack.append((path, [])) + if value is not root: + path += (key,) + stack.append((_REMAP_EXIT, (key, new_parent, value))) + if new_items: + stack.extend(reversed(list(new_items))) + if trace_enter: + print(' .. remap stack size now:', len(stack)) + continue + if visit is _orig_default_visit: + # avoid function call overhead by inlining identity operation + visited_item = (key, value) + else: + try: + if trace_visit: + print(' .. remap visit:', path, '-', key, '-', value) + visited_item = visit(path, key, value) + except Exception: + if reraise_visit: + raise + visited_item = True + if visited_item is False: + if trace_visit: + print(' .. remap visit result: ') + continue # drop + elif visited_item is True: + visited_item = (key, value) + if trace_visit: + print(' .. remap visit result:', visited_item) + # TODO: typecheck? + # raise TypeError('expected (key, value) from visit(),' + # ' not: %r' % visited_item) + try: + new_items_stack[-1][1].append(visited_item) + except IndexError: + raise TypeError('expected remappable root, not: %r' % root) + return value + + +class PathAccessError(KeyError, IndexError, TypeError): + """An amalgamation of KeyError, IndexError, and TypeError, + representing what can occur when looking up a path in a nested + object. + """ + + def __init__(self, exc, seg, path): + self.exc = exc + self.seg = seg + self.path = path + + def __repr__(self): + cn = self.__class__.__name__ + return f'{cn}({self.exc!r}, {self.seg!r}, {self.path!r})' + + def __str__(self): + return ('could not access %r from path %r, got error: %r' + % (self.seg, self.path, self.exc)) + + +def get_path(root, path, default=_UNSET): + """Retrieve a value from a nested object via a tuple representing the + lookup path. + + >>> root = {'a': {'b': {'c': [[1], [2], [3]]}}} + >>> get_path(root, ('a', 'b', 'c', 2, 0)) + 3 + + The path tuple format is intentionally consistent with that of + :func:`remap`, but a single dotted string can also be passed. + + One of get_path's chief aims is improved error messaging. EAFP is + great, but the error messages are not. + + For instance, ``root['a']['b']['c'][2][1]`` gives back + ``IndexError: list index out of range`` + + What went out of range where? get_path currently raises + ``PathAccessError: could not access 2 from path ('a', 'b', 'c', 2, + 1), got error: IndexError('list index out of range',)``, a + subclass of IndexError and KeyError. + + You can also pass a default that covers the entire operation, + should the lookup fail at any level. + + Args: + root: The target nesting of dictionaries, lists, or other + objects supporting ``__getitem__``. + path (tuple): A sequence of strings and integers to be successively + looked up within *root*. A dot-separated (``a.b``) string may + also be passed. + default: The value to be returned should any + ``PathAccessError`` exceptions be raised. + """ + if isinstance(path, str): + path = path.split('.') + cur = root + try: + for seg in path: + try: + cur = cur[seg] + except (KeyError, IndexError) as exc: + raise PathAccessError(exc, seg, path) + except TypeError as exc: + # either string index in a list, or a parent that + # doesn't support indexing + try: + seg = int(seg) + cur = cur[seg] + except (ValueError, KeyError, IndexError, TypeError): + if not is_iterable(cur): + exc = TypeError('%r object is not indexable' + % type(cur).__name__) + raise PathAccessError(exc, seg, path) + except PathAccessError: + if default is _UNSET: + raise + return default + return cur + + +def research(root, query=lambda p, k, v: True, reraise=False, enter=default_enter): + """The :func:`research` function uses :func:`remap` to recurse over + any data nested in *root*, and find values which match a given + criterion, specified by the *query* callable. + + Results are returned as a list of ``(path, value)`` pairs. The + paths are tuples in the same format accepted by + :func:`get_path`. This can be useful for comparing values nested + in two or more different structures. + + Here's a simple example that finds all integers: + + >>> root = {'a': {'b': 1, 'c': (2, 'd', 3)}, 'e': None} + >>> res = research(root, query=lambda p, k, v: isinstance(v, int)) + >>> print(sorted(res)) + [(('a', 'b'), 1), (('a', 'c', 0), 2), (('a', 'c', 2), 3)] + + Note how *query* follows the same, familiar ``path, key, value`` + signature as the ``visit`` and ``enter`` functions on + :func:`remap`, and returns a :class:`bool`. + + Args: + root: The target object to search. Supports the same types of + objects as :func:`remap`, including :class:`list`, + :class:`tuple`, :class:`dict`, and :class:`set`. + query (callable): The function called on every object to + determine whether to include it in the search results. The + callable must accept three arguments, *path*, *key*, and + *value*, commonly abbreviated *p*, *k*, and *v*, same as + *enter* and *visit* from :func:`remap`. + reraise (bool): Whether to reraise exceptions raised by *query* + or to simply drop the result that caused the error. + + + With :func:`research` it's easy to inspect the details of a data + structure, like finding values that are at a certain depth (using + ``len(p)``) and much more. If more advanced functionality is + needed, check out the code and make your own :func:`remap` + wrapper, and consider `submitting a patch`_! + + .. _submitting a patch: https://github.com/mahmoud/boltons/pulls + """ + ret = [] + + if not callable(query): + raise TypeError('query expected callable, not: %r' % query) + + def _enter(path, key, value): + try: + if query(path, key, value): + ret.append((path + (key,), value)) + except Exception: + if reraise: + raise + return enter(path, key, value) + + remap(root, enter=_enter) + return ret + + +# TODO: recollect() +# TODO: refilter() +# TODO: reiter() + + +# GUID iterators: 10x faster and somewhat more compact than uuid. + +class GUIDerator: + """The GUIDerator is an iterator that yields a globally-unique + identifier (GUID) on every iteration. The GUIDs produced are + hexadecimal strings. + + Testing shows it to be around 12x faster than the uuid module. By + default it is also more compact, partly due to its default 96-bit + (24-hexdigit) length. 96 bits of randomness means that there is a + 1 in 2 ^ 32 chance of collision after 2 ^ 64 iterations. If more + or less uniqueness is desired, the *size* argument can be adjusted + accordingly. + + Args: + size (int): character length of the GUID, defaults to 24. Lengths + between 20 and 36 are considered valid. + + The GUIDerator has built-in fork protection that causes it to + detect a fork on next iteration and reseed accordingly. + + """ + + def __init__(self, size=24): + self.size = size + if size < 20 or size > 36: + raise ValueError('expected 20 < size <= 36') + import hashlib + self._sha1 = hashlib.sha1 + self.count = itertools.count() + self.reseed() + + def reseed(self): + import socket + self.pid = os.getpid() + self.salt = '-'.join([str(self.pid), + socket.gethostname() or '', + str(time.time()), + os.urandom(6).hex()]) + return + + def __iter__(self): + return self + + def __next__(self): + if os.getpid() != self.pid: + self.reseed() + target_bytes = (self.salt + str(next(self.count))).encode('utf8') + hash_text = self._sha1(target_bytes).hexdigest()[:self.size] + return hash_text + + next = __next__ + + +class SequentialGUIDerator(GUIDerator): + """Much like the standard GUIDerator, the SequentialGUIDerator is an + iterator that yields a globally-unique identifier (GUID) on every + iteration. The GUIDs produced are hexadecimal strings. + + The SequentialGUIDerator differs in that it picks a starting GUID + value and increments every iteration. This yields GUIDs which are + of course unique, but also ordered and lexicographically sortable. + + The SequentialGUIDerator is around 50% faster than the normal + GUIDerator, making it almost 20x as fast as the built-in uuid + module. By default it is also more compact, partly due to its + 96-bit (24-hexdigit) default length. 96 bits of randomness means that + there is a 1 in 2 ^ 32 chance of collision after 2 ^ 64 + iterations. If more or less uniqueness is desired, the *size* + argument can be adjusted accordingly. + + Args: + size (int): character length of the GUID, defaults to 24. + + Note that with SequentialGUIDerator there is a chance of GUIDs + growing larger than the size configured. The SequentialGUIDerator + has built-in fork protection that causes it to detect a fork on + next iteration and reseed accordingly. + + """ + + def reseed(self): + super().reseed() + start_str = self._sha1(self.salt.encode('utf8')).hexdigest() + self.start = int(start_str[:self.size], 16) + self.start |= (1 << ((self.size * 4) - 2)) + + def __next__(self): + if os.getpid() != self.pid: + self.reseed() + return '%x' % (next(self.count) + self.start) + + next = __next__ + + +guid_iter = GUIDerator() +seq_guid_iter = SequentialGUIDerator() + + +def soft_sorted(iterable, first=None, last=None, key=None, reverse=False): + """For when you care about the order of some elements, but not about + others. + + Use this to float to the top and/or sink to the bottom a specific + ordering, while sorting the rest of the elements according to + normal :func:`sorted` rules. + + >>> soft_sorted(['two', 'b', 'one', 'a'], first=['one', 'two']) + ['one', 'two', 'a', 'b'] + >>> soft_sorted(range(7), first=[6, 15], last=[2, 4], reverse=True) + [6, 5, 3, 1, 0, 2, 4] + >>> import string + >>> ''.join(soft_sorted(string.hexdigits, first='za1', last='b', key=str.lower)) + 'aA1023456789cCdDeEfFbB' + + Args: + iterable (list): A list or other iterable to sort. + first (list): A sequence to enforce for elements which should + appear at the beginning of the returned list. + last (list): A sequence to enforce for elements which should + appear at the end of the returned list. + key (callable): Callable used to generate a comparable key for + each item to be sorted, same as the key in + :func:`sorted`. Note that entries in *first* and *last* + should be the keys for the items. Defaults to + passthrough/the identity function. + reverse (bool): Whether or not elements not explicitly ordered + by *first* and *last* should be in reverse order or not. + + Returns a new list in sorted order. + """ + first = first or [] + last = last or [] + key = key or (lambda x: x) + seq = list(iterable) + other = [x for x in seq if not ( + (first and key(x) in first) or (last and key(x) in last))] + other.sort(key=key, reverse=reverse) + + if first: + first = sorted([x for x in seq if key(x) in first], + key=lambda x: first.index(key(x))) + if last: + last = sorted([x for x in seq if key(x) in last], + key=lambda x: last.index(key(x))) + return first + other + last + + +def untyped_sorted(iterable, key=None, reverse=False): + """A version of :func:`sorted` which will happily sort an iterable of + heterogeneous types and return a new list, similar to legacy Python's + behavior. + + >>> untyped_sorted(['abc', 2.0, 1, 2, 'def']) + [1, 2.0, 2, 'abc', 'def'] + + Note how mutually orderable types are sorted as expected, as in + the case of the integers and floats above. + + .. note:: + + Results may vary across Python versions and builds, but the + function will produce a sorted list, except in the case of + explicitly unorderable objects. + + """ + class _Wrapper: + slots = ('obj',) + + def __init__(self, obj): + self.obj = obj + + def __lt__(self, other): + obj = key(self.obj) if key is not None else self.obj + other = key(other.obj) if key is not None else other.obj + try: + ret = obj < other + except TypeError: + ret = ((type(obj).__name__, id(type(obj)), obj) + < (type(other).__name__, id(type(other)), other)) + return ret + + if key is not None and not callable(key): + raise TypeError('expected function or callable object for key, not: %r' + % key) + + return sorted(iterable, key=_Wrapper, reverse=reverse) + + +""" +May actually be faster to do an isinstance check for a str path + +$ python -m timeit -s "x = [1]" "x[0]" +10000000 loops, best of 3: 0.0207 usec per loop +$ python -m timeit -s "x = [1]" "try: x[0] \nexcept: pass" +10000000 loops, best of 3: 0.029 usec per loop +$ python -m timeit -s "x = [1]" "try: x[1] \nexcept: pass" +1000000 loops, best of 3: 0.315 usec per loop +# setting up try/except is fast, only around 0.01us +# actually triggering the exception takes almost 10x as long + +$ python -m timeit -s "x = [1]" "isinstance(x, basestring)" +10000000 loops, best of 3: 0.141 usec per loop +$ python -m timeit -s "x = [1]" "isinstance(x, str)" +10000000 loops, best of 3: 0.131 usec per loop +$ python -m timeit -s "x = [1]" "try: x.split('.')\n except: pass" +1000000 loops, best of 3: 0.443 usec per loop +$ python -m timeit -s "x = [1]" "try: x.split('.') \nexcept AttributeError: pass" +1000000 loops, best of 3: 0.544 usec per loop +""" diff --git a/data/miniconda3/lib/python3.13/site-packages/boltons/jsonutils.py b/data/miniconda3/lib/python3.13/site-packages/boltons/jsonutils.py new file mode 100644 index 0000000000000000000000000000000000000000..bf61b03a3b1d43e534f268f6dec577781c53eab3 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/boltons/jsonutils.py @@ -0,0 +1,267 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# * The names of the contributors may not be used to endorse or +# promote products derived from this software without specific +# prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""``jsonutils`` aims to provide various helpers for working with +JSON. Currently it focuses on providing a reliable and intuitive means +of working with `JSON Lines`_-formatted files. + +.. _JSON Lines: http://jsonlines.org/ + +""" + + +import io +import os +import json + + +DEFAULT_BLOCKSIZE = 4096 + + +__all__ = ['JSONLIterator', 'reverse_iter_lines'] + + +def reverse_iter_lines(file_obj, blocksize=DEFAULT_BLOCKSIZE, preseek=True, encoding=None): + """Returns an iterator over the lines from a file object, in + reverse order, i.e., last line first, first line last. Uses the + :meth:`file.seek` method of file objects, and is tested compatible with + :class:`file` objects, as well as :class:`StringIO.StringIO`. + + Args: + file_obj (file): An open file object. Note that + ``reverse_iter_lines`` mutably reads from the file and + other functions should not mutably interact with the file + object after being passed. Files can be opened in bytes or + text mode. + blocksize (int): The block size to pass to + :meth:`file.read()`. Warning: keep this a fairly large + multiple of 2, defaults to 4096. + preseek (bool): Tells the function whether or not to automatically + seek to the end of the file. Defaults to ``True``. + ``preseek=False`` is useful in cases when the + file cursor is already in position, either at the end of + the file or in the middle for relative reverse line + generation. + + """ + # This function is a bit of a pain because it attempts to be byte/text agnostic + try: + encoding = encoding or file_obj.encoding + except AttributeError: + # BytesIO + encoding = None + else: + encoding = 'utf-8' + + # need orig_obj to keep alive otherwise __del__ on the TextWrapper will close the file + orig_obj = file_obj + try: + file_obj = orig_obj.detach() + except (AttributeError, io.UnsupportedOperation): + pass + + empty_bytes, newline_bytes, empty_text = b'', b'\n', '' + + if preseek: + file_obj.seek(0, os.SEEK_END) + buff = empty_bytes + cur_pos = file_obj.tell() + while 0 < cur_pos: + read_size = min(blocksize, cur_pos) + cur_pos -= read_size + file_obj.seek(cur_pos, os.SEEK_SET) + cur = file_obj.read(read_size) + buff = cur + buff + lines = buff.splitlines() + + if len(lines) < 2 or lines[0] == empty_bytes: + continue + if buff[-1:] == newline_bytes: + yield empty_text if encoding else empty_bytes + for line in lines[:0:-1]: + yield line.decode(encoding) if encoding else line + buff = lines[0] + if buff: + yield buff.decode(encoding) if encoding else buff + + + +""" +TODO: allow passthroughs for: + +json.load(fp[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]]) +""" + + +class JSONLIterator: + """The ``JSONLIterator`` is used to iterate over JSON-encoded objects + stored in the `JSON Lines format`_ (one object per line). + + Most notably it has the ability to efficiently read from the + bottom of files, making it very effective for reading in simple + append-only JSONL use cases. It also has the ability to start from + anywhere in the file and ignore corrupted lines. + + Args: + file_obj (file): An open file object. + ignore_errors (bool): Whether to skip over lines that raise an error on + deserialization (:func:`json.loads`). + reverse (bool): Controls the direction of the iteration. + Defaults to ``False``. If set to ``True`` and *rel_seek* + is unset, seeks to the end of the file before iteration + begins. + rel_seek (float): Used to preseek the start position of + iteration. Set to 0.0 for the start of the file, 1.0 for the + end, and anything in between. + + .. _JSON Lines format: http://jsonlines.org/ + """ + def __init__(self, file_obj, + ignore_errors=False, reverse=False, rel_seek=None): + self._reverse = bool(reverse) + self._file_obj = file_obj + self.ignore_errors = ignore_errors + + if rel_seek is None: + if reverse: + rel_seek = 1.0 + elif not -1.0 < rel_seek < 1.0: + raise ValueError("'rel_seek' expected a float between" + " -1.0 and 1.0, not %r" % rel_seek) + elif rel_seek < 0: + rel_seek = 1.0 - rel_seek + self._rel_seek = rel_seek + self._blocksize = 4096 + if rel_seek is not None: + self._init_rel_seek() + if self._reverse: + self._line_iter = reverse_iter_lines(self._file_obj, + blocksize=self._blocksize, + preseek=False) + else: + self._line_iter = iter(self._file_obj) + + @property + def cur_byte_pos(self): + "A property representing where in the file the iterator is reading." + return self._file_obj.tell() + + def _align_to_newline(self): + "Aligns the file object's position to the next newline." + fo, bsize = self._file_obj, self._blocksize + cur, total_read = '', 0 + cur_pos = fo.tell() + while '\n' not in cur: + cur = fo.read(bsize) + total_read += bsize + try: + newline_offset = cur.index('\n') + total_read - bsize + except ValueError: + raise # TODO: seek to end? + fo.seek(cur_pos + newline_offset) + + def _init_rel_seek(self): + "Sets the file object's position to the relative location set above." + rs, fo = self._rel_seek, self._file_obj + if rs == 0.0: + fo.seek(0, os.SEEK_SET) + else: + fo.seek(0, os.SEEK_END) + size = fo.tell() + if rs == 1.0: + self._cur_pos = size + else: + target = int(size * rs) + fo.seek(target, os.SEEK_SET) + self._align_to_newline() + self._cur_pos = fo.tell() + + def __iter__(self): + return self + + def next(self): + """Yields one :class:`dict` loaded with :func:`json.loads`, advancing + the file object by one line. Raises :exc:`StopIteration` upon reaching + the end of the file (or beginning, if ``reverse`` was set to ``True``. + """ + while 1: + line = next(self._line_iter).lstrip() + if not line: + continue + try: + obj = json.loads(line) + except Exception: + if not self.ignore_errors: + raise + continue + return obj + + __next__ = next + + +if __name__ == '__main__': + def _main(): + import sys + if '-h' in sys.argv or '--help' in sys.argv: + print('loads one or more JSON Line files for basic validation.') + return + verbose = False + if '-v' in sys.argv or '--verbose' in sys.argv: + verbose = True + file_count, obj_count = 0, 0 + filenames = sys.argv[1:] + for filename in filenames: + if filename in ('-h', '--help', '-v', '--verbose'): + continue + file_count += 1 + with open(filename, 'rb') as file_obj: + iterator = JSONLIterator(file_obj) + cur_obj_count = 0 + while 1: + try: + next(iterator) + except ValueError: + print('error reading object #%s around byte %s in %s' + % (cur_obj_count + 1, iterator.cur_byte_pos, filename)) + return + except StopIteration: + break + obj_count += 1 + cur_obj_count += 1 + if verbose and obj_count and obj_count % 100 == 0: + sys.stdout.write('.') + if obj_count % 10000: + sys.stdout.write('%s\n' % obj_count) + if verbose: + print('files checked: %s' % file_count) + print('objects loaded: %s' % obj_count) + return + + _main() diff --git a/data/miniconda3/lib/python3.13/site-packages/boltons/listutils.py b/data/miniconda3/lib/python3.13/site-packages/boltons/listutils.py new file mode 100644 index 0000000000000000000000000000000000000000..06b9da28f74488d45b98a8f949d7e34cfd930160 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/boltons/listutils.py @@ -0,0 +1,350 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# * The names of the contributors may not be used to endorse or +# promote products derived from this software without specific +# prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Python's builtin :class:`list` is a very fast and efficient +sequence type, but it could be better for certain access patterns, +such as non-sequential insertion into a large lists. ``listutils`` +provides a pure-Python solution to this problem. + +For utilities for working with iterables and lists, check out +:mod:`iterutils`. For the a :class:`list`-based version of +:class:`collections.namedtuple`, check out :mod:`namedutils`. +""" + + +import operator +from math import log as math_log +from itertools import chain, islice + +try: + from .typeutils import make_sentinel + _MISSING = make_sentinel(var_name='_MISSING') +except ImportError: + _MISSING = object() + +# TODO: expose splaylist? +__all__ = ['BList', 'BarrelList'] + + +# TODO: comparators +# TODO: keep track of list lengths and bisect to the right list for +# faster getitem (and slightly slower setitem and delitem ops) + +class BarrelList(list): + """The ``BarrelList`` is a :class:`list` subtype backed by many + dynamically-scaled sublists, to provide better scaling and random + insertion/deletion characteristics. It is a subtype of the builtin + :class:`list` and has an identical API, supporting indexing, + slicing, sorting, etc. If application requirements call for + something more performant, consider the `blist module available on + PyPI`_. + + The name comes by way of Kurt Rose, who said it reminded him of + barrel shifters. Not sure how, but it's BList-like, so the name + stuck. BList is of course a reference to `B-trees`_. + + Args: + iterable: An optional iterable of initial values for the list. + + >>> blist = BList(range(100000)) + >>> blist.pop(50000) + 50000 + >>> len(blist) + 99999 + >>> len(blist.lists) # how many underlying lists + 8 + >>> slice_idx = blist.lists[0][-1] + >>> blist[slice_idx:slice_idx + 2] + BarrelList([11637, 11638]) + + Slicing is supported and works just fine across list borders, + returning another instance of the BarrelList. + + .. _blist module available on PyPI: https://pypi.python.org/pypi/blist + .. _B-trees: https://en.wikipedia.org/wiki/B-tree + + """ + + _size_factor = 1520 + "This size factor is the result of tuning using the tune() function below." + + def __init__(self, iterable=None): + self.lists = [[]] + if iterable: + self.extend(iterable) + + @property + def _cur_size_limit(self): + len_self, size_factor = len(self), self._size_factor + return int(round(size_factor * math_log(len_self + 2, 2))) + + def _translate_index(self, index): + if index < 0: + index += len(self) + rel_idx, lists = index, self.lists + for list_idx in range(len(lists)): + len_list = len(lists[list_idx]) + if rel_idx < len_list: + break + rel_idx -= len_list + if rel_idx < 0: + return None, None + return list_idx, rel_idx + + def _balance_list(self, list_idx): + if list_idx < 0: + list_idx += len(self.lists) + cur_list, len_self = self.lists[list_idx], len(self) + size_limit = self._cur_size_limit + if len(cur_list) > size_limit: + half_limit = size_limit // 2 + while len(cur_list) > half_limit: + next_list_idx = list_idx + 1 + self.lists.insert(next_list_idx, cur_list[-half_limit:]) + del cur_list[-half_limit:] + return True + return False + + def insert(self, index, item): + if len(self.lists) == 1: + self.lists[0].insert(index, item) + self._balance_list(0) + else: + list_idx, rel_idx = self._translate_index(index) + if list_idx is None: + raise IndexError() + self.lists[list_idx].insert(rel_idx, item) + self._balance_list(list_idx) + return + + def append(self, item): + self.lists[-1].append(item) + + def extend(self, iterable): + self.lists[-1].extend(iterable) + + def pop(self, *a): + lists = self.lists + if len(lists) == 1 and not a: + return self.lists[0].pop() + index = a and a[0] + if index == () or index is None or index == -1: + ret = lists[-1].pop() + if len(lists) > 1 and not lists[-1]: + lists.pop() + else: + list_idx, rel_idx = self._translate_index(index) + if list_idx is None: + raise IndexError() + ret = lists[list_idx].pop(rel_idx) + self._balance_list(list_idx) + return ret + + def iter_slice(self, start, stop, step=None): + iterable = self # TODO: optimization opportunities abound + # start_list_idx, stop_list_idx = 0, len(self.lists) + if start is None: + start = 0 + if stop is None: + stop = len(self) + if step is not None and step < 0: + step = -step + start, stop = -start, -stop - 1 + iterable = reversed(self) + if start < 0: + start += len(self) + # start_list_idx, start_rel_idx = self._translate_index(start) + if stop < 0: + stop += len(self) + # stop_list_idx, stop_rel_idx = self._translate_index(stop) + return islice(iterable, start, stop, step) + + def del_slice(self, start, stop, step=None): + if step is not None and abs(step) > 1: # punt + new_list = chain(self.iter_slice(0, start, step), + self.iter_slice(stop, None, step)) + self.lists[0][:] = new_list + self._balance_list(0) + return + if start is None: + start = 0 + if stop is None: + stop = len(self) + start_list_idx, start_rel_idx = self._translate_index(start) + stop_list_idx, stop_rel_idx = self._translate_index(stop) + if start_list_idx is None: + raise IndexError() + if stop_list_idx is None: + raise IndexError() + + if start_list_idx == stop_list_idx: + del self.lists[start_list_idx][start_rel_idx:stop_rel_idx] + elif start_list_idx < stop_list_idx: + del self.lists[start_list_idx + 1:stop_list_idx] + del self.lists[start_list_idx][start_rel_idx:] + del self.lists[stop_list_idx][:stop_rel_idx] + else: + assert False, ('start list index should never translate to' + ' greater than stop list index') + + __delslice__ = del_slice + + @classmethod + def from_iterable(cls, it): + return cls(it) + + def __iter__(self): + return chain.from_iterable(self.lists) + + def __reversed__(self): + return chain.from_iterable(reversed(l) for l in reversed(self.lists)) + + def __len__(self): + return sum([len(l) for l in self.lists]) + + def __contains__(self, item): + for cur in self.lists: + if item in cur: + return True + return False + + def __getitem__(self, index): + try: + start, stop, step = index.start, index.stop, index.step + except AttributeError: + index = operator.index(index) + else: + iter_slice = self.iter_slice(start, stop, step) + ret = self.from_iterable(iter_slice) + return ret + list_idx, rel_idx = self._translate_index(index) + if list_idx is None: + raise IndexError() + return self.lists[list_idx][rel_idx] + + def __delitem__(self, index): + try: + start, stop, step = index.start, index.stop, index.step + except AttributeError: + index = operator.index(index) + else: + self.del_slice(start, stop, step) + return + list_idx, rel_idx = self._translate_index(index) + if list_idx is None: + raise IndexError() + del self.lists[list_idx][rel_idx] + + def __setitem__(self, index, item): + try: + start, stop, step = index.start, index.stop, index.step + except AttributeError: + index = operator.index(index) + else: + if len(self.lists) == 1: + self.lists[0][index] = item + else: + tmp = list(self) + tmp[index] = item + self.lists[:] = [tmp] + self._balance_list(0) + return + list_idx, rel_idx = self._translate_index(index) + if list_idx is None: + raise IndexError() + self.lists[list_idx][rel_idx] = item + + def __getslice__(self, start, stop): + iter_slice = self.iter_slice(start, stop, 1) + return self.from_iterable(iter_slice) + + def __setslice__(self, start, stop, sequence): + if len(self.lists) == 1: + self.lists[0][start:stop] = sequence + else: + tmp = list(self) + tmp[start:stop] = sequence + self.lists[:] = [tmp] + self._balance_list(0) + return + + def __repr__(self): + return f'{self.__class__.__name__}({list(self)!r})' + + def sort(self): + # poor pythonist's mergesort, it's faster than sorted(self) + # when the lists' average length is greater than 512. + if len(self.lists) == 1: + self.lists[0].sort() + else: + for li in self.lists: + li.sort() + tmp_sorted = sorted(chain.from_iterable(self.lists)) + del self.lists[:] + self.lists[0] = tmp_sorted + self._balance_list(0) + + def reverse(self): + for cur in self.lists: + cur.reverse() + self.lists.reverse() + + def count(self, item): + return sum([cur.count(item) for cur in self.lists]) + + def index(self, item): + len_accum = 0 + for cur in self.lists: + try: + rel_idx = cur.index(item) + return len_accum + rel_idx + except ValueError: + len_accum += len(cur) + raise ValueError(f'{item!r} is not in list') + + +BList = BarrelList + + +class SplayList(list): + """Like a `splay tree`_, the SplayList facilitates moving higher + utility items closer to the front of the list for faster access. + + .. _splay tree: https://en.wikipedia.org/wiki/Splay_tree + """ + + def shift(self, item_index, dest_index=0): + if item_index == dest_index: + return + item = self.pop(item_index) + self.insert(dest_index, item) + + def swap(self, item_index, dest_index): + self[dest_index], self[item_index] = self[item_index], self[dest_index] diff --git a/data/miniconda3/lib/python3.13/site-packages/boltons/mathutils.py b/data/miniconda3/lib/python3.13/site-packages/boltons/mathutils.py new file mode 100644 index 0000000000000000000000000000000000000000..1367a5413bbb9c6f3754da50c33b073641ac40df --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/boltons/mathutils.py @@ -0,0 +1,249 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# * The names of the contributors may not be used to endorse or +# promote products derived from this software without specific +# prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""This module provides useful math functions on top of Python's +built-in :mod:`math` module. +""" + +from math import ceil as _ceil, floor as _floor +import bisect +import binascii + + +def clamp(x, lower=float('-inf'), upper=float('inf')): + """Limit a value to a given range. + + Args: + x (int or float): Number to be clamped. + lower (int or float): Minimum value for x. + upper (int or float): Maximum value for x. + + The returned value is guaranteed to be between *lower* and + *upper*. Integers, floats, and other comparable types can be + mixed. + + >>> clamp(1.0, 0, 5) + 1.0 + >>> clamp(-1.0, 0, 5) + 0 + >>> clamp(101.0, 0, 5) + 5 + >>> clamp(123, upper=5) + 5 + + Similar to `numpy's clip`_ function. + + .. _numpy's clip: http://docs.scipy.org/doc/numpy/reference/generated/numpy.clip.html + + """ + if upper < lower: + raise ValueError('expected upper bound (%r) >= lower bound (%r)' + % (upper, lower)) + return min(max(x, lower), upper) + + +def ceil(x, options=None): + """Return the ceiling of *x*. If *options* is set, return the smallest + integer or float from *options* that is greater than or equal to + *x*. + + Args: + x (int or float): Number to be tested. + options (iterable): Optional iterable of arbitrary numbers + (ints or floats). + + >>> VALID_CABLE_CSA = [1.5, 2.5, 4, 6, 10, 25, 35, 50] + >>> ceil(3.5, options=VALID_CABLE_CSA) + 4 + >>> ceil(4, options=VALID_CABLE_CSA) + 4 + """ + if options is None: + return _ceil(x) + options = sorted(options) + i = bisect.bisect_left(options, x) + if i == len(options): + raise ValueError("no ceil options greater than or equal to: %r" % x) + return options[i] + + +def floor(x, options=None): + """Return the floor of *x*. If *options* is set, return the largest + integer or float from *options* that is less than or equal to + *x*. + + Args: + x (int or float): Number to be tested. + options (iterable): Optional iterable of arbitrary numbers + (ints or floats). + + >>> VALID_CABLE_CSA = [1.5, 2.5, 4, 6, 10, 25, 35, 50] + >>> floor(3.5, options=VALID_CABLE_CSA) + 2.5 + >>> floor(2.5, options=VALID_CABLE_CSA) + 2.5 + + """ + if options is None: + return _floor(x) + options = sorted(options) + + i = bisect.bisect_right(options, x) + if not i: + raise ValueError("no floor options less than or equal to: %r" % x) + return options[i - 1] + + +class Bits: + ''' + An immutable bit-string or bit-array object. + Provides list-like access to bits as bools, + as well as bitwise masking and shifting operators. + Bits also make it easy to convert between many + different useful representations: + + * bytes -- good for serializing raw binary data + * int -- good for incrementing (e.g. to try all possible values) + * list of bools -- good for iterating over or treating as flags + * hex/bin string -- good for human readability + + ''' + __slots__ = ('val', 'len') + + def __init__(self, val=0, len_=None): + if type(val) is not int: + if type(val) is list: + val = ''.join(['1' if e else '0' for e in val]) + if type(val) is bytes: + val = val.decode('ascii') + if type(val) is str: + if len_ is None: + len_ = len(val) + if val.startswith('0x'): + len_ = (len_ - 2) * 4 + if val.startswith('0x'): + val = int(val, 16) + else: + if val: + val = int(val, 2) + else: + val = 0 + if type(val) is not int: + raise TypeError(f'initialized with bad type: {type(val).__name__}') + if val < 0: + raise ValueError('Bits cannot represent negative values') + if len_ is None: + len_ = len(f'{val:b}') + if val > 2 ** len_: + raise ValueError(f'value {val} cannot be represented with {len_} bits') + self.val = val # data is stored internally as integer + self.len = len_ + + def __getitem__(self, k): + if type(k) is slice: + return Bits(self.as_bin()[k]) + if type(k) is int: + if k >= self.len: + raise IndexError(k) + return bool((1 << (self.len - k - 1)) & self.val) + raise TypeError(type(k)) + + def __len__(self): + return self.len + + def __eq__(self, other): + if type(self) is not type(other): + return NotImplemented + return self.val == other.val and self.len == other.len + + def __or__(self, other): + if type(self) is not type(other): + return NotImplemented + return Bits(self.val | other.val, max(self.len, other.len)) + + def __and__(self, other): + if type(self) is not type(other): + return NotImplemented + return Bits(self.val & other.val, max(self.len, other.len)) + + def __lshift__(self, other): + return Bits(self.val << other, self.len + other) + + def __rshift__(self, other): + return Bits(self.val >> other, self.len - other) + + def __hash__(self): + return hash(self.val) + + def as_list(self): + return [c == '1' for c in self.as_bin()] + + def as_bin(self): + return f'{{0:0{self.len}b}}'.format(self.val) + + def as_hex(self): + # make template to pad out to number of bytes necessary to represent bits + tmpl = f'%0{2 * (self.len // 8 + ((self.len % 8) != 0))}X' + ret = tmpl % self.val + return ret + + def as_int(self): + return self.val + + def as_bytes(self): + return binascii.unhexlify(self.as_hex()) + + @classmethod + def from_list(cls, list_): + return cls(list_) + + @classmethod + def from_bin(cls, bin): + return cls(bin) + + @classmethod + def from_hex(cls, hex): + if isinstance(hex, bytes): + hex = hex.decode('ascii') + if not hex.startswith('0x'): + hex = '0x' + hex + return cls(hex) + + @classmethod + def from_int(cls, int_, len_=None): + return cls(int_, len_) + + @classmethod + def from_bytes(cls, bytes_): + return cls.from_hex(binascii.hexlify(bytes_)) + + def __repr__(self): + cn = self.__class__.__name__ + return f"{cn}('{self.as_bin()}')" diff --git a/data/miniconda3/lib/python3.13/site-packages/boltons/mboxutils.py b/data/miniconda3/lib/python3.13/site-packages/boltons/mboxutils.py new file mode 100644 index 0000000000000000000000000000000000000000..299d105955a2f303190f2e52b75d8e81b590852c --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/boltons/mboxutils.py @@ -0,0 +1,150 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# * The names of the contributors may not be used to endorse or +# promote products derived from this software without specific +# prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Useful utilities for working with the `mbox`_-formatted +mailboxes. Credit to Mark Williams for these. + +.. _mbox: https://en.wikipedia.org/wiki/Mbox +""" + +import mailbox +import tempfile + + +DEFAULT_MAXMEM = 4 * 1024 * 1024 # 4MB + + +class mbox_readonlydir(mailbox.mbox): + """A subclass of :class:`mailbox.mbox` suitable for use with mboxs + insides a read-only mail directory, e.g., ``/var/mail``. Otherwise + the API is exactly the same as the built-in mbox. + + Deletes messages via truncation, in the manner of `Heirloom mailx`_. + + Args: + path (str): Path to the mbox file. + factory (type): Message type (defaults to :class:`rfc822.Message`) + create (bool): Create mailbox if it does not exist. (defaults + to ``True``) + maxmem (int): Specifies, in bytes, the largest sized mailbox + to attempt to copy into memory. Larger mailboxes + will be copied incrementally which is more + hazardous. (defaults to 4MB) + + .. note:: + + Because this truncates and rewrites parts of the mbox file, + this class can corrupt your mailbox. Only use this if you know + the built-in :class:`mailbox.mbox` does not work for your use + case. + + .. _Heirloom mailx: http://heirloom.sourceforge.net/mailx.html + """ + def __init__(self, path, factory=None, create=True, maxmem=1024 * 1024): + mailbox.mbox.__init__(self, path, factory, create) + self.maxmem = maxmem + + def flush(self): + """Write any pending changes to disk. This is called on mailbox + close and is usually not called explicitly. + + .. note:: + + This deletes messages via truncation. Interruptions may + corrupt your mailbox. + """ + + # Appending and basic assertions are the same as in mailbox.mbox.flush. + if not self._pending: + if self._pending_sync: + # Messages have only been added, so syncing the file + # is enough. + mailbox._sync_flush(self._file) + self._pending_sync = False + return + + # In order to be writing anything out at all, self._toc must + # already have been generated (and presumably has been modified + # by adding or deleting an item). + assert self._toc is not None + + # Check length of self._file; if it's changed, some other process + # has modified the mailbox since we scanned it. + self._file.seek(0, 2) + cur_len = self._file.tell() + if cur_len != self._file_length: + raise mailbox.ExternalClashError('Size of mailbox file changed ' + '(expected %i, found %i)' % + (self._file_length, cur_len)) + + self._file.seek(0) + + # Truncation logic begins here. Mostly the same except we + # can use tempfile because we're not doing rename(2). + with tempfile.TemporaryFile() as new_file: + new_toc = {} + self._pre_mailbox_hook(new_file) + for key in sorted(self._toc.keys()): + start, stop = self._toc[key] + self._file.seek(start) + self._pre_message_hook(new_file) + new_start = new_file.tell() + while True: + buffer = self._file.read(min(4096, + stop - self._file.tell())) + if buffer == '': + break + new_file.write(buffer) + new_toc[key] = (new_start, new_file.tell()) + self._post_message_hook(new_file) + self._file_length = new_file.tell() + + self._file.seek(0) + new_file.seek(0) + + # Copy back our messages + if self._file_length <= self.maxmem: + self._file.write(new_file.read()) + else: + while True: + buffer = new_file.read(4096) + if not buffer: + break + self._file.write(buffer) + + # Delete the rest. + self._file.truncate() + + # Same wrap up. + self._toc = new_toc + self._pending = False + self._pending_sync = False + if self._locked: + mailbox._lock_file(self._file, dotlock=False) diff --git a/data/miniconda3/lib/python3.13/site-packages/boltons/namedutils.py b/data/miniconda3/lib/python3.13/site-packages/boltons/namedutils.py new file mode 100644 index 0000000000000000000000000000000000000000..0311f81468b69822335e0c3299c431a28d17aa9e --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/boltons/namedutils.py @@ -0,0 +1,385 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# * The names of the contributors may not be used to endorse or +# promote products derived from this software without specific +# prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""\ +The ``namedutils`` module defines two lightweight container types: +:class:`namedtuple` and :class:`namedlist`. Both are subtypes of built-in +sequence types, which are very fast and efficient. They simply add +named attribute accessors for specific indexes within themselves. + +The :class:`namedtuple` is identical to the built-in +:class:`collections.namedtuple`, with a couple of enhancements, +including a ``__repr__`` more suitable to inheritance. + +The :class:`namedlist` is the mutable counterpart to the +:class:`namedtuple`, and is much faster and lighter-weight than +full-blown :class:`object`. Consider this if you're implementing nodes +in a tree, graph, or other mutable data structure. If you want an even +skinnier approach, you'll probably have to look to C. +""" + + +import sys as _sys +from collections import OrderedDict +from keyword import iskeyword as _iskeyword +from operator import itemgetter as _itemgetter + + +__all__ = ['namedlist', 'namedtuple'] + +# Tiny templates + +_repr_tmpl = '{name}=%r' + +_imm_field_tmpl = '''\ + {name} = _property(_itemgetter({index:d}), doc='Alias for field {index:d}') +''' + +_m_field_tmpl = '''\ + {name} = _property(_itemgetter({index:d}), _itemsetter({index:d}), doc='Alias for field {index:d}') +''' + +################################################################# +### namedtuple +################################################################# + +_namedtuple_tmpl = '''\ +class {typename}(tuple): + '{typename}({arg_list})' + + __slots__ = () + + _fields = {field_names!r} + + def __new__(_cls, {arg_list}): # TODO: tweak sig to make more extensible + 'Create new instance of {typename}({arg_list})' + return _tuple.__new__(_cls, ({arg_list})) + + @classmethod + def _make(cls, iterable, new=_tuple.__new__, len=len): + 'Make a new {typename} object from a sequence or iterable' + result = new(cls, iterable) + if len(result) != {num_fields:d}: + raise TypeError('Expected {num_fields:d}' + ' arguments, got %d' % len(result)) + return result + + def __repr__(self): + 'Return a nicely formatted representation string' + tmpl = self.__class__.__name__ + '({repr_fmt})' + return tmpl % self + + def _asdict(self): + 'Return a new OrderedDict which maps field names to their values' + return OrderedDict(zip(self._fields, self)) + + def _replace(_self, **kwds): + 'Return a new {typename} object replacing field(s) with new values' + result = _self._make(map(kwds.pop, {field_names!r}, _self)) + if kwds: + raise ValueError('Got unexpected field names: %r' % kwds.keys()) + return result + + def __getnewargs__(self): + 'Return self as a plain tuple. Used by copy and pickle.' + return tuple(self) + + __dict__ = _property(_asdict) + + def __getstate__(self): + 'Exclude the OrderedDict from pickling' # wat + pass + +{field_defs} +''' + +def namedtuple(typename, field_names, verbose=False, rename=False): + """Returns a new subclass of tuple with named fields. + + >>> Point = namedtuple('Point', ['x', 'y']) + >>> Point.__doc__ # docstring for the new class + 'Point(x, y)' + >>> p = Point(11, y=22) # instantiate with pos args or keywords + >>> p[0] + p[1] # indexable like a plain tuple + 33 + >>> x, y = p # unpack like a regular tuple + >>> x, y + (11, 22) + >>> p.x + p.y # fields also accessible by name + 33 + >>> d = p._asdict() # convert to a dictionary + >>> d['x'] + 11 + >>> Point(**d) # convert from a dictionary + Point(x=11, y=22) + >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields + Point(x=100, y=22) + """ + + # Validate the field names. At the user's option, either generate an error + # message or automatically replace the field name with a valid name. + if isinstance(field_names, str): + field_names = field_names.replace(',', ' ').split() + field_names = [str(x) for x in field_names] + if rename: + seen = set() + for index, name in enumerate(field_names): + if (not all(c.isalnum() or c == '_' for c in name) + or _iskeyword(name) + or not name + or name[0].isdigit() + or name.startswith('_') + or name in seen): + field_names[index] = '_%d' % index + seen.add(name) + for name in [typename] + field_names: + if not all(c.isalnum() or c == '_' for c in name): + raise ValueError('Type names and field names can only contain ' + 'alphanumeric characters and underscores: %r' + % name) + if _iskeyword(name): + raise ValueError('Type names and field names cannot be a ' + 'keyword: %r' % name) + if name[0].isdigit(): + raise ValueError('Type names and field names cannot start with ' + 'a number: %r' % name) + seen = set() + for name in field_names: + if name.startswith('_') and not rename: + raise ValueError('Field names cannot start with an underscore: ' + '%r' % name) + if name in seen: + raise ValueError('Encountered duplicate field name: %r' % name) + seen.add(name) + + # Fill-in the class template + fmt_kw = {'typename': typename} + fmt_kw['field_names'] = tuple(field_names) + fmt_kw['num_fields'] = len(field_names) + fmt_kw['arg_list'] = repr(tuple(field_names)).replace("'", "")[1:-1] + fmt_kw['repr_fmt'] = ', '.join(_repr_tmpl.format(name=name) + for name in field_names) + fmt_kw['field_defs'] = '\n'.join(_imm_field_tmpl.format(index=index, name=name) + for index, name in enumerate(field_names)) + class_definition = _namedtuple_tmpl.format(**fmt_kw) + + if verbose: + print(class_definition) + + # Execute the template string in a temporary namespace and support + # tracing utilities by setting a value for frame.f_globals['__name__'] + namespace = dict(_itemgetter=_itemgetter, + __name__='namedtuple_%s' % typename, + OrderedDict=OrderedDict, + _property=property, + _tuple=tuple) + try: + exec(class_definition, namespace) + except SyntaxError as e: + raise SyntaxError(e.msg + ':\n' + class_definition) + result = namespace[typename] + + # For pickling to work, the __module__ variable needs to be set to the frame + # where the named tuple is created. Bypass this step in environments where + # sys._getframe is not defined (Jython for example) or sys._getframe is not + # defined for arguments greater than 0 (IronPython). + try: + frame = _sys._getframe(1) + result.__module__ = frame.f_globals.get('__name__', '__main__') + except (AttributeError, ValueError): + pass + + return result + + +################################################################# +### namedlist +################################################################# + +_namedlist_tmpl = '''\ +class {typename}(list): + '{typename}({arg_list})' + + __slots__ = () + + _fields = {field_names!r} + + def __new__(_cls, {arg_list}): # TODO: tweak sig to make more extensible + 'Create new instance of {typename}({arg_list})' + return _list.__new__(_cls, ({arg_list})) + + def __init__(self, {arg_list}): # tuple didn't need this but list does + return _list.__init__(self, ({arg_list})) + + @classmethod + def _make(cls, iterable, new=_list, len=len): + 'Make a new {typename} object from a sequence or iterable' + # why did this function exist? why not just star the + # iterable like below? + result = cls(*iterable) + if len(result) != {num_fields:d}: + raise TypeError('Expected {num_fields:d} arguments,' + ' got %d' % len(result)) + return result + + def __repr__(self): + 'Return a nicely formatted representation string' + tmpl = self.__class__.__name__ + '({repr_fmt})' + return tmpl % tuple(self) + + def _asdict(self): + 'Return a new OrderedDict which maps field names to their values' + return OrderedDict(zip(self._fields, self)) + + def _replace(_self, **kwds): + 'Return a new {typename} object replacing field(s) with new values' + result = _self._make(map(kwds.pop, {field_names!r}, _self)) + if kwds: + raise ValueError('Got unexpected field names: %r' % kwds.keys()) + return result + + def __getnewargs__(self): + 'Return self as a plain list. Used by copy and pickle.' + return tuple(self) + + __dict__ = _property(_asdict) + + def __getstate__(self): + 'Exclude the OrderedDict from pickling' # wat + pass + +{field_defs} +''' + + +def namedlist(typename, field_names, verbose=False, rename=False): + """Returns a new subclass of list with named fields. + + >>> Point = namedlist('Point', ['x', 'y']) + >>> Point.__doc__ # docstring for the new class + 'Point(x, y)' + >>> p = Point(11, y=22) # instantiate with pos args or keywords + >>> p[0] + p[1] # indexable like a plain list + 33 + >>> x, y = p # unpack like a regular list + >>> x, y + (11, 22) + >>> p.x + p.y # fields also accessible by name + 33 + >>> d = p._asdict() # convert to a dictionary + >>> d['x'] + 11 + >>> Point(**d) # convert from a dictionary + Point(x=11, y=22) + >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields + Point(x=100, y=22) + """ + + # Validate the field names. At the user's option, either generate an error + # message or automatically replace the field name with a valid name. + if isinstance(field_names, str): + field_names = field_names.replace(',', ' ').split() + field_names = [str(x) for x in field_names] + if rename: + seen = set() + for index, name in enumerate(field_names): + if (not all(c.isalnum() or c == '_' for c in name) + or _iskeyword(name) + or not name + or name[0].isdigit() + or name.startswith('_') + or name in seen): + field_names[index] = '_%d' % index + seen.add(name) + for name in [typename] + field_names: + if not all(c.isalnum() or c == '_' for c in name): + raise ValueError('Type names and field names can only contain ' + 'alphanumeric characters and underscores: %r' + % name) + if _iskeyword(name): + raise ValueError('Type names and field names cannot be a ' + 'keyword: %r' % name) + if name[0].isdigit(): + raise ValueError('Type names and field names cannot start with ' + 'a number: %r' % name) + seen = set() + for name in field_names: + if name.startswith('_') and not rename: + raise ValueError('Field names cannot start with an underscore: ' + '%r' % name) + if name in seen: + raise ValueError('Encountered duplicate field name: %r' % name) + seen.add(name) + + # Fill-in the class template + fmt_kw = {'typename': typename} + fmt_kw['field_names'] = tuple(field_names) + fmt_kw['num_fields'] = len(field_names) + fmt_kw['arg_list'] = repr(tuple(field_names)).replace("'", "")[1:-1] + fmt_kw['repr_fmt'] = ', '.join(_repr_tmpl.format(name=name) + for name in field_names) + fmt_kw['field_defs'] = '\n'.join(_m_field_tmpl.format(index=index, name=name) + for index, name in enumerate(field_names)) + class_definition = _namedlist_tmpl.format(**fmt_kw) + + if verbose: + print(class_definition) + + def _itemsetter(key): + def _itemsetter(obj, value): + obj[key] = value + return _itemsetter + + # Execute the template string in a temporary namespace and support + # tracing utilities by setting a value for frame.f_globals['__name__'] + namespace = dict(_itemgetter=_itemgetter, + _itemsetter=_itemsetter, + __name__='namedlist_%s' % typename, + OrderedDict=OrderedDict, + _property=property, + _list=list) + try: + exec(class_definition, namespace) + except SyntaxError as e: + raise SyntaxError(e.msg + ':\n' + class_definition) + result = namespace[typename] + + # For pickling to work, the __module__ variable needs to be set to + # the frame where the named list is created. Bypass this step in + # environments where sys._getframe is not defined (Jython for + # example) or sys._getframe is not defined for arguments greater + # than 0 (IronPython). + try: + frame = _sys._getframe(1) + result.__module__ = frame.f_globals.get('__name__', '__main__') + except (AttributeError, ValueError): + pass + + return result diff --git a/data/miniconda3/lib/python3.13/site-packages/boltons/pathutils.py b/data/miniconda3/lib/python3.13/site-packages/boltons/pathutils.py new file mode 100644 index 0000000000000000000000000000000000000000..a8cb2602f31b5920c67c03027684b01c22bf371c --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/boltons/pathutils.py @@ -0,0 +1,183 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# * The names of the contributors may not be used to endorse or +# promote products derived from this software without specific +# prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +""" +Functions for working with filesystem paths. + +The :func:`expandpath` function expands the tilde to $HOME and environment +variables to their values. + +The :func:`augpath` function creates variants of an existing path without +having to spend multiple lines of code splitting it up and stitching it back +together. + +The :func:`shrinkuser` function replaces your home directory with a tilde. +""" + +from os.path import (expanduser, expandvars, join, normpath, split, splitext) +import os + + +__all__ = [ + 'augpath', 'shrinkuser', 'expandpath', +] + + +def augpath(path, suffix='', prefix='', ext=None, base=None, dpath=None, + multidot=False): + """ + Augment a path by modifying its components. + + Creates a new path with a different extension, basename, directory, prefix, + and/or suffix. + + A prefix is inserted before the basename. A suffix is inserted + between the basename and the extension. The basename and extension can be + replaced with a new one. Essentially a path is broken down into components + (dpath, base, ext), and then recombined as (dpath, prefix, base, suffix, + ext) after replacing any specified component. + + Args: + path (str | PathLike): a path to augment + suffix (str, default=''): placed between the basename and extension + prefix (str, default=''): placed in front of the basename + ext (str, default=None): if specified, replaces the extension + base (str, default=None): if specified, replaces the basename without + extension + dpath (str | PathLike, default=None): if specified, replaces the + directory + multidot (bool, default=False): Allows extensions to contain multiple + dots. Specifically, if False, everything after the last dot in the + basename is the extension. If True, everything after the first dot + in the basename is the extension. + + Returns: + str: augmented path + + Example: + >>> path = 'foo.bar' + >>> suffix = '_suff' + >>> prefix = 'pref_' + >>> ext = '.baz' + >>> newpath = augpath(path, suffix, prefix, ext=ext, base='bar') + >>> print('newpath = %s' % (newpath,)) + newpath = pref_bar_suff.baz + + Example: + >>> augpath('foo.bar') + 'foo.bar' + >>> augpath('foo.bar', ext='.BAZ') + 'foo.BAZ' + >>> augpath('foo.bar', suffix='_') + 'foo_.bar' + >>> augpath('foo.bar', prefix='_') + '_foo.bar' + >>> augpath('foo.bar', base='baz') + 'baz.bar' + >>> augpath('foo.tar.gz', ext='.zip', multidot=True) + 'foo.zip' + >>> augpath('foo.tar.gz', ext='.zip', multidot=False) + 'foo.tar.zip' + >>> augpath('foo.tar.gz', suffix='_new', multidot=True) + 'foo_new.tar.gz' + """ + # Breakup path + orig_dpath, fname = split(path) + if multidot: + # The first dot defines the extension + parts = fname.split('.', 1) + orig_base = parts[0] + orig_ext = '' if len(parts) == 1 else '.' + parts[1] + else: + # The last dot defines the extension + orig_base, orig_ext = splitext(fname) + # Replace parts with specified augmentations + if dpath is None: + dpath = orig_dpath + if ext is None: + ext = orig_ext + if base is None: + base = orig_base + # Recombine into new path + new_fname = ''.join((prefix, base, suffix, ext)) + newpath = join(dpath, new_fname) + return newpath + + +def shrinkuser(path, home='~'): + """ + Inverse of :func:`os.path.expanduser`. + + Args: + path (str | PathLike): path in system file structure + home (str, default='~'): symbol used to replace the home path. + Defaults to '~', but you might want to use '$HOME' or + '%USERPROFILE%' instead. + + Returns: + str: path: shortened path replacing the home directory with a tilde + + Example: + >>> path = expanduser('~') + >>> assert path != '~' + >>> assert shrinkuser(path) == '~' + >>> assert shrinkuser(path + '1') == path + '1' + >>> assert shrinkuser(path + '/1') == join('~', '1') + >>> assert shrinkuser(path + '/1', '$HOME') == join('$HOME', '1') + """ + path = normpath(path) + userhome_dpath = expanduser('~') + if path.startswith(userhome_dpath): + if len(path) == len(userhome_dpath): + path = home + elif path[len(userhome_dpath)] == os.path.sep: + path = home + path[len(userhome_dpath):] + return path + + +def expandpath(path): + """ + Shell-like expansion of environment variables and tilde home directory. + + Args: + path (str | PathLike): the path to expand + + Returns: + str : expanded path + + Example: + >>> import os + >>> os.environ['SPAM'] = 'eggs' + >>> assert expandpath('~/$SPAM') == expanduser('~/eggs') + >>> assert expandpath('foo') == 'foo' + """ + path = expanduser(path) + path = expandvars(path) + return path diff --git a/data/miniconda3/lib/python3.13/site-packages/boltons/queueutils.py b/data/miniconda3/lib/python3.13/site-packages/boltons/queueutils.py new file mode 100644 index 0000000000000000000000000000000000000000..f6e4e4c28d0f0a394eb6deba7fec1f92b1344059 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/boltons/queueutils.py @@ -0,0 +1,223 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# * The names of the contributors may not be used to endorse or +# promote products derived from this software without specific +# prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Python comes with a many great data structures, from :class:`dict` +to :class:`collections.deque`, and no shortage of serviceable +algorithm implementations, from :func:`sorted` to :mod:`bisect`. But +priority queues are curiously relegated to an example documented in +:mod:`heapq`. Even there, the approach presented is not full-featured +and object-oriented. There is a built-in priority queue, +:class:`Queue.PriorityQueue`, but in addition to its austere API, it +carries the double-edged sword of threadsafety, making it fine for +multi-threaded, multi-consumer applications, but high-overhead for +cooperative/single-threaded use cases. + +The ``queueutils`` module currently provides two Queue +implementations: :class:`HeapPriorityQueue`, based on a heap, and +:class:`SortedPriorityQueue`, based on a sorted list. Both use a +unified API based on :class:`BasePriorityQueue` to facilitate testing +the slightly different performance characteristics on various +application use cases. + +>>> pq = PriorityQueue() +>>> pq.add('low priority task', 0) +>>> pq.add('high priority task', 2) +>>> pq.add('medium priority task 1', 1) +>>> pq.add('medium priority task 2', 1) +>>> len(pq) +4 +>>> pq.pop() +'high priority task' +>>> pq.peek() +'medium priority task 1' +>>> len(pq) +3 + +""" + + +from heapq import heappush, heappop +from bisect import insort +import itertools + +try: + from .typeutils import make_sentinel + _REMOVED = make_sentinel(var_name='_REMOVED') +except ImportError: + _REMOVED = object() + +try: + from .listutils import BList + # see BarrelList docstring for notes +except ImportError: + BList = list + + +__all__ = ['PriorityQueue', 'BasePriorityQueue', + 'HeapPriorityQueue', 'SortedPriorityQueue'] + + +# TODO: make Base a real abstract class +# TODO: add uniqueification + + +class BasePriorityQueue: + """The abstract base class for the other PriorityQueues in this + module. Override the ``_backend_type`` class attribute, as well as + the :meth:`_push_entry` and :meth:`_pop_entry` staticmethods for + custom subclass behavior. (Don't forget to use + :func:`staticmethod`). + + Args: + priority_key (callable): A function that takes *priority* as + passed in by :meth:`add` and returns a real number + representing the effective priority. + + """ + # negating priority means larger numbers = higher priority + _default_priority_key = staticmethod(lambda p: -float(p or 0)) + _backend_type = list + + def __init__(self, **kw): + self._pq = self._backend_type() + self._entry_map = {} + self._counter = itertools.count() + self._get_priority = kw.pop('priority_key', self._default_priority_key) + if kw: + raise TypeError('unexpected keyword arguments: %r' % kw.keys()) + + @staticmethod + def _push_entry(backend, entry): + pass # abstract + + @staticmethod + def _pop_entry(backend): + pass # abstract + + def add(self, task, priority=None): + """ + Add a task to the queue, or change the *task*'s priority if *task* + is already in the queue. *task* can be any hashable object, + and *priority* defaults to ``0``. Higher values representing + higher priority, but this behavior can be controlled by + setting *priority_key* in the constructor. + """ + priority = self._get_priority(priority) + if task in self._entry_map: + self.remove(task) + count = next(self._counter) + entry = [priority, count, task] + self._entry_map[task] = entry + self._push_entry(self._pq, entry) + + def remove(self, task): + """Remove a task from the priority queue. Raises :exc:`KeyError` if + the *task* is absent. + """ + entry = self._entry_map.pop(task) + entry[-1] = _REMOVED + + def _cull(self, raise_exc=True): + "Remove entries marked as removed by previous :meth:`remove` calls." + while self._pq: + priority, count, task = self._pq[0] + if task is _REMOVED: + self._pop_entry(self._pq) + continue + return + if raise_exc: + raise IndexError('empty priority queue') + + def peek(self, default=_REMOVED): + """Read the next value in the queue without removing it. Returns + *default* on an empty queue, or raises :exc:`KeyError` if + *default* is not set. + """ + try: + self._cull() + _, _, task = self._pq[0] + except IndexError: + if default is not _REMOVED: + return default + raise IndexError('peek on empty queue') + return task + + def pop(self, default=_REMOVED): + """Remove and return the next value in the queue. Returns *default* on + an empty queue, or raises :exc:`KeyError` if *default* is not + set. + """ + try: + self._cull() + _, _, task = self._pop_entry(self._pq) + del self._entry_map[task] + except IndexError: + if default is not _REMOVED: + return default + raise IndexError('pop on empty queue') + return task + + def __len__(self): + "Return the number of tasks in the queue." + return len(self._entry_map) + + +class HeapPriorityQueue(BasePriorityQueue): + """A priority queue inherited from :class:`BasePriorityQueue`, + backed by a list and based on the :func:`heapq.heappop` and + :func:`heapq.heappush` functions in the built-in :mod:`heapq` + module. + """ + @staticmethod + def _pop_entry(backend): + return heappop(backend) + + @staticmethod + def _push_entry(backend, entry): + heappush(backend, entry) + + +class SortedPriorityQueue(BasePriorityQueue): + """A priority queue inherited from :class:`BasePriorityQueue`, based + on the :func:`bisect.insort` approach for in-order insertion into + a sorted list. + """ + _backend_type = BList + + @staticmethod + def _pop_entry(backend): + return backend.pop(0) + + @staticmethod + def _push_entry(backend, entry): + insort(backend, entry) + + +PriorityQueue = SortedPriorityQueue diff --git a/data/miniconda3/lib/python3.13/site-packages/boltons/setutils.py b/data/miniconda3/lib/python3.13/site-packages/boltons/setutils.py new file mode 100644 index 0000000000000000000000000000000000000000..3ed5ab32052ebb2750f90a2bc07eab40b2249525 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/boltons/setutils.py @@ -0,0 +1,969 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# * The names of the contributors may not be used to endorse or +# promote products derived from this software without specific +# prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""\ + +The :class:`set` type brings the practical expressiveness of +set theory to Python. It has a very rich API overall, but lacks a +couple of fundamental features. For one, sets are not ordered. On top +of this, sets are not indexable, i.e, ``my_set[8]`` will raise an +:exc:`TypeError`. The :class:`IndexedSet` type remedies both of these +issues without compromising on the excellent complexity +characteristics of Python's built-in set implementation. +""" + + +from bisect import bisect_left +from collections.abc import MutableSet +from itertools import chain, islice +import operator + +try: + from .typeutils import make_sentinel + _MISSING = make_sentinel(var_name='_MISSING') +except ImportError: + _MISSING = object() + + +__all__ = ['IndexedSet', 'complement'] + + +_COMPACTION_FACTOR = 8 + +# TODO: inherit from set() +# TODO: .discard_many(), .remove_many() +# TODO: raise exception on non-set params? +# TODO: technically reverse operators should probably reverse the +# order of the 'other' inputs and put self last (to try and maintain +# insertion order) + + +class IndexedSet(MutableSet): + """``IndexedSet`` is a :class:`collections.MutableSet` that maintains + insertion order and uniqueness of inserted elements. It's a hybrid + type, mostly like an OrderedSet, but also :class:`list`-like, in + that it supports indexing and slicing. + + Args: + other (iterable): An optional iterable used to initialize the set. + + >>> x = IndexedSet(list(range(4)) + list(range(8))) + >>> x + IndexedSet([0, 1, 2, 3, 4, 5, 6, 7]) + >>> x - set(range(2)) + IndexedSet([2, 3, 4, 5, 6, 7]) + >>> x[-1] + 7 + >>> fcr = IndexedSet('freecreditreport.com') + >>> ''.join(fcr[:fcr.index('.')]) + 'frecditpo' + + Standard set operators and interoperation with :class:`set` are + all supported: + + >>> fcr & set('cash4gold.com') + IndexedSet(['c', 'd', 'o', '.', 'm']) + + As you can see, the ``IndexedSet`` is almost like a ``UniqueList``, + retaining only one copy of a given value, in the order it was + first added. For the curious, the reason why IndexedSet does not + support setting items based on index (i.e, ``__setitem__()``), + consider the following dilemma:: + + my_indexed_set = [A, B, C, D] + my_indexed_set[2] = A + + At this point, a set requires only one *A*, but a :class:`list` would + overwrite *C*. Overwriting *C* would change the length of the list, + meaning that ``my_indexed_set[2]`` would not be *A*, as expected with a + list, but rather *D*. So, no ``__setitem__()``. + + Otherwise, the API strives to be as complete a union of the + :class:`list` and :class:`set` APIs as possible. + """ + def __init__(self, other=None): + self.item_index_map = dict() + self.item_list = [] + self.dead_indices = [] + self._compactions = 0 + self._c_max_size = 0 + if other: + self.update(other) + + # internal functions + @property + def _dead_index_count(self): + return len(self.item_list) - len(self.item_index_map) + + def _compact(self): + if not self.dead_indices: + return + self._compactions += 1 + dead_index_count = self._dead_index_count + items, index_map = self.item_list, self.item_index_map + self._c_max_size = max(self._c_max_size, len(items)) + for i, item in enumerate(self): + items[i] = item + index_map[item] = i + del items[-dead_index_count:] + del self.dead_indices[:] + + def _cull(self): + ded = self.dead_indices + if not ded: + return + items, ii_map = self.item_list, self.item_index_map + if not ii_map: + del items[:] + del ded[:] + elif len(ded) > 384: + self._compact() + elif self._dead_index_count > (len(items) / _COMPACTION_FACTOR): + self._compact() + elif items[-1] is _MISSING: # get rid of dead right hand side + num_dead = 1 + while items[-(num_dead + 1)] is _MISSING: + num_dead += 1 + if ded and ded[-1][1] == len(items): + del ded[-1] + del items[-num_dead:] + + def _get_real_index(self, index): + if index < 0: + index += len(self) + if not self.dead_indices: + return index + real_index = index + for d_start, d_stop in self.dead_indices: + if real_index < d_start: + break + real_index += d_stop - d_start + return real_index + + def _get_apparent_index(self, index): + if index < 0: + index += len(self) + if not self.dead_indices: + return index + apparent_index = index + for d_start, d_stop in self.dead_indices: + if index < d_start: + break + apparent_index -= d_stop - d_start + return apparent_index + + def _add_dead(self, start, stop=None): + # TODO: does not handle when the new interval subsumes + # multiple existing intervals + dints = self.dead_indices + if stop is None: + stop = start + 1 + cand_int = [start, stop] + if not dints: + dints.append(cand_int) + return + int_idx = bisect_left(dints, cand_int) + dint = dints[int_idx - 1] + d_start, d_stop = dint + if start <= d_start <= stop: + dint[0] = start + elif start <= d_stop <= stop: + dint[1] = stop + else: + dints.insert(int_idx, cand_int) + return + + # common operations (shared by set and list) + def __len__(self): + return len(self.item_index_map) + + def __contains__(self, item): + return item in self.item_index_map + + def __iter__(self): + return (item for item in self.item_list if item is not _MISSING) + + def __reversed__(self): + item_list = self.item_list + return (item for item in reversed(item_list) if item is not _MISSING) + + def __repr__(self): + return f'{self.__class__.__name__}({list(self)!r})' + + def __eq__(self, other): + if isinstance(other, IndexedSet): + return len(self) == len(other) and list(self) == list(other) + try: + return set(self) == set(other) + except TypeError: + return False + + @classmethod + def from_iterable(cls, it): + "from_iterable(it) -> create a set from an iterable" + return cls(it) + + # set operations + def add(self, item): + "add(item) -> add item to the set" + if item not in self.item_index_map: + self.item_index_map[item] = len(self.item_list) + self.item_list.append(item) + + def remove(self, item): + "remove(item) -> remove item from the set, raises if not present" + try: + didx = self.item_index_map.pop(item) + except KeyError: + raise KeyError(item) + self.item_list[didx] = _MISSING + self._add_dead(didx) + self._cull() + + def discard(self, item): + "discard(item) -> discard item from the set (does not raise)" + try: + self.remove(item) + except KeyError: + pass + + def clear(self): + "clear() -> empty the set" + del self.item_list[:] + del self.dead_indices[:] + self.item_index_map.clear() + + def isdisjoint(self, other): + "isdisjoint(other) -> return True if no overlap with other" + iim = self.item_index_map + for k in other: + if k in iim: + return False + return True + + def issubset(self, other): + "issubset(other) -> return True if other contains this set" + if len(other) < len(self): + return False + for k in self.item_index_map: + if k not in other: + return False + return True + + def issuperset(self, other): + "issuperset(other) -> return True if set contains other" + if len(other) > len(self): + return False + iim = self.item_index_map + for k in other: + if k not in iim: + return False + return True + + def union(self, *others): + "union(*others) -> return a new set containing this set and others" + return self.from_iterable(chain(self, *others)) + + def iter_intersection(self, *others): + "iter_intersection(*others) -> iterate over elements also in others" + for k in self: + for other in others: + if k not in other: + break + else: + yield k + return + + def intersection(self, *others): + "intersection(*others) -> get a set with overlap of this and others" + if len(others) == 1: + other = others[0] + return self.from_iterable(k for k in self if k in other) + return self.from_iterable(self.iter_intersection(*others)) + + def iter_difference(self, *others): + "iter_difference(*others) -> iterate over elements not in others" + for k in self: + for other in others: + if k in other: + break + else: + yield k + return + + def difference(self, *others): + "difference(*others) -> get a new set with elements not in others" + if len(others) == 1: + other = others[0] + return self.from_iterable(k for k in self if k not in other) + return self.from_iterable(self.iter_difference(*others)) + + def symmetric_difference(self, *others): + "symmetric_difference(*others) -> XOR set of this and others" + ret = self.union(*others) + return ret.difference(self.intersection(*others)) + + __or__ = __ror__ = union + __and__ = __rand__ = intersection + __sub__ = difference + __xor__ = __rxor__ = symmetric_difference + + def __rsub__(self, other): + vals = [x for x in other if x not in self] + return type(other)(vals) + + # in-place set operations + def update(self, *others): + "update(*others) -> add values from one or more iterables" + if not others: + return # raise? + elif len(others) == 1: + other = others[0] + else: + other = chain(others) + for o in other: + self.add(o) + + def intersection_update(self, *others): + "intersection_update(*others) -> discard self.difference(*others)" + for val in self.difference(*others): + self.discard(val) + + def difference_update(self, *others): + "difference_update(*others) -> discard self.intersection(*others)" + if self in others: + self.clear() + for val in self.intersection(*others): + self.discard(val) + + def symmetric_difference_update(self, other): # note singular 'other' + "symmetric_difference_update(other) -> in-place XOR with other" + if self is other: + self.clear() + for val in other: + if val in self: + self.discard(val) + else: + self.add(val) + + def __ior__(self, *others): + self.update(*others) + return self + + def __iand__(self, *others): + self.intersection_update(*others) + return self + + def __isub__(self, *others): + self.difference_update(*others) + return self + + def __ixor__(self, *others): + self.symmetric_difference_update(*others) + return self + + def iter_slice(self, start, stop, step=None): + "iterate over a slice of the set" + iterable = self + if start is not None: + start = self._get_real_index(start) + if stop is not None: + stop = self._get_real_index(stop) + if step is not None and step < 0: + step = -step + iterable = reversed(self) + return islice(iterable, start, stop, step) + + # list operations + def __getitem__(self, index): + try: + start, stop, step = index.start, index.stop, index.step + except AttributeError: + index = operator.index(index) + else: + iter_slice = self.iter_slice(start, stop, step) + return self.from_iterable(iter_slice) + if index < 0: + index += len(self) + real_index = self._get_real_index(index) + try: + ret = self.item_list[real_index] + except IndexError: + raise IndexError('IndexedSet index out of range') + return ret + + def pop(self, index=None): + "pop(index) -> remove the item at a given index (-1 by default)" + item_index_map = self.item_index_map + len_self = len(item_index_map) + if index is None or index == -1 or index == len_self - 1: + ret = self.item_list.pop() + del item_index_map[ret] + else: + real_index = self._get_real_index(index) + ret = self.item_list[real_index] + self.item_list[real_index] = _MISSING + del item_index_map[ret] + self._add_dead(real_index) + self._cull() + return ret + + def count(self, val): + "count(val) -> count number of instances of value (0 or 1)" + if val in self.item_index_map: + return 1 + return 0 + + def reverse(self): + "reverse() -> reverse the contents of the set in-place" + reversed_list = list(reversed(self)) + self.item_list[:] = reversed_list + for i, item in enumerate(self.item_list): + self.item_index_map[item] = i + del self.dead_indices[:] + + def sort(self, **kwargs): + "sort() -> sort the contents of the set in-place" + sorted_list = sorted(self, **kwargs) + if sorted_list == self.item_list: + return + self.item_list[:] = sorted_list + for i, item in enumerate(self.item_list): + self.item_index_map[item] = i + del self.dead_indices[:] + + def index(self, val): + "index(val) -> get the index of a value, raises if not present" + try: + return self._get_apparent_index(self.item_index_map[val]) + except KeyError: + cn = self.__class__.__name__ + raise ValueError(f'{val!r} is not in {cn}') + + +def complement(wrapped): + """Given a :class:`set`, convert it to a **complement set**. + + Whereas a :class:`set` keeps track of what it contains, a + `complement set + `_ keeps + track of what it does *not* contain. For example, look what + happens when we intersect a normal set with a complement set:: + + >>> list(set(range(5)) & complement(set([2, 3]))) + [0, 1, 4] + + We get the everything in the left that wasn't in the right, + because intersecting with a complement is the same as subtracting + a normal set. + + Args: + wrapped (set): A set or any other iterable which should be + turned into a complement set. + + All set methods and operators are supported by complement sets, + between other :func:`complement`-wrapped sets and/or regular + :class:`set` objects. + + Because a complement set only tracks what elements are *not* in + the set, functionality based on set contents is unavailable: + :func:`len`, :func:`iter` (and for loops), and ``.pop()``. But a + complement set can always be turned back into a regular set by + complementing it again: + + >>> s = set(range(5)) + >>> complement(complement(s)) == s + True + + .. note:: + + An empty complement set corresponds to the concept of a + `universal set `_ + from mathematics. + + Complement sets by example + ^^^^^^^^^^^^^^^^^^^^^^^^^^ + + Many uses of sets can be expressed more simply by using a + complement. Rather than trying to work out in your head the proper + way to invert an expression, you can just throw a complement on + the set. Consider this example of a name filter:: + + >>> class NamesFilter(object): + ... def __init__(self, allowed): + ... self._allowed = allowed + ... + ... def filter(self, names): + ... return [name for name in names if name in self._allowed] + >>> NamesFilter(set(['alice', 'bob'])).filter(['alice', 'bob', 'carol']) + ['alice', 'bob'] + + What if we want to just express "let all the names through"? + + We could try to enumerate all of the expected names:: + + ``NamesFilter({'alice', 'bob', 'carol'})`` + + But this is very brittle -- what if at some point over this + object is changed to filter ``['alice', 'bob', 'carol', 'dan']``? + + Even worse, what about the poor programmer who next works + on this piece of code? They cannot tell whether the purpose + of the large allowed set was "allow everything", or if 'dan' + was excluded for some subtle reason. + + A complement set lets the programmer intention be expressed + succinctly and directly:: + + NamesFilter(complement(set())) + + Not only is this code short and robust, it is easy to understand + the intention. + + """ + if type(wrapped) is _ComplementSet: + return wrapped.complemented() + if type(wrapped) is frozenset: + return _ComplementSet(excluded=wrapped) + return _ComplementSet(excluded=set(wrapped)) + + +def _norm_args_typeerror(other): + '''normalize args and raise type-error if there is a problem''' + if type(other) in (set, frozenset): + inc, exc = other, None + elif type(other) is _ComplementSet: + inc, exc = other._included, other._excluded + else: + raise TypeError('argument must be another set or complement(set)') + return inc, exc + + +def _norm_args_notimplemented(other): + '''normalize args and return NotImplemented (for overloaded operators)''' + if type(other) in (set, frozenset): + inc, exc = other, None + elif type(other) is _ComplementSet: + inc, exc = other._included, other._excluded + else: + return NotImplemented, None + return inc, exc + + +class _ComplementSet: + """ + helper class for complement() that implements the set methods + """ + __slots__ = ('_included', '_excluded') + + def __init__(self, included=None, excluded=None): + if included is None: + assert type(excluded) in (set, frozenset) + elif excluded is None: + assert type(included) in (set, frozenset) + else: + raise ValueError('one of included or excluded must be a set') + self._included, self._excluded = included, excluded + + def __repr__(self): + if self._included is None: + return f'complement({repr(self._excluded)})' + return f'complement(complement({repr(self._included)}))' + + def complemented(self): + '''return a complement of the current set''' + if type(self._included) is frozenset or type(self._excluded) is frozenset: + return _ComplementSet(included=self._excluded, excluded=self._included) + return _ComplementSet( + included=None if self._excluded is None else set(self._excluded), + excluded=None if self._included is None else set(self._included)) + + __invert__ = complemented + + def complement(self): + '''convert the current set to its complement in-place''' + self._included, self._excluded = self._excluded, self._included + + def __contains__(self, item): + if self._included is None: + return not item in self._excluded + return item in self._included + + def add(self, item): + if self._included is None: + if item in self._excluded: + self._excluded.remove(item) + else: + self._included.add(item) + + def remove(self, item): + if self._included is None: + self._excluded.add(item) + else: + self._included.remove(item) + + def pop(self): + if self._included is None: + raise NotImplementedError # self.missing.add(random.choice(gc.objects())) + return self._included.pop() + + def intersection(self, other): + try: + return self & other + except NotImplementedError: + raise TypeError('argument must be another set or complement(set)') + + def __and__(self, other): + inc, exc = _norm_args_notimplemented(other) + if inc is NotImplemented: + return NotImplemented + if self._included is None: + if exc is None: # - + + return _ComplementSet(included=inc - self._excluded) + else: # - - + return _ComplementSet(excluded=self._excluded.union(other._excluded)) + else: + if inc is None: # + - + return _ComplementSet(included=exc - self._included) + else: # + + + return _ComplementSet(included=self._included.intersection(inc)) + + __rand__ = __and__ + + def __iand__(self, other): + inc, exc = _norm_args_notimplemented(other) + if inc is NotImplemented: + return NotImplemented + if self._included is None: + if exc is None: # - + + self._excluded = inc - self._excluded # TODO: do this in place? + else: # - - + self._excluded |= exc + else: + if inc is None: # + - + self._included -= exc + self._included, self._excluded = None, self._included + else: # + + + self._included &= inc + return self + + def union(self, other): + try: + return self | other + except NotImplementedError: + raise TypeError('argument must be another set or complement(set)') + + def __or__(self, other): + inc, exc = _norm_args_notimplemented(other) + if inc is NotImplemented: + return NotImplemented + if self._included is None: + if exc is None: # - + + return _ComplementSet(excluded=self._excluded - inc) + else: # - - + return _ComplementSet(excluded=self._excluded.intersection(exc)) + else: + if inc is None: # + - + return _ComplementSet(excluded=exc - self._included) + else: # + + + return _ComplementSet(included=self._included.union(inc)) + + __ror__ = __or__ + + def __ior__(self, other): + inc, exc = _norm_args_notimplemented(other) + if inc is NotImplemented: + return NotImplemented + if self._included is None: + if exc is None: # - + + self._excluded -= inc + else: # - - + self._excluded &= exc + else: + if inc is None: # + - + self._included, self._excluded = None, exc - self._included # TODO: do this in place? + else: # + + + self._included |= inc + return self + + def update(self, items): + if type(items) in (set, frozenset): + inc, exc = items, None + elif type(items) is _ComplementSet: + inc, exc = items._included, items._excluded + else: + inc, exc = frozenset(items), None + if self._included is None: + if exc is None: # - + + self._excluded &= inc + else: # - - + self._excluded.discard(exc) + else: + if inc is None: # + - + self._included &= exc + self._included, self._excluded = None, self._excluded + else: # + + + self._included.update(inc) + + def discard(self, items): + if type(items) in (set, frozenset): + inc, exc = items, None + elif type(items) is _ComplementSet: + inc, exc = items._included, items._excluded + else: + inc, exc = frozenset(items), None + if self._included is None: + if exc is None: # - + + self._excluded.update(inc) + else: # - - + self._included, self._excluded = exc - self._excluded, None + else: + if inc is None: # + - + self._included &= exc + else: # + + + self._included.discard(inc) + + def symmetric_difference(self, other): + try: + return self ^ other + except NotImplementedError: + raise TypeError('argument must be another set or complement(set)') + + def __xor__(self, other): + inc, exc = _norm_args_notimplemented(other) + if inc is NotImplemented: + return NotImplemented + if inc is NotImplemented: + return NotImplemented + if self._included is None: + if exc is None: # - + + return _ComplementSet(excluded=self._excluded - inc) + else: # - - + return _ComplementSet(included=self._excluded.symmetric_difference(exc)) + else: + if inc is None: # + - + return _ComplementSet(excluded=exc - self._included) + else: # + + + return _ComplementSet(included=self._included.symmetric_difference(inc)) + + __rxor__ = __xor__ + + def symmetric_difference_update(self, other): + inc, exc = _norm_args_typeerror(other) + if self._included is None: + if exc is None: # - + + self._excluded |= inc + else: # - - + self._excluded.symmetric_difference_update(exc) + self._included, self._excluded = self._excluded, None + else: + if inc is None: # + - + self._included |= exc + self._included, self._excluded = None, self._included + else: # + + + self._included.symmetric_difference_update(inc) + + def isdisjoint(self, other): + inc, exc = _norm_args_typeerror(other) + if inc is NotImplemented: + return NotImplemented + if self._included is None: + if exc is None: # - + + return inc.issubset(self._excluded) + else: # - - + return False + else: + if inc is None: # + - + return self._included.issubset(exc) + else: # + + + return self._included.isdisjoint(inc) + + def issubset(self, other): + '''everything missing from other is also missing from self''' + try: + return self <= other + except NotImplementedError: + raise TypeError('argument must be another set or complement(set)') + + def __le__(self, other): + inc, exc = _norm_args_notimplemented(other) + if inc is NotImplemented: + return NotImplemented + if inc is NotImplemented: + return NotImplemented + if self._included is None: + if exc is None: # - + + return False + else: # - - + return self._excluded.issupserset(exc) + else: + if inc is None: # + - + return self._included.isdisjoint(exc) + else: # + + + return self._included.issubset(inc) + + def __lt__(self, other): + inc, exc = _norm_args_notimplemented(other) + if inc is NotImplemented: + return NotImplemented + if inc is NotImplemented: + return NotImplemented + if self._included is None: + if exc is None: # - + + return False + else: # - - + return self._excluded > exc + else: + if inc is None: # + - + return self._included.isdisjoint(exc) + else: # + + + return self._included < inc + + def issuperset(self, other): + '''everything missing from self is also missing from super''' + try: + return self >= other + except NotImplementedError: + raise TypeError('argument must be another set or complement(set)') + + def __ge__(self, other): + inc, exc = _norm_args_notimplemented(other) + if inc is NotImplemented: + return NotImplemented + if self._included is None: + if exc is None: # - + + return not self._excluded.intersection(inc) + else: # - - + return self._excluded.issubset(exc) + else: + if inc is None: # + - + return False + else: # + + + return self._included.issupserset(inc) + + def __gt__(self, other): + inc, exc = _norm_args_notimplemented(other) + if inc is NotImplemented: + return NotImplemented + if self._included is None: + if exc is None: # - + + return not self._excluded.intersection(inc) + else: # - - + return self._excluded < exc + else: + if inc is None: # + - + return False + else: # + + + return self._included > inc + + def difference(self, other): + try: + return self - other + except NotImplementedError: + raise TypeError('argument must be another set or complement(set)') + + def __sub__(self, other): + inc, exc = _norm_args_notimplemented(other) + if inc is NotImplemented: + return NotImplemented + if self._included is None: + if exc is None: # - + + return _ComplementSet(excluded=self._excluded | inc) + else: # - - + return _ComplementSet(included=exc - self._excluded) + else: + if inc is None: # + - + return _ComplementSet(included=self._included & exc) + else: # + + + return _ComplementSet(included=self._included.difference(inc)) + + def __rsub__(self, other): + inc, exc = _norm_args_notimplemented(other) + if inc is NotImplemented: + return NotImplemented + # rsub, so the expression being evaluated is "other - self" + if self._included is None: + if exc is None: # - + + return _ComplementSet(included=inc & self._excluded) + else: # - - + return _ComplementSet(included=self._excluded - exc) + else: + if inc is None: # + - + return _ComplementSet(excluded=exc | self._included) + else: # + + + return _ComplementSet(included=inc.difference(self._included)) + + def difference_update(self, other): + try: + self -= other + except NotImplementedError: + raise TypeError('argument must be another set or complement(set)') + + def __isub__(self, other): + inc, exc = _norm_args_notimplemented(other) + if inc is NotImplemented: + return NotImplemented + if self._included is None: + if exc is None: # - + + self._excluded |= inc + else: # - - + self._included, self._excluded = exc - self._excluded, None + else: + if inc is None: # + - + self._included &= exc + else: # + + + self._included.difference_update(inc) + return self + + def __eq__(self, other): + return ( + type(self) is type(other) + and self._included == other._included + and self._excluded == other._excluded) or ( + type(other) in (set, frozenset) and self._included == other) + + def __hash__(self): + return hash(self._included) ^ hash(self._excluded) + + def __len__(self): + if self._included is not None: + return len(self._included) + raise NotImplementedError('complemented sets have undefined length') + + def __iter__(self): + if self._included is not None: + return iter(self._included) + raise NotImplementedError('complemented sets have undefined contents') + + def __bool__(self): + if self._included is not None: + return bool(self._included) + return True + diff --git a/data/miniconda3/lib/python3.13/site-packages/boltons/socketutils.py b/data/miniconda3/lib/python3.13/site-packages/boltons/socketutils.py new file mode 100644 index 0000000000000000000000000000000000000000..387f84f0dde1e0d6a80a7c0518e39be4c6949855 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/boltons/socketutils.py @@ -0,0 +1,766 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# * The names of the contributors may not be used to endorse or +# promote products derived from this software without specific +# prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""At its heart, Python can be viewed as an extension of the C +programming language. Springing from the most popular systems +programming language has made Python itself a great language for +systems programming. One key to success in this domain is Python's +very serviceable :mod:`socket` module and its :class:`socket.socket` +type. + +The ``socketutils`` module provides natural next steps to the ``socket`` +builtin: straightforward, tested building blocks for higher-level +protocols. + +The :class:`BufferedSocket` wraps an ordinary socket, providing a +layer of intuitive buffering for both sending and receiving. This +facilitates parsing messages from streams, i.e., all sockets with type +``SOCK_STREAM``. The BufferedSocket enables receiving until the next +relevant token, up to a certain size, or until the connection is +closed. For all of these, it provides consistent APIs to size +limiting, as well as timeouts that are compatible with multiple +concurrency paradigms. Use it to parse the next one-off text or binary +socket protocol you encounter. + +This module also provides the :class:`NetstringSocket`, a pure-Python +implementation of `the Netstring protocol`_, built on top of the +:class:`BufferedSocket`, serving as a ready-made, production-grade example. + +Special thanks to `Kurt Rose`_ for his original authorship and all his +contributions on this module. Also thanks to `Daniel J. Bernstein`_, the +original author of `Netstring`_. + +.. _the Netstring protocol: https://en.wikipedia.org/wiki/Netstring +.. _Kurt Rose: https://github.com/doublereedkurt +.. _Daniel J. Bernstein: https://cr.yp.to/ +.. _Netstring: https://cr.yp.to/proto/netstrings.txt + +""" + +import time +import socket + +try: + from threading import RLock +except Exception: + class RLock: + 'Dummy reentrant lock for builds without threads' + def __enter__(self): + pass + + def __exit__(self, exctype, excinst, exctb): + pass + + +try: + from .typeutils import make_sentinel + _UNSET = make_sentinel(var_name='_UNSET') +except ImportError: + _UNSET = object() + + +DEFAULT_TIMEOUT = 10 # 10 seconds +DEFAULT_MAXSIZE = 32 * 1024 # 32kb +_RECV_LARGE_MAXSIZE = 1024 ** 5 # 1PB + + +class BufferedSocket: + """Mainly provides recv_until and recv_size. recv, send, sendall, and + peek all function as similarly as possible to the built-in socket + API. + + This type has been tested against both the built-in socket type as + well as those from gevent and eventlet. It also features support + for sockets with timeouts set to 0 (aka nonblocking), provided the + caller is prepared to handle the EWOULDBLOCK exceptions. + + Args: + sock (socket): The connected socket to be wrapped. + timeout (float): The default timeout for sends and recvs, in + seconds. Set to ``None`` for no timeout, and 0 for + nonblocking. Defaults to *sock*'s own timeout if already set, + and 10 seconds otherwise. + maxsize (int): The default maximum number of bytes to be received + into the buffer before it is considered full and raises an + exception. Defaults to 32 kilobytes. + recvsize (int): The number of bytes to recv for every + lower-level :meth:`socket.recv` call. Defaults to *maxsize*. + + *timeout* and *maxsize* can both be overridden on individual socket + operations. + + All ``recv`` methods return bytestrings (:class:`bytes`) and can + raise :exc:`socket.error`. :exc:`Timeout`, + :exc:`ConnectionClosed`, and :exc:`MessageTooLong` all inherit + from :exc:`socket.error` and exist to provide better error + messages. Received bytes are always buffered, even if an exception + is raised. Use :meth:`BufferedSocket.getrecvbuffer` to retrieve + partial recvs. + + BufferedSocket does not replace the built-in socket by any + means. While the overlapping parts of the API are kept parallel to + the built-in :class:`socket.socket`, BufferedSocket does not + inherit from socket, and most socket functionality is only + available on the underlying socket. :meth:`socket.getpeername`, + :meth:`socket.getsockname`, :meth:`socket.fileno`, and others are + only available on the underlying socket that is wrapped. Use the + ``BufferedSocket.sock`` attribute to access it. See the examples + for more information on how to use BufferedSockets with built-in + sockets. + + The BufferedSocket is threadsafe, but consider the semantics of + your protocol before accessing a single socket from multiple + threads. Similarly, once the BufferedSocket is constructed, avoid + using the underlying socket directly. Only use it for operations + unrelated to messages, e.g., :meth:`socket.getpeername`. + + """ + def __init__(self, sock, timeout=_UNSET, + maxsize=DEFAULT_MAXSIZE, recvsize=_UNSET): + self.sock = sock + self.rbuf = b'' + self.sbuf = [] + self.maxsize = int(maxsize) + + if timeout is _UNSET: + if self.sock.gettimeout() is None: + self.timeout = DEFAULT_TIMEOUT + else: + self.timeout = self.sock.gettimeout() + else: + if timeout is None: + self.timeout = timeout + else: + self.timeout = float(timeout) + + if recvsize is _UNSET: + self._recvsize = self.maxsize + else: + self._recvsize = int(recvsize) + + self._send_lock = RLock() + self._recv_lock = RLock() + + def settimeout(self, timeout): + "Set the default *timeout* for future operations, in seconds." + self.timeout = timeout + + def gettimeout(self): + return self.timeout + + def setblocking(self, blocking): + self.timeout = None if blocking else 0.0 + + def setmaxsize(self, maxsize): + """Set the default maximum buffer size *maxsize* for future + operations, in bytes. Does not truncate the current buffer. + """ + self.maxsize = maxsize + + def getrecvbuffer(self): + "Returns the receive buffer bytestring (rbuf)." + with self._recv_lock: + return self.rbuf + + def getsendbuffer(self): + "Returns a copy of the send buffer list." + with self._send_lock: + return b''.join(self.sbuf) + + def recv(self, size, flags=0, timeout=_UNSET): + """Returns **up to** *size* bytes, using the internal buffer before + performing a single :meth:`socket.recv` operation. + + Args: + size (int): The maximum number of bytes to receive. + flags (int): Kept for API compatibility with sockets. Only + the default, ``0``, is valid. + timeout (float): The timeout for this operation. Can be + ``0`` for nonblocking and ``None`` for no + timeout. Defaults to the value set in the constructor + of BufferedSocket. + + If the operation does not complete in *timeout* seconds, a + :exc:`Timeout` is raised. Much like the built-in + :class:`socket.socket`, if this method returns an empty string, + then the socket is closed and recv buffer is empty. Further + calls to recv will raise :exc:`socket.error`. + + """ + with self._recv_lock: + if timeout is _UNSET: + timeout = self.timeout + if flags: + raise ValueError("non-zero flags not supported: %r" % flags) + if len(self.rbuf) >= size: + data, self.rbuf = self.rbuf[:size], self.rbuf[size:] + return data + if self.rbuf: + ret, self.rbuf = self.rbuf, b'' + return ret + self.sock.settimeout(timeout) + try: + data = self.sock.recv(self._recvsize) + except socket.timeout: + raise Timeout(timeout) # check the rbuf attr for more + if len(data) > size: + data, self.rbuf = data[:size], data[size:] + return data + + def peek(self, size, timeout=_UNSET): + """Returns *size* bytes from the socket and/or internal buffer. Bytes + are retained in BufferedSocket's internal recv buffer. To only + see bytes in the recv buffer, use :meth:`getrecvbuffer`. + + Args: + size (int): The exact number of bytes to peek at + timeout (float): The timeout for this operation. Can be 0 for + nonblocking and None for no timeout. Defaults to the value + set in the constructor of BufferedSocket. + + If the appropriate number of bytes cannot be fetched from the + buffer and socket before *timeout* expires, then a + :exc:`Timeout` will be raised. If the connection is closed, a + :exc:`ConnectionClosed` will be raised. + """ + with self._recv_lock: + if len(self.rbuf) >= size: + return self.rbuf[:size] + data = self.recv_size(size, timeout=timeout) + self.rbuf = data + self.rbuf + return data + + def recv_close(self, timeout=_UNSET, maxsize=_UNSET): + """Receive until the connection is closed, up to *maxsize* bytes. If + more than *maxsize* bytes are received, raises :exc:`MessageTooLong`. + """ + # recv_close works by using recv_size to request maxsize data, + # and ignoring ConnectionClose, returning and clearing the + # internal buffer instead. It raises an exception if + # ConnectionClosed isn't raised. + with self._recv_lock: + if maxsize is _UNSET: + maxsize = self.maxsize + if maxsize is None: + maxsize = _RECV_LARGE_MAXSIZE + try: + recvd = self.recv_size(maxsize + 1, timeout) + except ConnectionClosed: + ret, self.rbuf = self.rbuf, b'' + else: + # put extra received bytes (now in rbuf) after recvd + self.rbuf = recvd + self.rbuf + size_read = min(maxsize, len(self.rbuf)) + raise MessageTooLong(size_read) # check receive buffer + return ret + + def recv_until(self, delimiter, timeout=_UNSET, maxsize=_UNSET, + with_delimiter=False): + """Receive until *delimiter* is found, *maxsize* bytes have been read, + or *timeout* is exceeded. + + Args: + delimiter (bytes): One or more bytes to be searched for + in the socket stream. + timeout (float): The timeout for this operation. Can be 0 for + nonblocking and None for no timeout. Defaults to the value + set in the constructor of BufferedSocket. + maxsize (int): The maximum size for the internal buffer. + Defaults to the value set in the constructor. + with_delimiter (bool): Whether or not to include the + delimiter in the output. ``False`` by default, but + ``True`` is useful in cases where one is simply + forwarding the messages. + + ``recv_until`` will raise the following exceptions: + + * :exc:`Timeout` if more than *timeout* seconds expire. + * :exc:`ConnectionClosed` if the underlying socket is closed + by the sending end. + * :exc:`MessageTooLong` if the delimiter is not found in the + first *maxsize* bytes. + * :exc:`socket.error` if operating in nonblocking mode + (*timeout* equal to 0), or if some unexpected socket error + occurs, such as operating on a closed socket. + + """ + with self._recv_lock: + if maxsize is _UNSET: + maxsize = self.maxsize + if maxsize is None: + maxsize = _RECV_LARGE_MAXSIZE + if timeout is _UNSET: + timeout = self.timeout + len_delimiter = len(delimiter) + + sock = self.sock + recvd = bytearray(self.rbuf) + start = time.time() + find_offset_start = 0 # becomes a negative index below + + if not timeout: # covers None (no timeout) and 0 (nonblocking) + sock.settimeout(timeout) + try: + while 1: + offset = recvd.find(delimiter, find_offset_start, maxsize) + if offset != -1: # str.find returns -1 when no match found + if with_delimiter: # include delimiter in return + offset += len_delimiter + rbuf_offset = offset + else: + rbuf_offset = offset + len_delimiter + break + elif len(recvd) > maxsize: + raise MessageTooLong(maxsize, delimiter) # see rbuf + if timeout: + cur_timeout = timeout - (time.time() - start) + if cur_timeout <= 0.0: + raise socket.timeout() + sock.settimeout(cur_timeout) + nxt = sock.recv(self._recvsize) + if not nxt: + args = (len(recvd), delimiter) + msg = ('connection closed after reading %s bytes' + ' without finding symbol: %r' % args) + raise ConnectionClosed(msg) # check the recv buffer + recvd.extend(nxt) + find_offset_start = -len(nxt) - len_delimiter + 1 + except socket.timeout: + self.rbuf = bytes(recvd) + msg = ('read %s bytes without finding delimiter: %r' + % (len(recvd), delimiter)) + raise Timeout(timeout, msg) # check the recv buffer + except Exception: + self.rbuf = bytes(recvd) + raise + val, self.rbuf = bytes(recvd[:offset]), bytes(recvd[rbuf_offset:]) + return val + + def recv_size(self, size, timeout=_UNSET): + """Read off of the internal buffer, then off the socket, until + *size* bytes have been read. + + Args: + size (int): number of bytes to read before returning. + timeout (float): The timeout for this operation. Can be 0 for + nonblocking and None for no timeout. Defaults to the value + set in the constructor of BufferedSocket. + + If the appropriate number of bytes cannot be fetched from the + buffer and socket before *timeout* expires, then a + :exc:`Timeout` will be raised. If the connection is closed, a + :exc:`ConnectionClosed` will be raised. + """ + with self._recv_lock: + if timeout is _UNSET: + timeout = self.timeout + chunks = [] + total_bytes = 0 + try: + start = time.time() + self.sock.settimeout(timeout) + nxt = self.rbuf or self.sock.recv(self._recvsize) + while nxt: + total_bytes += len(nxt) + if total_bytes >= size: + break + chunks.append(nxt) + if timeout: + cur_timeout = timeout - (time.time() - start) + if cur_timeout <= 0.0: + raise socket.timeout() + self.sock.settimeout(cur_timeout) + nxt = self.sock.recv(self._recvsize) + else: + msg = ('connection closed after reading %s of %s requested' + ' bytes' % (total_bytes, size)) + raise ConnectionClosed(msg) # check recv buffer + except socket.timeout: + self.rbuf = b''.join(chunks) + msg = f'read {total_bytes} of {size} bytes' + raise Timeout(timeout, msg) # check recv buffer + except Exception: + # received data is still buffered in the case of errors + self.rbuf = b''.join(chunks) + raise + extra_bytes = total_bytes - size + if extra_bytes: + last, self.rbuf = nxt[:-extra_bytes], nxt[-extra_bytes:] + else: + last, self.rbuf = nxt, b'' + chunks.append(last) + return b''.join(chunks) + + def send(self, data, flags=0, timeout=_UNSET): + """Send the contents of the internal send buffer, as well as *data*, + to the receiving end of the connection. Returns the total + number of bytes sent. If no exception is raised, all of *data* was + sent and the internal send buffer is empty. + + Args: + data (bytes): The bytes to send. + flags (int): Kept for API compatibility with sockets. Only + the default 0 is valid. + timeout (float): The timeout for this operation. Can be 0 for + nonblocking and None for no timeout. Defaults to the value + set in the constructor of BufferedSocket. + + Will raise :exc:`Timeout` if the send operation fails to + complete before *timeout*. In the event of an exception, use + :meth:`BufferedSocket.getsendbuffer` to see which data was + unsent. + """ + with self._send_lock: + if timeout is _UNSET: + timeout = self.timeout + if flags: + raise ValueError("non-zero flags not supported") + sbuf = self.sbuf + sbuf.append(data) + if len(sbuf) > 1: + sbuf[:] = [b''.join([s for s in sbuf if s])] + self.sock.settimeout(timeout) + start, total_sent = time.time(), 0 + try: + while sbuf[0]: + sent = self.sock.send(sbuf[0]) + total_sent += sent + sbuf[0] = sbuf[0][sent:] + if timeout: + cur_timeout = timeout - (time.time() - start) + if cur_timeout <= 0.0: + raise socket.timeout() + self.sock.settimeout(cur_timeout) + except socket.timeout: + raise Timeout(timeout, '%s bytes unsent' % len(sbuf[0])) + return total_sent + + def sendall(self, data, flags=0, timeout=_UNSET): + """A passthrough to :meth:`~BufferedSocket.send`, retained for + parallelism to the :class:`socket.socket` API. + """ + return self.send(data, flags, timeout) + + def flush(self): + "Send the contents of the internal send buffer." + with self._send_lock: + self.send(b'') + return + + def buffer(self, data): + "Buffer *data* bytes for the next send operation." + with self._send_lock: + self.sbuf.append(data) + return + + # # # + # # # Passing through some socket basics + # # # + + def getsockname(self): + """Convenience function to return the wrapped socket's own address. + See :meth:`socket.getsockname` for more details. + """ + return self.sock.getsockname() + + def getpeername(self): + """Convenience function to return the remote address to which the + wrapped socket is connected. See :meth:`socket.getpeername` + for more details. + """ + return self.sock.getpeername() + + def getsockopt(self, level, optname, buflen=None): + """Convenience function passing through to the wrapped socket's + :meth:`socket.getsockopt`. + """ + args = (level, optname) + if buflen is not None: + args += (buflen,) + return self.sock.getsockopt(*args) + + def setsockopt(self, level, optname, value): + """Convenience function passing through to the wrapped socket's + :meth:`socket.setsockopt`. + """ + return self.sock.setsockopt(level, optname, value) + + @property + def type(self): + """A passthrough to the wrapped socket's type. Valid usages should + only ever see :data:`socket.SOCK_STREAM`. + """ + return self.sock.type + + @property + def family(self): + """A passthrough to the wrapped socket's family. BufferedSocket + supports all widely-used families, so this read-only attribute + can be one of :data:`socket.AF_INET` for IP, + :data:`socket.AF_INET6` for IPv6, and :data:`socket.AF_UNIX` + for UDS. + """ + return self.sock.family + + @property + def proto(self): + """A passthrough to the wrapped socket's protocol. The ``proto`` + attribute is very rarely used, so it's always 0, meaning "the + default" protocol. Pretty much all the practical information + is in :attr:`~BufferedSocket.type` and + :attr:`~BufferedSocket.family`, so you can go back to never + thinking about this. + """ + return self.sock.proto + + # # # + # # # Now for some more advanced interpretations of the builtin socket + # # # + + def fileno(self): + """Returns the file descriptor of the wrapped socket. -1 if it has + been closed on this end. + + Note that this makes the BufferedSocket selectable, i.e., + usable for operating system event loops without any external + libraries. Keep in mind that the operating system cannot know + about data in BufferedSocket's internal buffer. Exercise + discipline with calling ``recv*`` functions. + """ + return self.sock.fileno() + + def close(self): + """Closes the wrapped socket, and empties the internal buffers. The + send buffer is not flushed automatically, so if you have been + calling :meth:`~BufferedSocket.buffer`, be sure to call + :meth:`~BufferedSocket.flush` before calling this + method. After calling this method, future socket operations + will raise :exc:`socket.error`. + """ + with self._recv_lock: + with self._send_lock: + self.rbuf = b'' + self.rbuf_unconsumed = self.rbuf + self.sbuf[:] = [] + self.sock.close() + return + + def shutdown(self, how): + """Convenience method which passes through to the wrapped socket's + :meth:`~socket.shutdown`. Semantics vary by platform, so no + special internal handling is done with the buffers. This + method exists to facilitate the most common usage, wherein a + full ``shutdown`` is followed by a + :meth:`~BufferedSocket.close`. Developers requiring more + support, please open `an issue`_. + + .. _an issue: https://github.com/mahmoud/boltons/issues + """ + with self._recv_lock: + with self._send_lock: + self.sock.shutdown(how) + return + + # end BufferedSocket + + +class Error(socket.error): + """A subclass of :exc:`socket.error` from which all other + ``socketutils`` exceptions inherit. + + When using :class:`BufferedSocket` and other ``socketutils`` + types, generally you want to catch one of the specific exception + types below, or :exc:`socket.error`. + """ + pass + + +class ConnectionClosed(Error): + """Raised when receiving and the connection is unexpectedly closed + from the sending end. Raised from :class:`BufferedSocket`'s + :meth:`~BufferedSocket.peek`, :meth:`~BufferedSocket.recv_until`, + and :meth:`~BufferedSocket.recv_size`, and never from its + :meth:`~BufferedSocket.recv` or + :meth:`~BufferedSocket.recv_close`. + """ + pass + + +class MessageTooLong(Error): + """Raised from :meth:`BufferedSocket.recv_until` and + :meth:`BufferedSocket.recv_closed` when more than *maxsize* bytes are + read without encountering the delimiter or a closed connection, + respectively. + """ + def __init__(self, bytes_read=None, delimiter=None): + msg = 'message exceeded maximum size' + if bytes_read is not None: + msg += f'. {bytes_read} bytes read' + if delimiter is not None: + msg += f'. Delimiter not found: {delimiter!r}' + super().__init__(msg) + + +class Timeout(socket.timeout, Error): + """Inheriting from :exc:`socket.timeout`, Timeout is used to indicate + when a socket operation did not complete within the time + specified. Raised from any of :class:`BufferedSocket`'s ``recv`` + methods. + """ + def __init__(self, timeout, extra=""): + msg = 'socket operation timed out' + if timeout is not None: + msg += ' after %sms.' % (timeout * 1000) + if extra: + msg += ' ' + extra + super().__init__(msg) + + +class NetstringSocket: + """ + Reads and writes using the netstring protocol. + + More info: https://en.wikipedia.org/wiki/Netstring + Even more info: http://cr.yp.to/proto/netstrings.txt + """ + def __init__(self, sock, timeout=DEFAULT_TIMEOUT, maxsize=DEFAULT_MAXSIZE): + self.bsock = BufferedSocket(sock) + self.timeout = timeout + self.maxsize = maxsize + self._msgsize_maxsize = len(str(maxsize)) + 1 # len(str()) == log10 + + def fileno(self): + return self.bsock.fileno() + + def settimeout(self, timeout): + self.timeout = timeout + + def setmaxsize(self, maxsize): + self.maxsize = maxsize + self._msgsize_maxsize = self._calc_msgsize_maxsize(maxsize) + + def _calc_msgsize_maxsize(self, maxsize): + return len(str(maxsize)) + 1 # len(str()) == log10 + + def read_ns(self, timeout=_UNSET, maxsize=_UNSET): + if timeout is _UNSET: + timeout = self.timeout + + if maxsize is _UNSET: + maxsize = self.maxsize + msgsize_maxsize = self._msgsize_maxsize + else: + msgsize_maxsize = self._calc_msgsize_maxsize(maxsize) + + size_prefix = self.bsock.recv_until(b':', + timeout=timeout, + maxsize=msgsize_maxsize) + try: + size = int(size_prefix) + except ValueError: + raise NetstringInvalidSize('netstring message size must be valid' + ' integer, not %r' % size_prefix) + + if size > maxsize: + raise NetstringMessageTooLong(size, maxsize) + payload = self.bsock.recv_size(size) + if self.bsock.recv(1) != b',': + raise NetstringProtocolError("expected trailing ',' after message") + + return payload + + def write_ns(self, payload): + size = len(payload) + if size > self.maxsize: + raise NetstringMessageTooLong(size, self.maxsize) + data = str(size).encode('ascii') + b':' + payload + b',' + self.bsock.send(data) + + +class NetstringProtocolError(Error): + "Base class for all of socketutils' Netstring exception types." + pass + + +class NetstringInvalidSize(NetstringProtocolError): + """NetstringInvalidSize is raised when the ``:``-delimited size prefix + of the message does not contain a valid integer. + + Message showing valid size:: + + 5:hello, + + Here the ``5`` is the size. Anything in this prefix position that + is not parsable as a Python integer (i.e., :class:`int`) will raise + this exception. + """ + def __init__(self, msg): + super().__init__(msg) + + +class NetstringMessageTooLong(NetstringProtocolError): + """NetstringMessageTooLong is raised when the size prefix contains a + valid integer, but that integer is larger than the + :class:`NetstringSocket`'s configured *maxsize*. + + When this exception is raised, it's recommended to simply close + the connection instead of trying to recover. + """ + def __init__(self, size, maxsize): + msg = ('netstring message length exceeds configured maxsize: %s > %s' + % (size, maxsize)) + super().__init__(msg) + + +""" +attrs worth adding/passing through: + + +properties: type, proto + +For its main functionality, BufferedSocket can wrap any object that +has the following methods: + + - gettimeout() + - settimeout() + - recv(size) + - send(data) + +The following methods are passed through: + +... + +""" + +# TODO: buffered socket check socket.type == SOCK_STREAM? +# TODO: make recv_until support taking a regex +# TODO: including the delimiter in the recv_until return is not +# necessary, as ConnectionClosed differentiates empty messages +# from socket closes. diff --git a/data/miniconda3/lib/python3.13/site-packages/boltons/statsutils.py b/data/miniconda3/lib/python3.13/site-packages/boltons/statsutils.py new file mode 100644 index 0000000000000000000000000000000000000000..36a82230d80f2b6e32fcf07851da2aa2c4d7132b --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/boltons/statsutils.py @@ -0,0 +1,814 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# * The names of the contributors may not be used to endorse or +# promote products derived from this software without specific +# prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""``statsutils`` provides tools aimed primarily at descriptive +statistics for data analysis, such as :func:`mean` (average), +:func:`median`, :func:`variance`, and many others, + +The :class:`Stats` type provides all the main functionality of the +``statsutils`` module. A :class:`Stats` object wraps a given dataset, +providing all statistical measures as property attributes. These +attributes cache their results, which allows efficient computation of +multiple measures, as many measures rely on other measures. For +example, relative standard deviation (:attr:`Stats.rel_std_dev`) +relies on both the mean and standard deviation. The Stats object +caches those results so no rework is done. + +The :class:`Stats` type's attributes have module-level counterparts for +convenience when the computation reuse advantages do not apply. + +>>> stats = Stats(range(42)) +>>> stats.mean +20.5 +>>> mean(range(42)) +20.5 + +Statistics is a large field, and ``statsutils`` is focused on a few +basic techniques that are useful in software. The following is a brief +introduction to those techniques. For a more in-depth introduction, +`Statistics for Software +`_, +an article I wrote on the topic. It introduces key terminology vital +to effective usage of statistics. + +Statistical moments +------------------- + +Python programmers are probably familiar with the concept of the +*mean* or *average*, which gives a rough quantitiative middle value by +which a sample can be can be generalized. However, the mean is just +the first of four `moment`_-based measures by which a sample or +distribution can be measured. + +The four `Standardized moments`_ are: + + 1. `Mean`_ - :func:`mean` - theoretical middle value + 2. `Variance`_ - :func:`variance` - width of value dispersion + 3. `Skewness`_ - :func:`skewness` - symmetry of distribution + 4. `Kurtosis`_ - :func:`kurtosis` - "peakiness" or "long-tailed"-ness + +For more information check out `the Moment article on Wikipedia`_. + +.. _moment: https://en.wikipedia.org/wiki/Moment_(mathematics) +.. _Standardized moments: https://en.wikipedia.org/wiki/Standardized_moment +.. _Mean: https://en.wikipedia.org/wiki/Mean +.. _Variance: https://en.wikipedia.org/wiki/Variance +.. _Skewness: https://en.wikipedia.org/wiki/Skewness +.. _Kurtosis: https://en.wikipedia.org/wiki/Kurtosis +.. _the Moment article on Wikipedia: https://en.wikipedia.org/wiki/Moment_(mathematics) + +Keep in mind that while these moments can give a bit more insight into +the shape and distribution of data, they do not guarantee a complete +picture. Wildly different datasets can have the same values for all +four moments, so generalize wisely. + +Robust statistics +----------------- + +Moment-based statistics are notorious for being easily skewed by +outliers. The whole field of robust statistics aims to mitigate this +dilemma. ``statsutils`` also includes several robust statistical methods: + + * `Median`_ - The middle value of a sorted dataset + * `Trimean`_ - Another robust measure of the data's central tendency + * `Median Absolute Deviation`_ (MAD) - A robust measure of + variability, a natural counterpart to :func:`variance`. + * `Trimming`_ - Reducing a dataset to only the middle majority of + data is a simple way of making other estimators more robust. + +.. _Median: https://en.wikipedia.org/wiki/Median +.. _Trimean: https://en.wikipedia.org/wiki/Trimean +.. _Median Absolute Deviation: https://en.wikipedia.org/wiki/Median_absolute_deviation +.. _Trimming: https://en.wikipedia.org/wiki/Trimmed_estimator + + +Online and Offline Statistics +----------------------------- + +Unrelated to computer networking, `online`_ statistics involve +calculating statistics in a `streaming`_ fashion, without all the data +being available. The :class:`Stats` type is meant for the more +traditional offline statistics when all the data is available. For +pure-Python online statistics accumulators, look at the `Lithoxyl`_ +system instrumentation package. + +.. _Online: https://en.wikipedia.org/wiki/Online_algorithm +.. _streaming: https://en.wikipedia.org/wiki/Streaming_algorithm +.. _Lithoxyl: https://github.com/mahmoud/lithoxyl + +""" + + +import bisect +from math import floor, ceil +from collections import Counter + + +class _StatsProperty: + def __init__(self, name, func): + self.name = name + self.func = func + self.internal_name = '_' + name + + doc = func.__doc__ or '' + pre_doctest_doc, _, _ = doc.partition('>>>') + self.__doc__ = pre_doctest_doc + + def __get__(self, obj, objtype=None): + if obj is None: + return self + if not obj.data: + return obj.default + try: + return getattr(obj, self.internal_name) + except AttributeError: + setattr(obj, self.internal_name, self.func(obj)) + return getattr(obj, self.internal_name) + + +class Stats: + """The ``Stats`` type is used to represent a group of unordered + statistical datapoints for calculations such as mean, median, and + variance. + + Args: + + data (list): List or other iterable containing numeric values. + default (float): A value to be returned when a given + statistical measure is not defined. 0.0 by default, but + ``float('nan')`` is appropriate for stricter applications. + use_copy (bool): By default Stats objects copy the initial + data into a new list to avoid issues with + modifications. Pass ``False`` to disable this behavior. + is_sorted (bool): Presorted data can skip an extra sorting + step for a little speed boost. Defaults to False. + + """ + def __init__(self, data, default=0.0, use_copy=True, is_sorted=False): + self._use_copy = use_copy + self._is_sorted = is_sorted + if use_copy: + self.data = list(data) + else: + self.data = data + + self.default = default + cls = self.__class__ + self._prop_attr_names = [a for a in dir(self) + if isinstance(getattr(cls, a, None), + _StatsProperty)] + self._pearson_precision = 0 + + def __len__(self): + return len(self.data) + + def __iter__(self): + return iter(self.data) + + def _get_sorted_data(self): + """When using a copy of the data, it's better to have that copy be + sorted, but we do it lazily using this method, in case no + sorted measures are used. I.e., if median is never called, + sorting would be a waste. + + When not using a copy, it's presumed that all optimizations + are on the user. + """ + if not self._use_copy: + return sorted(self.data) + elif not self._is_sorted: + self.data.sort() + return self.data + + def clear_cache(self): + """``Stats`` objects automatically cache intermediary calculations + that can be reused. For instance, accessing the ``std_dev`` + attribute after the ``variance`` attribute will be + significantly faster for medium-to-large datasets. + + If you modify the object by adding additional data points, + call this function to have the cached statistics recomputed. + + """ + for attr_name in self._prop_attr_names: + attr_name = getattr(self.__class__, attr_name).internal_name + if not hasattr(self, attr_name): + continue + delattr(self, attr_name) + return + + def _calc_count(self): + """The number of items in this Stats object. Returns the same as + :func:`len` on a Stats object, but provided for pandas terminology + parallelism. + + >>> Stats(range(20)).count + 20 + """ + return len(self.data) + count = _StatsProperty('count', _calc_count) + + def _calc_mean(self): + """ + The arithmetic mean, or "average". Sum of the values divided by + the number of values. + + >>> mean(range(20)) + 9.5 + >>> mean(list(range(19)) + [949]) # 949 is an arbitrary outlier + 56.0 + """ + return sum(self.data, 0.0) / len(self.data) + mean = _StatsProperty('mean', _calc_mean) + + def _calc_max(self): + """ + The maximum value present in the data. + + >>> Stats([2, 1, 3]).max + 3 + """ + if self._is_sorted: + return self.data[-1] + return max(self.data) + max = _StatsProperty('max', _calc_max) + + def _calc_min(self): + """ + The minimum value present in the data. + + >>> Stats([2, 1, 3]).min + 1 + """ + if self._is_sorted: + return self.data[0] + return min(self.data) + min = _StatsProperty('min', _calc_min) + + def _calc_median(self): + """ + The median is either the middle value or the average of the two + middle values of a sample. Compared to the mean, it's generally + more resilient to the presence of outliers in the sample. + + >>> median([2, 1, 3]) + 2 + >>> median(range(97)) + 48 + >>> median(list(range(96)) + [1066]) # 1066 is an arbitrary outlier + 48 + """ + return self._get_quantile(self._get_sorted_data(), 0.5) + median = _StatsProperty('median', _calc_median) + + def _calc_iqr(self): + """Inter-quartile range (IQR) is the difference between the 75th + percentile and 25th percentile. IQR is a robust measure of + dispersion, like standard deviation, but safer to compare + between datasets, as it is less influenced by outliers. + + >>> iqr([1, 2, 3, 4, 5]) + 2 + >>> iqr(range(1001)) + 500 + """ + return self.get_quantile(0.75) - self.get_quantile(0.25) + iqr = _StatsProperty('iqr', _calc_iqr) + + def _calc_trimean(self): + """The trimean is a robust measure of central tendency, like the + median, that takes the weighted average of the median and the + upper and lower quartiles. + + >>> trimean([2, 1, 3]) + 2.0 + >>> trimean(range(97)) + 48.0 + >>> trimean(list(range(96)) + [1066]) # 1066 is an arbitrary outlier + 48.0 + + """ + sorted_data = self._get_sorted_data() + gq = lambda q: self._get_quantile(sorted_data, q) + return (gq(0.25) + (2 * gq(0.5)) + gq(0.75)) / 4.0 + trimean = _StatsProperty('trimean', _calc_trimean) + + def _calc_variance(self): + """\ + Variance is the average of the squares of the difference between + each value and the mean. + + >>> variance(range(97)) + 784.0 + """ + global mean # defined elsewhere in this file + return mean(self._get_pow_diffs(2)) + variance = _StatsProperty('variance', _calc_variance) + + def _calc_std_dev(self): + """\ + Standard deviation. Square root of the variance. + + >>> std_dev(range(97)) + 28.0 + """ + return self.variance ** 0.5 + std_dev = _StatsProperty('std_dev', _calc_std_dev) + + def _calc_median_abs_dev(self): + """\ + Median Absolute Deviation is a robust measure of statistical + dispersion: http://en.wikipedia.org/wiki/Median_absolute_deviation + + >>> median_abs_dev(range(97)) + 24.0 + """ + global median # defined elsewhere in this file + sorted_vals = sorted(self.data) + x = float(median(sorted_vals)) + return median([abs(x - v) for v in sorted_vals]) + median_abs_dev = _StatsProperty('median_abs_dev', _calc_median_abs_dev) + mad = median_abs_dev # convenience + + def _calc_rel_std_dev(self): + """\ + Standard deviation divided by the absolute value of the average. + + http://en.wikipedia.org/wiki/Relative_standard_deviation + + >>> print('%1.3f' % rel_std_dev(range(97))) + 0.583 + """ + abs_mean = abs(self.mean) + if abs_mean: + return self.std_dev / abs_mean + else: + return self.default + rel_std_dev = _StatsProperty('rel_std_dev', _calc_rel_std_dev) + + def _calc_skewness(self): + """\ + Indicates the asymmetry of a curve. Positive values mean the bulk + of the values are on the left side of the average and vice versa. + + http://en.wikipedia.org/wiki/Skewness + + See the module docstring for more about statistical moments. + + >>> skewness(range(97)) # symmetrical around 48.0 + 0.0 + >>> left_skewed = skewness(list(range(97)) + list(range(10))) + >>> right_skewed = skewness(list(range(97)) + list(range(87, 97))) + >>> round(left_skewed, 3), round(right_skewed, 3) + (0.114, -0.114) + """ + data, s_dev = self.data, self.std_dev + if len(data) > 1 and s_dev > 0: + return (sum(self._get_pow_diffs(3)) / + float((len(data) - 1) * (s_dev ** 3))) + else: + return self.default + skewness = _StatsProperty('skewness', _calc_skewness) + + def _calc_kurtosis(self): + """\ + Indicates how much data is in the tails of the distribution. The + result is always positive, with the normal "bell-curve" + distribution having a kurtosis of 3. + + http://en.wikipedia.org/wiki/Kurtosis + + See the module docstring for more about statistical moments. + + >>> kurtosis(range(9)) + 1.99125 + + With a kurtosis of 1.99125, [0, 1, 2, 3, 4, 5, 6, 7, 8] is more + centrally distributed than the normal curve. + """ + data, s_dev = self.data, self.std_dev + if len(data) > 1 and s_dev > 0: + return (sum(self._get_pow_diffs(4)) / + float((len(data) - 1) * (s_dev ** 4))) + else: + return 0.0 + kurtosis = _StatsProperty('kurtosis', _calc_kurtosis) + + def _calc_pearson_type(self): + precision = self._pearson_precision + skewness = self.skewness + kurtosis = self.kurtosis + beta1 = skewness ** 2.0 + beta2 = kurtosis * 1.0 + + # TODO: range checks? + + c0 = (4 * beta2) - (3 * beta1) + c1 = skewness * (beta2 + 3) + c2 = (2 * beta2) - (3 * beta1) - 6 + + if round(c1, precision) == 0: + if round(beta2, precision) == 3: + return 0 # Normal + else: + if beta2 < 3: + return 2 # Symmetric Beta + elif beta2 > 3: + return 7 + elif round(c2, precision) == 0: + return 3 # Gamma + else: + k = c1 ** 2 / (4 * c0 * c2) + if k < 0: + return 1 # Beta + raise RuntimeError('missed a spot') + pearson_type = _StatsProperty('pearson_type', _calc_pearson_type) + + @staticmethod + def _get_quantile(sorted_data, q): + data, n = sorted_data, len(sorted_data) + idx = q / 1.0 * (n - 1) + idx_f, idx_c = int(floor(idx)), int(ceil(idx)) + if idx_f == idx_c: + return data[idx_f] + return (data[idx_f] * (idx_c - idx)) + (data[idx_c] * (idx - idx_f)) + + def get_quantile(self, q): + """Get a quantile from the dataset. Quantiles are floating point + values between ``0.0`` and ``1.0``, with ``0.0`` representing + the minimum value in the dataset and ``1.0`` representing the + maximum. ``0.5`` represents the median: + + >>> Stats(range(100)).get_quantile(0.5) + 49.5 + """ + q = float(q) + if not 0.0 <= q <= 1.0: + raise ValueError('expected q between 0.0 and 1.0, not %r' % q) + elif not self.data: + return self.default + return self._get_quantile(self._get_sorted_data(), q) + + def get_zscore(self, value): + """Get the z-score for *value* in the group. If the standard deviation + is 0, 0 inf or -inf will be returned to indicate whether the value is + equal to, greater than or below the group's mean. + """ + mean = self.mean + if self.std_dev == 0: + if value == mean: + return 0 + if value > mean: + return float('inf') + if value < mean: + return float('-inf') + return (float(value) - mean) / self.std_dev + + def trim_relative(self, amount=0.15): + """A utility function used to cut a proportion of values off each end + of a list of values. This has the effect of limiting the + effect of outliers. + + Args: + amount (float): A value between 0.0 and 0.5 to trim off of + each side of the data. + + .. note: + + This operation modifies the data in-place. It does not + make or return a copy. + + """ + trim = float(amount) + if not 0.0 <= trim < 0.5: + raise ValueError('expected amount between 0.0 and 0.5, not %r' + % trim) + size = len(self.data) + size_diff = int(size * trim) + if size_diff == 0.0: + return + self.data = self._get_sorted_data()[size_diff:-size_diff] + self.clear_cache() + + def _get_pow_diffs(self, power): + """ + A utility function used for calculating statistical moments. + """ + m = self.mean + return [(v - m) ** power for v in self.data] + + def _get_bin_bounds(self, count=None, with_max=False): + if not self.data: + return [0.0] # TODO: raise? + + data = self.data + len_data, min_data, max_data = len(data), min(data), max(data) + + if len_data < 4: + if not count: + count = len_data + dx = (max_data - min_data) / float(count) + bins = [min_data + (dx * i) for i in range(count)] + elif count is None: + # freedman algorithm for fixed-width bin selection + q25, q75 = self.get_quantile(0.25), self.get_quantile(0.75) + dx = 2 * (q75 - q25) / (len_data ** (1 / 3.0)) + bin_count = max(1, int(ceil((max_data - min_data) / dx))) + bins = [min_data + (dx * i) for i in range(bin_count + 1)] + bins = [b for b in bins if b < max_data] + else: + dx = (max_data - min_data) / float(count) + bins = [min_data + (dx * i) for i in range(count)] + + if with_max: + bins.append(float(max_data)) + + return bins + + def get_histogram_counts(self, bins=None, **kw): + """Produces a list of ``(bin, count)`` pairs comprising a histogram of + the Stats object's data, using fixed-width bins. See + :meth:`Stats.format_histogram` for more details. + + Args: + bins (int): maximum number of bins, or list of + floating-point bin boundaries. Defaults to the output of + Freedman's algorithm. + bin_digits (int): Number of digits used to round down the + bin boundaries. Defaults to 1. + + The output of this method can be stored and/or modified, and + then passed to :func:`statsutils.format_histogram_counts` to + achieve the same text formatting as the + :meth:`~Stats.format_histogram` method. This can be useful for + snapshotting over time. + """ + bin_digits = int(kw.pop('bin_digits', 1)) + if kw: + raise TypeError('unexpected keyword arguments: %r' % kw.keys()) + + if not bins: + bins = self._get_bin_bounds() + else: + try: + bin_count = int(bins) + except TypeError: + try: + bins = [float(x) for x in bins] + except Exception: + raise ValueError('bins expected integer bin count or list' + ' of float bin boundaries, not %r' % bins) + if self.min < bins[0]: + bins = [self.min] + bins + else: + bins = self._get_bin_bounds(bin_count) + + # floor and ceil really should have taken ndigits, like round() + round_factor = 10.0 ** bin_digits + bins = [floor(b * round_factor) / round_factor for b in bins] + bins = sorted(set(bins)) + + idxs = [bisect.bisect(bins, d) - 1 for d in self.data] + count_map = Counter(idxs) + + bin_counts = [(b, count_map.get(i, 0)) for i, b in enumerate(bins)] + + return bin_counts + + def format_histogram(self, bins=None, **kw): + """Produces a textual histogram of the data, using fixed-width bins, + allowing for simple visualization, even in console environments. + + >>> data = list(range(20)) + list(range(5, 15)) + [10] + >>> print(Stats(data).format_histogram(width=30)) + 0.0: 5 ######### + 4.4: 8 ############### + 8.9: 11 #################### + 13.3: 5 ######### + 17.8: 2 #### + + In this histogram, five values are between 0.0 and 4.4, eight + are between 4.4 and 8.9, and two values lie between 17.8 and + the max. + + You can specify the number of bins, or provide a list of + bin boundaries themselves. If no bins are provided, as in the + example above, `Freedman's algorithm`_ for bin selection is + used. + + Args: + bins (int): Maximum number of bins for the + histogram. Also accepts a list of floating-point + bin boundaries. If the minimum boundary is still + greater than the minimum value in the data, that + boundary will be implicitly added. Defaults to the bin + boundaries returned by `Freedman's algorithm`_. + bin_digits (int): Number of digits to round each bin + to. Note that bins are always rounded down to avoid + clipping any data. Defaults to 1. + width (int): integer number of columns in the longest line + in the histogram. Defaults to console width on Python + 3.3+, or 80 if that is not available. + format_bin (callable): Called on each bin to create a + label for the final output. Use this function to add + units, such as "ms" for milliseconds. + + Should you want something more programmatically reusable, see + the :meth:`~Stats.get_histogram_counts` method, the output of + is used by format_histogram. The :meth:`~Stats.describe` + method is another useful summarization method, albeit less + visual. + + .. _Freedman's algorithm: https://en.wikipedia.org/wiki/Freedman%E2%80%93Diaconis_rule + """ + width = kw.pop('width', None) + format_bin = kw.pop('format_bin', None) + bin_counts = self.get_histogram_counts(bins=bins, **kw) + return format_histogram_counts(bin_counts, + width=width, + format_bin=format_bin) + + def describe(self, quantiles=None, format=None): + """Provides standard summary statistics for the data in the Stats + object, in one of several convenient formats. + + Args: + quantiles (list): A list of numeric values to use as + quantiles in the resulting summary. All values must be + 0.0-1.0, with 0.5 representing the median. Defaults to + ``[0.25, 0.5, 0.75]``, representing the standard + quartiles. + format (str): Controls the return type of the function, + with one of three valid values: ``"dict"`` gives back + a :class:`dict` with the appropriate keys and + values. ``"list"`` is a list of key-value pairs in an + order suitable to pass to an OrderedDict or HTML + table. ``"text"`` converts the values to text suitable + for printing, as seen below. + + Here is the information returned by a default ``describe``, as + presented in the ``"text"`` format: + + >>> stats = Stats(range(1, 8)) + >>> print(stats.describe(format='text')) + count: 7 + mean: 4.0 + std_dev: 2.0 + mad: 2.0 + min: 1 + 0.25: 2.5 + 0.5: 4 + 0.75: 5.5 + max: 7 + + For more advanced descriptive statistics, check out my blog + post on the topic `Statistics for Software + `_. + + """ + if format is None: + format = 'dict' + elif format not in ('dict', 'list', 'text'): + raise ValueError('invalid format for describe,' + ' expected one of "dict"/"list"/"text", not %r' + % format) + quantiles = quantiles or [0.25, 0.5, 0.75] + q_items = [] + for q in quantiles: + q_val = self.get_quantile(q) + q_items.append((str(q), q_val)) + + items = [('count', self.count), + ('mean', self.mean), + ('std_dev', self.std_dev), + ('mad', self.mad), + ('min', self.min)] + + items.extend(q_items) + items.append(('max', self.max)) + if format == 'dict': + ret = dict(items) + elif format == 'list': + ret = items + elif format == 'text': + ret = '\n'.join(['{}{}'.format((label + ':').ljust(10), val) + for label, val in items]) + return ret + + +def describe(data, quantiles=None, format=None): + """A convenience function to get standard summary statistics useful + for describing most data. See :meth:`Stats.describe` for more + details. + + >>> print(describe(range(7), format='text')) + count: 7 + mean: 3.0 + std_dev: 2.0 + mad: 2.0 + min: 0 + 0.25: 1.5 + 0.5: 3 + 0.75: 4.5 + max: 6 + + See :meth:`Stats.format_histogram` for another very useful + summarization that uses textual visualization. + """ + return Stats(data).describe(quantiles=quantiles, format=format) + + +def _get_conv_func(attr_name): + def stats_helper(data, default=0.0): + return getattr(Stats(data, default=default, use_copy=False), + attr_name) + return stats_helper + + +for attr_name, attr in list(Stats.__dict__.items()): + if isinstance(attr, _StatsProperty): + if attr_name in ('max', 'min', 'count'): # don't shadow builtins + continue + if attr_name in ('mad',): # convenience aliases + continue + func = _get_conv_func(attr_name) + func.__doc__ = attr.func.__doc__ + globals()[attr_name] = func + delattr(Stats, '_calc_' + attr_name) +# cleanup +del attr +del attr_name +del func + + +def format_histogram_counts(bin_counts, width=None, format_bin=None): + """The formatting logic behind :meth:`Stats.format_histogram`, which + takes the output of :meth:`Stats.get_histogram_counts`, and passes + them to this function. + + Args: + bin_counts (list): A list of bin values to counts. + width (int): Number of character columns in the text output, + defaults to 80 or console width in Python 3.3+. + format_bin (callable): Used to convert bin values into string + labels. + """ + lines = [] + if not format_bin: + format_bin = lambda v: v + if not width: + try: + import shutil # python 3 convenience + width = shutil.get_terminal_size()[0] + except Exception: + width = 80 + + bins = [b for b, _ in bin_counts] + count_max = max([count for _, count in bin_counts]) + count_cols = len(str(count_max)) + + labels = ['%s' % format_bin(b) for b in bins] + label_cols = max([len(l) for l in labels]) + tmp_line = '{}: {} #'.format('x' * label_cols, count_max) + + bar_cols = max(width - len(tmp_line), 3) + line_k = float(bar_cols) / count_max + tmpl = "{label:>{label_cols}}: {count:>{count_cols}} {bar}" + for label, (bin_val, count) in zip(labels, bin_counts): + bar_len = int(round(count * line_k)) + bar = ('#' * bar_len) or '|' + line = tmpl.format(label=label, + label_cols=label_cols, + count=count, + count_cols=count_cols, + bar=bar) + lines.append(line) + + return '\n'.join(lines) diff --git a/data/miniconda3/lib/python3.13/site-packages/boltons/strutils.py b/data/miniconda3/lib/python3.13/site-packages/boltons/strutils.py new file mode 100644 index 0000000000000000000000000000000000000000..1d43f2b0a1441a487a42e1885545a9fe531d5764 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/boltons/strutils.py @@ -0,0 +1,1289 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# * The names of the contributors may not be used to endorse or +# promote products derived from this software without specific +# prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""So much practical programming involves string manipulation, which +Python readily accommodates. Still, there are dozens of basic and +common capabilities missing from the standard library, several of them +provided by ``strutils``. +""" + + +import builtins +import re +import sys +import uuid +import zlib +import string +import unicodedata +import collections +from collections.abc import Mapping +from gzip import GzipFile +from html.parser import HTMLParser +from html import entities as htmlentitydefs +from io import BytesIO as StringIO + + +__all__ = ['camel2under', 'under2camel', 'slugify', 'split_punct_ws', + 'unit_len', 'ordinalize', 'cardinalize', 'pluralize', 'singularize', + 'asciify', 'is_ascii', 'is_uuid', 'html2text', 'strip_ansi', + 'bytes2human', 'find_hashtags', 'a10n', 'gzip_bytes', 'gunzip_bytes', + 'iter_splitlines', 'indent', 'escape_shell_args', + 'args2cmd', 'args2sh', 'parse_int_list', 'format_int_list', + 'complement_int_list', 'int_ranges_from_int_list', 'MultiReplace', + 'multi_replace', 'unwrap_text', 'removeprefix'] + + +_punct_ws_str = string.punctuation + string.whitespace +_punct_re = re.compile('[' + _punct_ws_str + ']+') +_camel2under_re = re.compile('((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))') + + +def camel2under(camel_string): + """Converts a camelcased string to underscores. Useful for turning a + class name into a function name. + + >>> camel2under('BasicParseTest') + 'basic_parse_test' + """ + return _camel2under_re.sub(r'_\1', camel_string).lower() + + +def under2camel(under_string): + """Converts an underscored string to camelcased. Useful for turning a + function name into a class name. + + >>> under2camel('complex_tokenizer') + 'ComplexTokenizer' + """ + return ''.join(w.capitalize() or '_' for w in under_string.split('_')) + + +def slugify(text, delim='_', lower=True, ascii=False): + """ + A basic function that turns text full of scary characters + (i.e., punctuation and whitespace), into a relatively safe + lowercased string separated only by the delimiter specified + by *delim*, which defaults to ``_``. + + The *ascii* convenience flag will :func:`asciify` the slug if + you require ascii-only slugs. + + >>> slugify('First post! Hi!!!!~1 ') + 'first_post_hi_1' + + >>> slugify("Kurt Gödel's pretty cool.", ascii=True) == \ + b'kurt_goedel_s_pretty_cool' + True + + """ + ret = delim.join(split_punct_ws(text)) or delim if text else '' + if ascii: + ret = asciify(ret) + if lower: + ret = ret.lower() + return ret + + +def split_punct_ws(text): + """While :meth:`str.split` will split on whitespace, + :func:`split_punct_ws` will split on punctuation and + whitespace. This used internally by :func:`slugify`, above. + + >>> split_punct_ws('First post! Hi!!!!~1 ') + ['First', 'post', 'Hi', '1'] + """ + return [w for w in _punct_re.split(text) if w] + + +def unit_len(sized_iterable, unit_noun='item'): # TODO: len_units()/unitize()? + """Returns a plain-English description of an iterable's + :func:`len()`, conditionally pluralized with :func:`cardinalize`, + detailed below. + + >>> print(unit_len(range(10), 'number')) + 10 numbers + >>> print(unit_len('aeiou', 'vowel')) + 5 vowels + >>> print(unit_len([], 'worry')) + No worries + """ + count = len(sized_iterable) + units = cardinalize(unit_noun, count) + if count: + return f'{count} {units}' + return f'No {units}' + + +_ORDINAL_MAP = {'1': 'st', + '2': 'nd', + '3': 'rd'} # 'th' is the default + + +def ordinalize(number, ext_only=False): + """Turns *number* into its cardinal form, i.e., 1st, 2nd, + 3rd, 4th, etc. If the last character isn't a digit, it returns the + string value unchanged. + + Args: + number (int or str): Number to be cardinalized. + ext_only (bool): Whether to return only the suffix. Default ``False``. + + >>> print(ordinalize(1)) + 1st + >>> print(ordinalize(3694839230)) + 3694839230th + >>> print(ordinalize('hi')) + hi + >>> print(ordinalize(1515)) + 1515th + """ + numstr, ext = str(number), '' + if numstr and numstr[-1] in string.digits: + try: + # first check for teens + if numstr[-2] == '1': + ext = 'th' + else: + # all other cases + ext = _ORDINAL_MAP.get(numstr[-1], 'th') + except IndexError: + # single digit numbers (will reach here based on [-2] above) + ext = _ORDINAL_MAP.get(numstr[-1], 'th') + if ext_only: + return ext + else: + return numstr + ext + + +def cardinalize(unit_noun, count): + """Conditionally pluralizes a singular word *unit_noun* if + *count* is not one, preserving case when possible. + + >>> vowels = 'aeiou' + >>> print(len(vowels), cardinalize('vowel', len(vowels))) + 5 vowels + >>> print(3, cardinalize('Wish', 3)) + 3 Wishes + """ + if count == 1: + return unit_noun + return pluralize(unit_noun) + + +def singularize(word): + """Semi-intelligently converts an English plural *word* to its + singular form, preserving case pattern. + + >>> singularize('chances') + 'chance' + >>> singularize('Activities') + 'Activity' + >>> singularize('Glasses') + 'Glass' + >>> singularize('FEET') + 'FOOT' + + """ + orig_word, word = word, word.strip().lower() + if not word or word in _IRR_S2P: + return orig_word + + irr_singular = _IRR_P2S.get(word) + if irr_singular: + singular = irr_singular + elif not word.endswith('s'): + return orig_word + elif len(word) == 2: + singular = word[:-1] # or just return word? + elif word.endswith('ies') and word[-4:-3] not in 'aeiou': + singular = word[:-3] + 'y' + elif word.endswith('es') and word[-3] == 's': + singular = word[:-2] + else: + singular = word[:-1] + return _match_case(orig_word, singular) + + +def pluralize(word): + """Semi-intelligently converts an English *word* from singular form to + plural, preserving case pattern. + + >>> pluralize('friend') + 'friends' + >>> pluralize('enemy') + 'enemies' + >>> pluralize('Sheep') + 'Sheep' + """ + orig_word, word = word, word.strip().lower() + if not word or word in _IRR_P2S: + return orig_word + irr_plural = _IRR_S2P.get(word) + if irr_plural: + plural = irr_plural + elif word.endswith('y') and word[-2:-1] not in 'aeiou': + plural = word[:-1] + 'ies' + elif word[-1] == 's' or word.endswith('ch') or word.endswith('sh'): + plural = word if word.endswith('es') else word + 'es' + else: + plural = word + 's' + return _match_case(orig_word, plural) + + +def _match_case(master, disciple): + if not master.strip(): + return disciple + if master.lower() == master: + return disciple.lower() + elif master.upper() == master: + return disciple.upper() + elif master.title() == master: + return disciple.title() + return disciple + + +# Singular to plural map of irregular pluralizations +_IRR_S2P = {'addendum': 'addenda', 'alga': 'algae', 'alumna': 'alumnae', + 'alumnus': 'alumni', 'analysis': 'analyses', 'antenna': 'antennae', + 'appendix': 'appendices', 'axis': 'axes', 'bacillus': 'bacilli', + 'bacterium': 'bacteria', 'basis': 'bases', 'beau': 'beaux', + 'bison': 'bison', 'bureau': 'bureaus', 'cactus': 'cacti', + 'calf': 'calves', 'child': 'children', 'corps': 'corps', + 'corpus': 'corpora', 'crisis': 'crises', 'criterion': 'criteria', + 'curriculum': 'curricula', 'datum': 'data', 'deer': 'deer', + 'diagnosis': 'diagnoses', 'die': 'dice', 'dwarf': 'dwarves', + 'echo': 'echoes', 'elf': 'elves', 'ellipsis': 'ellipses', + 'embargo': 'embargoes', 'emphasis': 'emphases', 'erratum': 'errata', + 'fireman': 'firemen', 'fish': 'fish', 'focus': 'foci', + 'foot': 'feet', 'formula': 'formulae', 'formula': 'formulas', + 'fungus': 'fungi', 'genus': 'genera', 'goose': 'geese', + 'half': 'halves', 'hero': 'heroes', 'hippopotamus': 'hippopotami', + 'hoof': 'hooves', 'hypothesis': 'hypotheses', 'index': 'indices', + 'knife': 'knives', 'leaf': 'leaves', 'life': 'lives', + 'loaf': 'loaves', 'louse': 'lice', 'man': 'men', + 'matrix': 'matrices', 'means': 'means', 'medium': 'media', + 'memorandum': 'memoranda', 'millennium': 'milennia', 'moose': 'moose', + 'mosquito': 'mosquitoes', 'mouse': 'mice', 'nebula': 'nebulae', + 'neurosis': 'neuroses', 'nucleus': 'nuclei', 'oasis': 'oases', + 'octopus': 'octopi', 'offspring': 'offspring', 'ovum': 'ova', + 'ox': 'oxen', 'paralysis': 'paralyses', 'parenthesis': 'parentheses', + 'person': 'people', 'phenomenon': 'phenomena', 'potato': 'potatoes', + 'radius': 'radii', 'scarf': 'scarves', 'scissors': 'scissors', + 'self': 'selves', 'sense': 'senses', 'series': 'series', 'sheep': + 'sheep', 'shelf': 'shelves', 'species': 'species', 'stimulus': + 'stimuli', 'stratum': 'strata', 'syllabus': 'syllabi', 'symposium': + 'symposia', 'synopsis': 'synopses', 'synthesis': 'syntheses', + 'tableau': 'tableaux', 'that': 'those', 'thesis': 'theses', + 'thief': 'thieves', 'this': 'these', 'tomato': 'tomatoes', 'tooth': + 'teeth', 'torpedo': 'torpedoes', 'vertebra': 'vertebrae', 'veto': + 'vetoes', 'vita': 'vitae', 'watch': 'watches', 'wife': 'wives', + 'wolf': 'wolves', 'woman': 'women'} + + +# Reverse index of the above +_IRR_P2S = {v: k for k, v in _IRR_S2P.items()} + +HASHTAG_RE = re.compile(r"(?:^|\s)[##]{1}(\w+)", re.UNICODE) + + +def find_hashtags(string): + """Finds and returns all hashtags in a string, with the hashmark + removed. Supports full-width hashmarks for Asian languages and + does not false-positive on URL anchors. + + >>> find_hashtags('#atag http://asite/#ananchor') + ['atag'] + + ``find_hashtags`` also works with unicode hashtags. + """ + + # the following works, doctest just struggles with it + # >>> find_hashtags(u"can't get enough of that dignity chicken #肯德基 woo") + # [u'\u80af\u5fb7\u57fa'] + return HASHTAG_RE.findall(string) + + +def a10n(string): + """That thing where "internationalization" becomes "i18n", what's it + called? Abbreviation? Oh wait, no: ``a10n``. (It's actually a form + of `numeronym`_.) + + >>> a10n('abbreviation') + 'a10n' + >>> a10n('internationalization') + 'i18n' + >>> a10n('') + '' + + .. _numeronym: http://en.wikipedia.org/wiki/Numeronym + """ + if len(string) < 3: + return string + return f'{string[0]}{len(string[1:-1])}{string[-1]}' + + +# Based on https://en.wikipedia.org/wiki/ANSI_escape_code#Escape_sequences +ANSI_SEQUENCES = re.compile(r''' + \x1B # Sequence starts with ESC, i.e. hex 0x1B + (?: + [@-Z\\-_] # Second byte: + # all 0x40–0x5F range but CSI char, i.e ASCII @A–Z\]^_ + | # Or + \[ # CSI sequences, starting with [ + [0-?]* # Parameter bytes: + # range 0x30–0x3F, ASCII 0–9:;<=>? + [ -/]* # Intermediate bytes: + # range 0x20–0x2F, ASCII space and !"#$%&'()*+,-./ + [@-~] # Final byte + # range 0x40–0x7E, ASCII @A–Z[\]^_`a–z{|}~ + ) +''', re.VERBOSE) + + +def strip_ansi(text): + """Strips ANSI escape codes from *text*. Useful for the occasional + time when a log or redirected output accidentally captures console + color codes and the like. + + >>> strip_ansi('\x1b[0m\x1b[1;36mart\x1b[46;34m') + 'art' + + Supports str, bytes and bytearray content as input. Returns the + same type as the input. + + There's a lot of ANSI art available for testing on `sixteencolors.net`_. + This function does not interpret or render ANSI art, but you can do so with + `ansi2img`_ or `escapes.js`_. + + .. _sixteencolors.net: http://sixteencolors.net + .. _ansi2img: http://www.bedroomlan.org/projects/ansi2img + .. _escapes.js: https://github.com/atdt/escapes.js + """ + # TODO: move to cliutils.py + + # Transform any ASCII-like content to unicode to allow regex to match, and + # save input type for later. + target_type = None + # Unicode type aliased to str is code-smell for Boltons in Python 3 env. + if isinstance(text, (bytes, bytearray)): + target_type = type(text) + text = text.decode('utf-8') + + cleaned = ANSI_SEQUENCES.sub('', text) + + # Transform back the result to the same bytearray type provided by the user. + if target_type and target_type != type(cleaned): + cleaned = target_type(cleaned, 'utf-8') + + return cleaned + + +def asciify(text, ignore=False): + """Converts a unicode or bytestring, *text*, into a bytestring with + just ascii characters. Performs basic deaccenting for all you + Europhiles out there. + + Also, a gentle reminder that this is a **utility**, primarily meant + for slugification. Whenever possible, make your application work + **with** unicode, not against it. + + Args: + text (str): The string to be asciified. + ignore (bool): Configures final encoding to ignore remaining + unasciified string instead of replacing it. + + >>> asciify('Beyoncé') == b'Beyonce' + True + """ + try: + try: + return text.encode('ascii') + except UnicodeDecodeError: + # this usually means you passed in a non-unicode string + text = text.decode('utf-8') + return text.encode('ascii') + except UnicodeEncodeError: + mode = 'replace' + if ignore: + mode = 'ignore' + transd = unicodedata.normalize('NFKD', text.translate(DEACCENT_MAP)) + ret = transd.encode('ascii', mode) + return ret + + +def is_ascii(text): + """Check if a string or bytestring, *text*, is composed of ascii + characters only. Raises :exc:`ValueError` if argument is not text. + + Args: + text (str): The string to be checked. + + >>> is_ascii('Beyoncé') + False + >>> is_ascii('Beyonce') + True + """ + if isinstance(text, str): + try: + text.encode('ascii') + except UnicodeEncodeError: + return False + elif isinstance(text, bytes): + try: + text.decode('ascii') + except UnicodeDecodeError: + return False + else: + raise ValueError('expected text or bytes, not %r' % type(text)) + return True + + +class DeaccenterDict(dict): + "A small caching dictionary for deaccenting." + def __missing__(self, key): + ch = self.get(key) + if ch is not None: + return ch + try: + de = unicodedata.decomposition(chr(key)) + p1, _, p2 = de.rpartition(' ') + if int(p2, 16) == 0x308: + ch = self.get(key) + else: + ch = int(p1, 16) + except (IndexError, ValueError): + ch = self.get(key, key) + self[key] = ch + return ch + + +# http://chmullig.com/2009/12/python-unicode-ascii-ifier/ +# For something more complete, investigate the unidecode +# or isounidecode packages, which are capable of performing +# crude transliteration. +_BASE_DEACCENT_MAP = { + 0xc6: "AE", # Æ LATIN CAPITAL LETTER AE + 0xd0: "D", # Ð LATIN CAPITAL LETTER ETH + 0xd8: "OE", # Ø LATIN CAPITAL LETTER O WITH STROKE + 0xde: "Th", # Þ LATIN CAPITAL LETTER THORN + 0xc4: 'Ae', # Ä LATIN CAPITAL LETTER A WITH DIAERESIS + 0xd6: 'Oe', # Ö LATIN CAPITAL LETTER O WITH DIAERESIS + 0xdc: 'Ue', # Ü LATIN CAPITAL LETTER U WITH DIAERESIS + 0xc0: "A", # À LATIN CAPITAL LETTER A WITH GRAVE + 0xc1: "A", # Á LATIN CAPITAL LETTER A WITH ACUTE + 0xc3: "A", # Ã LATIN CAPITAL LETTER A WITH TILDE + 0xc7: "C", # Ç LATIN CAPITAL LETTER C WITH CEDILLA + 0xc8: "E", # È LATIN CAPITAL LETTER E WITH GRAVE + 0xc9: "E", # É LATIN CAPITAL LETTER E WITH ACUTE + 0xca: "E", # Ê LATIN CAPITAL LETTER E WITH CIRCUMFLEX + 0xcc: "I", # Ì LATIN CAPITAL LETTER I WITH GRAVE + 0xcd: "I", # Í LATIN CAPITAL LETTER I WITH ACUTE + 0xd2: "O", # Ò LATIN CAPITAL LETTER O WITH GRAVE + 0xd3: "O", # Ó LATIN CAPITAL LETTER O WITH ACUTE + 0xd5: "O", # Õ LATIN CAPITAL LETTER O WITH TILDE + 0xd9: "U", # Ù LATIN CAPITAL LETTER U WITH GRAVE + 0xda: "U", # Ú LATIN CAPITAL LETTER U WITH ACUTE + 0xdf: "ss", # ß LATIN SMALL LETTER SHARP S + 0xe6: "ae", # æ LATIN SMALL LETTER AE + 0xf0: "d", # ð LATIN SMALL LETTER ETH + 0xf8: "oe", # ø LATIN SMALL LETTER O WITH STROKE + 0xfe: "th", # þ LATIN SMALL LETTER THORN, + 0xe4: 'ae', # ä LATIN SMALL LETTER A WITH DIAERESIS + 0xf6: 'oe', # ö LATIN SMALL LETTER O WITH DIAERESIS + 0xfc: 'ue', # ü LATIN SMALL LETTER U WITH DIAERESIS + 0xe0: "a", # à LATIN SMALL LETTER A WITH GRAVE + 0xe1: "a", # á LATIN SMALL LETTER A WITH ACUTE + 0xe3: "a", # ã LATIN SMALL LETTER A WITH TILDE + 0xe7: "c", # ç LATIN SMALL LETTER C WITH CEDILLA + 0xe8: "e", # è LATIN SMALL LETTER E WITH GRAVE + 0xe9: "e", # é LATIN SMALL LETTER E WITH ACUTE + 0xea: "e", # ê LATIN SMALL LETTER E WITH CIRCUMFLEX + 0xec: "i", # ì LATIN SMALL LETTER I WITH GRAVE + 0xed: "i", # í LATIN SMALL LETTER I WITH ACUTE + 0xf2: "o", # ò LATIN SMALL LETTER O WITH GRAVE + 0xf3: "o", # ó LATIN SMALL LETTER O WITH ACUTE + 0xf5: "o", # õ LATIN SMALL LETTER O WITH TILDE + 0xf9: "u", # ù LATIN SMALL LETTER U WITH GRAVE + 0xfa: "u", # ú LATIN SMALL LETTER U WITH ACUTE + 0x2018: "'", # ‘ LEFT SINGLE QUOTATION MARK + 0x2019: "'", # ’ RIGHT SINGLE QUOTATION MARK + 0x201c: '"', # “ LEFT DOUBLE QUOTATION MARK + 0x201d: '"', # ” RIGHT DOUBLE QUOTATION MARK + } + + +DEACCENT_MAP = DeaccenterDict(_BASE_DEACCENT_MAP) + + +_SIZE_SYMBOLS = ('B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y') +_SIZE_BOUNDS = [(1024 ** i, sym) for i, sym in enumerate(_SIZE_SYMBOLS)] +_SIZE_RANGES = list(zip(_SIZE_BOUNDS, _SIZE_BOUNDS[1:])) + + +def bytes2human(nbytes, ndigits=0): + """Turns an integer value of *nbytes* into a human readable format. Set + *ndigits* to control how many digits after the decimal point + should be shown (default ``0``). + + >>> bytes2human(128991) + '126K' + >>> bytes2human(100001221) + '95M' + >>> bytes2human(0, 2) + '0.00B' + """ + abs_bytes = abs(nbytes) + for (size, symbol), (next_size, next_symbol) in _SIZE_RANGES: + if abs_bytes <= next_size: + break + hnbytes = float(nbytes) / size + return '{hnbytes:.{ndigits}f}{symbol}'.format(hnbytes=hnbytes, + ndigits=ndigits, + symbol=symbol) + + +class HTMLTextExtractor(HTMLParser): + def __init__(self): + self.reset() + self.strict = False + self.convert_charrefs = True + self.result = [] + + def handle_data(self, d): + self.result.append(d) + + def handle_charref(self, number): + if number[0] == 'x' or number[0] == 'X': + codepoint = int(number[1:], 16) + else: + codepoint = int(number) + self.result.append(chr(codepoint)) + + def handle_entityref(self, name): + try: + codepoint = htmlentitydefs.name2codepoint[name] + except KeyError: + self.result.append('&' + name + ';') + else: + self.result.append(chr(codepoint)) + + def get_text(self): + return ''.join(self.result) + + +def html2text(html): + """Strips tags from HTML text, returning markup-free text. Also, does + a best effort replacement of entities like " " + + >>> r = html2text(u'Test &(\u0394ημώ)') + >>> r == u'Test &(\u0394\u03b7\u03bc\u03ce)' + True + """ + # based on answers to http://stackoverflow.com/questions/753052/ + s = HTMLTextExtractor() + s.feed(html) + return s.get_text() + + +_EMPTY_GZIP_BYTES = b'\x1f\x8b\x08\x089\xf3\xb9U\x00\x03empty\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00' +_NON_EMPTY_GZIP_BYTES = b'\x1f\x8b\x08\x08\xbc\xf7\xb9U\x00\x03not_empty\x00K\xaa,I-N\xcc\xc8\xafT\xe4\x02\x00\xf3nb\xbf\x0b\x00\x00\x00' + + +def gunzip_bytes(bytestring): + """The :mod:`gzip` module is great if you have a file or file-like + object, but what if you just have bytes. StringIO is one + possibility, but it's often faster, easier, and simpler to just + use this one-liner. Use this tried-and-true utility function to + decompress gzip from bytes. + + >>> gunzip_bytes(_EMPTY_GZIP_BYTES) == b'' + True + >>> gunzip_bytes(_NON_EMPTY_GZIP_BYTES).rstrip() == b'bytesahoy!' + True + """ + return zlib.decompress(bytestring, 16 + zlib.MAX_WBITS) + + +def gzip_bytes(bytestring, level=6): + """Turn some bytes into some compressed bytes. + + >>> len(gzip_bytes(b'a' * 10000)) + 46 + + Args: + bytestring (bytes): Bytes to be compressed + level (int): An integer, 1-9, controlling the + speed/compression. 1 is fastest, least compressed, 9 is + slowest, but most compressed. + + Note that all levels of gzip are pretty fast these days, though + it's not really a competitor in compression, at any level. + """ + out = StringIO() + f = GzipFile(fileobj=out, mode='wb', compresslevel=level) + f.write(bytestring) + f.close() + return out.getvalue() + + + +_line_ending_re = re.compile(r'(\r\n|\n|\x0b|\f|\r|\x85|\x2028|\x2029)', + re.UNICODE) + + +def iter_splitlines(text): + r"""Like :meth:`str.splitlines`, but returns an iterator of lines + instead of a list. Also similar to :meth:`file.next`, as that also + lazily reads and yields lines from a file. + + This function works with a variety of line endings, but as always, + be careful when mixing line endings within a file. + + >>> list(iter_splitlines('\nhi\nbye\n')) + ['', 'hi', 'bye', ''] + >>> list(iter_splitlines('\r\nhi\rbye\r\n')) + ['', 'hi', 'bye', ''] + >>> list(iter_splitlines('')) + [] + """ + prev_end, len_text = 0, len(text) + # print('last: %r' % last_idx) + # start, end = None, None + for match in _line_ending_re.finditer(text): + start, end = match.start(1), match.end(1) + # print(start, end) + if prev_end <= start: + yield text[prev_end:start] + if end == len_text: + yield '' + prev_end = end + tail = text[prev_end:] + if tail: + yield tail + return + + +def indent(text, margin, newline='\n', key=bool): + """The missing counterpart to the built-in :func:`textwrap.dedent`. + + Args: + text (str): The text to indent. + margin (str): The string to prepend to each line. + newline (str): The newline used to rejoin the lines (default: ``\\n``) + key (callable): Called on each line to determine whether to + indent it. Default: :class:`bool`, to ensure that empty lines do + not get whitespace added. + """ + indented_lines = [(margin + line if key(line) else line) + for line in iter_splitlines(text)] + return newline.join(indented_lines) + + +def is_uuid(obj, version=4): + """Check the argument is either a valid UUID object or string. + + Args: + obj (object): The test target. Strings and UUID objects supported. + version (int): The target UUID version, set to 0 to skip version check. + + >>> is_uuid('e682ccca-5a4c-4ef2-9711-73f9ad1e15ea') + True + >>> is_uuid('0221f0d9-d4b9-11e5-a478-10ddb1c2feb9') + False + >>> is_uuid('0221f0d9-d4b9-11e5-a478-10ddb1c2feb9', version=1) + True + """ + if not isinstance(obj, uuid.UUID): + try: + obj = uuid.UUID(obj) + except (TypeError, ValueError, AttributeError): + return False + if version and obj.version != int(version): + return False + return True + + +def escape_shell_args(args, sep=' ', style=None): + """Returns an escaped version of each string in *args*, according to + *style*. + + Args: + args (list): A list of arguments to escape and join together + sep (str): The separator used to join the escaped arguments. + style (str): The style of escaping to use. Can be one of + ``cmd`` or ``sh``, geared toward Windows and Linux/BSD/etc., + respectively. If *style* is ``None``, then it is picked + according to the system platform. + + See :func:`args2cmd` and :func:`args2sh` for details and example + output for each style. + """ + if not style: + style = 'cmd' if sys.platform == 'win32' else 'sh' + + if style == 'sh': + return args2sh(args, sep=sep) + elif style == 'cmd': + return args2cmd(args, sep=sep) + + raise ValueError("style expected one of 'cmd' or 'sh', not %r" % style) + + +_find_sh_unsafe = re.compile(r'[^a-zA-Z0-9_@%+=:,./-]').search + + +def args2sh(args, sep=' '): + """Return a shell-escaped string version of *args*, separated by + *sep*, based on the rules of sh, bash, and other shells in the + Linux/BSD/MacOS ecosystem. + + >>> print(args2sh(['aa', '[bb]', "cc'cc", 'dd"dd'])) + aa '[bb]' 'cc'"'"'cc' 'dd"dd' + + As you can see, arguments with no special characters are not + escaped, arguments with special characters are quoted with single + quotes, and single quotes themselves are quoted with double + quotes. Double quotes are handled like any other special + character. + + Based on code from the :mod:`pipes`/:mod:`shlex` modules. Also + note that :mod:`shlex` and :mod:`argparse` have functions to split + and parse strings escaped in this manner. + """ + ret_list = [] + + for arg in args: + if not arg: + ret_list.append("''") + continue + if _find_sh_unsafe(arg) is None: + ret_list.append(arg) + continue + # use single quotes, and put single quotes into double quotes + # the string $'b is then quoted as '$'"'"'b' + ret_list.append("'" + arg.replace("'", "'\"'\"'") + "'") + + return ' '.join(ret_list) + + +def args2cmd(args, sep=' '): + r"""Return a shell-escaped string version of *args*, separated by + *sep*, using the same rules as the Microsoft C runtime. + + >>> print(args2cmd(['aa', '[bb]', "cc'cc", 'dd"dd'])) + aa [bb] cc'cc dd\"dd + + As you can see, escaping is through backslashing and not quoting, + and double quotes are the only special character. See the comment + in the code for more details. Based on internal code from the + :mod:`subprocess` module. + + """ + # technique description from subprocess below + """ + 1) Arguments are delimited by white space, which is either a + space or a tab. + + 2) A string surrounded by double quotation marks is + interpreted as a single argument, regardless of white space + contained within. A quoted string can be embedded in an + argument. + + 3) A double quotation mark preceded by a backslash is + interpreted as a literal double quotation mark. + + 4) Backslashes are interpreted literally, unless they + immediately precede a double quotation mark. + + 5) If backslashes immediately precede a double quotation mark, + every pair of backslashes is interpreted as a literal + backslash. If the number of backslashes is odd, the last + backslash escapes the next double quotation mark as + described in rule 3. + + See http://msdn.microsoft.com/en-us/library/17w5ykft.aspx + or search http://msdn.microsoft.com for + "Parsing C++ Command-Line Arguments" + """ + result = [] + needquote = False + for arg in args: + bs_buf = [] + + # Add a space to separate this argument from the others + if result: + result.append(' ') + + needquote = (" " in arg) or ("\t" in arg) or not arg + if needquote: + result.append('"') + + for c in arg: + if c == '\\': + # Don't know if we need to double yet. + bs_buf.append(c) + elif c == '"': + # Double backslashes. + result.append('\\' * len(bs_buf)*2) + bs_buf = [] + result.append('\\"') + else: + # Normal char + if bs_buf: + result.extend(bs_buf) + bs_buf = [] + result.append(c) + + # Add remaining backslashes, if any. + if bs_buf: + result.extend(bs_buf) + + if needquote: + result.extend(bs_buf) + result.append('"') + + return ''.join(result) + + +def parse_int_list(range_string, delim=',', range_delim='-'): + """Returns a sorted list of positive integers based on + *range_string*. Reverse of :func:`format_int_list`. + + Args: + range_string (str): String of comma separated positive + integers or ranges (e.g. '1,2,4-6,8'). Typical of a custom + page range string used in printer dialogs. + delim (char): Defaults to ','. Separates integers and + contiguous ranges of integers. + range_delim (char): Defaults to '-'. Indicates a contiguous + range of integers. + + >>> parse_int_list('1,3,5-8,10-11,15') + [1, 3, 5, 6, 7, 8, 10, 11, 15] + + """ + output = [] + + for x in range_string.strip().split(delim): + + # Range + if range_delim in x: + range_limits = list(map(int, x.split(range_delim))) + output += list(range(min(range_limits), max(range_limits)+1)) + + # Empty String + elif not x: + continue + + # Integer + else: + output.append(int(x)) + + return sorted(output) + + +def format_int_list(int_list, delim=',', range_delim='-', delim_space=False): + """Returns a sorted range string from a list of positive integers + (*int_list*). Contiguous ranges of integers are collapsed to min + and max values. Reverse of :func:`parse_int_list`. + + Args: + int_list (list): List of positive integers to be converted + into a range string (e.g. [1,2,4,5,6,8]). + delim (char): Defaults to ','. Separates integers and + contiguous ranges of integers. + range_delim (char): Defaults to '-'. Indicates a contiguous + range of integers. + delim_space (bool): Defaults to ``False``. If ``True``, adds a + space after all *delim* characters. + + >>> format_int_list([1,3,5,6,7,8,10,11,15]) + '1,3,5-8,10-11,15' + + """ + output = [] + contig_range = collections.deque() + + for x in sorted(int_list): + + # Handle current (and first) value. + if len(contig_range) < 1: + contig_range.append(x) + + # Handle current value, given multiple previous values are contiguous. + elif len(contig_range) > 1: + delta = x - contig_range[-1] + + # Current value is contiguous. + if delta == 1: + contig_range.append(x) + + # Current value is non-contiguous. + elif delta > 1: + range_substr = '{:d}{}{:d}'.format(min(contig_range), + range_delim, + max(contig_range)) + output.append(range_substr) + contig_range.clear() + contig_range.append(x) + + # Current value repeated. + else: + continue + + # Handle current value, given no previous contiguous integers + else: + delta = x - contig_range[0] + + # Current value is contiguous. + if delta == 1: + contig_range.append(x) + + # Current value is non-contiguous. + elif delta > 1: + output.append(f'{contig_range.popleft():d}') + contig_range.append(x) + + # Current value repeated. + else: + continue + + # Handle the last value. + else: + + # Last value is non-contiguous. + if len(contig_range) == 1: + output.append(f'{contig_range.popleft():d}') + contig_range.clear() + + # Last value is part of contiguous range. + elif len(contig_range) > 1: + range_substr = '{:d}{}{:d}'.format(min(contig_range), + range_delim, + max(contig_range)) + output.append(range_substr) + contig_range.clear() + + if delim_space: + output_str = (delim+' ').join(output) + else: + output_str = delim.join(output) + + return output_str + + +def complement_int_list( + range_string, range_start=0, range_end=None, + delim=',', range_delim='-'): + """ Returns range string that is the complement of the one provided as + *range_string* parameter. + + These range strings are of the kind produce by :func:`format_int_list`, and + parseable by :func:`parse_int_list`. + + Args: + range_string (str): String of comma separated positive integers or + ranges (e.g. '1,2,4-6,8'). Typical of a custom page range string + used in printer dialogs. + range_start (int): A positive integer from which to start the resulting + range. Value is inclusive. Defaults to ``0``. + range_end (int): A positive integer from which the produced range is + stopped. Value is exclusive. Defaults to the maximum value found in + the provided ``range_string``. + delim (char): Defaults to ','. Separates integers and contiguous ranges + of integers. + range_delim (char): Defaults to '-'. Indicates a contiguous range of + integers. + + >>> complement_int_list('1,3,5-8,10-11,15') + '0,2,4,9,12-14' + + >>> complement_int_list('1,3,5-8,10-11,15', range_start=0) + '0,2,4,9,12-14' + + >>> complement_int_list('1,3,5-8,10-11,15', range_start=1) + '2,4,9,12-14' + + >>> complement_int_list('1,3,5-8,10-11,15', range_start=2) + '2,4,9,12-14' + + >>> complement_int_list('1,3,5-8,10-11,15', range_start=3) + '4,9,12-14' + + >>> complement_int_list('1,3,5-8,10-11,15', range_end=15) + '0,2,4,9,12-14' + + >>> complement_int_list('1,3,5-8,10-11,15', range_end=14) + '0,2,4,9,12-13' + + >>> complement_int_list('1,3,5-8,10-11,15', range_end=13) + '0,2,4,9,12' + + >>> complement_int_list('1,3,5-8,10-11,15', range_end=20) + '0,2,4,9,12-14,16-19' + + >>> complement_int_list('1,3,5-8,10-11,15', range_end=0) + '' + + >>> complement_int_list('1,3,5-8,10-11,15', range_start=-1) + '0,2,4,9,12-14' + + >>> complement_int_list('1,3,5-8,10-11,15', range_end=-1) + '' + + >>> complement_int_list('1,3,5-8', range_start=1, range_end=1) + '' + + >>> complement_int_list('1,3,5-8', range_start=2, range_end=2) + '' + + >>> complement_int_list('1,3,5-8', range_start=2, range_end=3) + '2' + + >>> complement_int_list('1,3,5-8', range_start=-10, range_end=-5) + '' + + >>> complement_int_list('1,3,5-8', range_start=20, range_end=10) + '' + + >>> complement_int_list('') + '' + """ + int_list = set(parse_int_list(range_string, delim, range_delim)) + if range_end is None: + if int_list: + range_end = max(int_list) + 1 + else: + range_end = range_start + complement_values = set( + range(range_end)) - int_list - set(range(range_start)) + return format_int_list(complement_values, delim, range_delim) + + +def int_ranges_from_int_list(range_string, delim=',', range_delim='-'): + """ Transform a string of ranges (*range_string*) into a tuple of tuples. + + Args: + range_string (str): String of comma separated positive integers or + ranges (e.g. '1,2,4-6,8'). Typical of a custom page range string + used in printer dialogs. + delim (char): Defaults to ','. Separates integers and contiguous ranges + of integers. + range_delim (char): Defaults to '-'. Indicates a contiguous range of + integers. + + >>> int_ranges_from_int_list('1,3,5-8,10-11,15') + ((1, 1), (3, 3), (5, 8), (10, 11), (15, 15)) + + >>> int_ranges_from_int_list('1') + ((1, 1),) + + >>> int_ranges_from_int_list('') + () + """ + int_tuples = [] + # Normalize the range string to our internal format for processing. + range_string = format_int_list( + parse_int_list(range_string, delim, range_delim)) + if range_string: + for bounds in range_string.split(','): + if '-' in bounds: + start, end = bounds.split('-') + else: + start, end = bounds, bounds + int_tuples.append((int(start), int(end))) + return tuple(int_tuples) + + +class MultiReplace: + """ + MultiReplace is a tool for doing multiple find/replace actions in one pass. + + Given a mapping of values to be replaced it allows for all of the matching + values to be replaced in a single pass which can save a lot of performance + on very large strings. In addition to simple replace, it also allows for + replacing based on regular expressions. + + Keyword Arguments: + + :type regex: bool + :param regex: Treat search keys as regular expressions [Default: False] + :type flags: int + :param flags: flags to pass to the regex engine during compile + + Dictionary Usage:: + + from boltons import strutils + s = strutils.MultiReplace({ + 'foo': 'zoo', + 'cat': 'hat', + 'bat': 'kraken' + }) + new = s.sub('The foo bar cat ate a bat') + new == 'The zoo bar hat ate a kraken' + + Iterable Usage:: + + from boltons import strutils + s = strutils.MultiReplace([ + ('foo', 'zoo'), + ('cat', 'hat'), + ('bat', 'kraken)' + ]) + new = s.sub('The foo bar cat ate a bat') + new == 'The zoo bar hat ate a kraken' + + + The constructor can be passed a dictionary or other mapping as well as + an iterable of tuples. If given an iterable, the substitution will be run + in the order the replacement values are specified in the iterable. This is + also true if it is given an OrderedDict. If given a dictionary then the + order will be non-deterministic:: + + >>> 'foo bar baz'.replace('foo', 'baz').replace('baz', 'bar') + 'bar bar bar' + >>> m = MultiReplace({'foo': 'baz', 'baz': 'bar'}) + >>> m.sub('foo bar baz') + 'baz bar bar' + + This is because the order of replacement can matter if you're inserting + something that might be replaced by a later substitution. Pay attention and + if you need to rely on order then consider using a list of tuples instead + of a dictionary. + """ + + def __init__(self, sub_map, **kwargs): + """Compile any regular expressions that have been passed.""" + options = { + 'regex': False, + 'flags': 0, + } + options.update(kwargs) + self.group_map = {} + regex_values = [] + + if isinstance(sub_map, Mapping): + sub_map = sub_map.items() + + for idx, vals in enumerate(sub_map): + group_name = f'group{idx}' + if isinstance(vals[0], str): + # If we're not treating input strings like a regex, escape it + if not options['regex']: + exp = re.escape(vals[0]) + else: + exp = vals[0] + else: + exp = vals[0].pattern + + regex_values.append(f'(?P<{group_name}>{exp})') + self.group_map[group_name] = vals[1] + + self.combined_pattern = re.compile( + '|'.join(regex_values), + flags=options['flags'] + ) + + def _get_value(self, match): + """Given a match object find replacement value.""" + group_dict = match.groupdict() + key = [x for x in group_dict if group_dict[x]][0] + return self.group_map[key] + + def sub(self, text): + """ + Run substitutions on the input text. + + Given an input string, run all substitutions given in the + constructor. + """ + return self.combined_pattern.sub(self._get_value, text) + + +def multi_replace(text, sub_map, **kwargs): + """ + Shortcut function to invoke MultiReplace in a single call. + + Example Usage:: + + from boltons.strutils import multi_replace + new = multi_replace( + 'The foo bar cat ate a bat', + {'foo': 'zoo', 'cat': 'hat', 'bat': 'kraken'} + ) + new == 'The zoo bar hat ate a kraken' + """ + m = MultiReplace(sub_map, **kwargs) + return m.sub(text) + + +def unwrap_text(text, ending='\n\n'): + r""" + Unwrap text, the natural complement to :func:`textwrap.wrap`. + + >>> text = "Short \n lines \nwrapped\nsmall.\n\nAnother\nparagraph." + >>> unwrap_text(text) + 'Short lines wrapped small.\n\nAnother paragraph.' + + Args: + text: A string to unwrap. + ending (str): The string to join all unwrapped paragraphs + by. Pass ``None`` to get the list. Defaults to '\n\n' for + compatibility with Markdown and RST. + + """ + all_grafs = [] + cur_graf = [] + for line in text.splitlines(): + line = line.strip() + if line: + cur_graf.append(line) + else: + all_grafs.append(' '.join(cur_graf)) + cur_graf = [] + if cur_graf: + all_grafs.append(' '.join(cur_graf)) + if ending is None: + return all_grafs + return ending.join(all_grafs) + +def removeprefix(text: str, prefix: str) -> str: + r""" + Remove `prefix` from start of `text` if present. + + Backport of `str.removeprefix` for Python versions less than 3.9. + + Args: + text: A string to remove the prefix from. + prefix: The string to remove from the beginning of `text`. + """ + if text.startswith(prefix): + return text[len(prefix):] + return text diff --git a/data/miniconda3/lib/python3.13/site-packages/boltons/tableutils.py b/data/miniconda3/lib/python3.13/site-packages/boltons/tableutils.py new file mode 100644 index 0000000000000000000000000000000000000000..46f155eb08ac6e0aa90db05e4768ec23f4ad6af1 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/boltons/tableutils.py @@ -0,0 +1,583 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# * The names of the contributors may not be used to endorse or +# promote products derived from this software without specific +# prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""If there is one recurring theme in ``boltons``, it is that Python +has excellent datastructures that constitute a good foundation for +most quick manipulations, as well as building applications. However, +Python usage has grown much faster than builtin data structure +power. Python has a growing need for more advanced general-purpose +data structures which behave intuitively. + +The :class:`Table` class is one example. When handed one- or +two-dimensional data, it can provide useful, if basic, text and HTML +renditions of small to medium sized data. It also heuristically +handles recursive data of various formats (lists, dicts, namedtuples, +objects). + +For more advanced :class:`Table`-style manipulation check out the +`pandas`_ DataFrame. + +.. _pandas: http://pandas.pydata.org/ + +""" + + +from html import escape as html_escape +import types +from itertools import islice +from collections.abc import Sequence, Mapping, MutableSequence + +try: + from .typeutils import make_sentinel + _MISSING = make_sentinel(var_name='_MISSING') +except ImportError: + _MISSING = object() + +""" +Some idle feature thoughts: + +* shift around column order without rearranging data +* gotta make it so you can add additional items, not just initialize with +* maybe a shortcut would be to allow adding of Tables to other Tables +* what's the perf of preallocating lists and overwriting items versus + starting from empty? +* is it possible to effectively tell the difference between when a + Table is from_data()'d with a single row (list) or with a list of lists? +* CSS: white-space pre-line or pre-wrap maybe? +* Would be nice to support different backends (currently uses lists + exclusively). Sometimes large datasets come in list-of-dicts and + list-of-tuples format and it's desirable to cut down processing overhead. + +TODO: make iterable on rows? +""" + +__all__ = ['Table'] + + +def to_text(obj, maxlen=None): + try: + text = str(obj) + except Exception: + try: + text = str(repr(obj)) + except Exception: + text = str(object.__repr__(obj)) + if maxlen and len(text) > maxlen: + text = text[:maxlen - 3] + '...' + # TODO: inverse of ljust/rjust/center + return text + + +def escape_html(obj, maxlen=None): + text = to_text(obj, maxlen=maxlen) + return html_escape(text, quote=True) + + +_DNR = {type(None), bool, complex, float, type(NotImplemented), slice, + str, bytes, int, + types.FunctionType, types.MethodType, + types.BuiltinFunctionType, types.GeneratorType} + + +class UnsupportedData(TypeError): + pass + + +class InputType: + def __init__(self, *a, **kw): + pass + + def get_entry_seq(self, data_seq, headers): + return [self.get_entry(entry, headers) for entry in data_seq] + + +class DictInputType(InputType): + def check_type(self, obj): + return isinstance(obj, Mapping) + + def guess_headers(self, obj): + return sorted(obj.keys()) + + def get_entry(self, obj, headers): + return [obj.get(h) for h in headers] + + def get_entry_seq(self, obj, headers): + return [[ci.get(h) for h in headers] for ci in obj] + + +class ObjectInputType(InputType): + def check_type(self, obj): + return type(obj) not in _DNR and hasattr(obj, '__class__') + + def guess_headers(self, obj): + headers = [] + for attr in dir(obj): + # an object's __dict__ could technically have non-string keys + try: + val = getattr(obj, attr) + except Exception: + # seen on greenlet: `run` shows in dir() but raises + # AttributeError. Also properties misbehave. + continue + if callable(val): + continue + headers.append(attr) + return headers + + def get_entry(self, obj, headers): + values = [] + for h in headers: + try: + values.append(getattr(obj, h)) + except Exception: + values.append(None) + return values + + +# might be better to hardcode list support since it's so close to the +# core or might be better to make this the copy-style from_* importer +# and have the non-copy style be hardcoded in __init__ +class ListInputType(InputType): + def check_type(self, obj): + return isinstance(obj, MutableSequence) + + def guess_headers(self, obj): + return None + + def get_entry(self, obj, headers): + return obj + + def get_entry_seq(self, obj_seq, headers): + return obj_seq + + +class TupleInputType(InputType): + def check_type(self, obj): + return isinstance(obj, tuple) + + def guess_headers(self, obj): + return None + + def get_entry(self, obj, headers): + return list(obj) + + def get_entry_seq(self, obj_seq, headers): + return [list(t) for t in obj_seq] + + +class NamedTupleInputType(InputType): + def check_type(self, obj): + return hasattr(obj, '_fields') and isinstance(obj, tuple) + + def guess_headers(self, obj): + return list(obj._fields) + + def get_entry(self, obj, headers): + return [getattr(obj, h, None) for h in headers] + + def get_entry_seq(self, obj_seq, headers): + return [[getattr(obj, h, None) for h in headers] for obj in obj_seq] + + +class Table: + """ + This Table class is meant to be simple, low-overhead, and extensible. Its + most common use would be for translation between in-memory data + structures and serialization formats, such as HTML and console-ready text. + + As such, it stores data in list-of-lists format, and *does not* copy + lists passed in. It also reserves the right to modify those lists in a + "filling" process, whereby short lists are extended to the width of + the table (usually determined by number of headers). This greatly + reduces overhead and processing/validation that would have to occur + otherwise. + + General description of headers behavior: + + Headers describe the columns, but are not part of the data, however, + if the *headers* argument is omitted, Table tries to infer header + names from the data. It is possible to have a table with no headers, + just pass in ``headers=None``. + + Supported inputs: + + * :class:`list` of :class:`list` objects + * :class:`dict` (list/single) + * :class:`object` (list/single) + * :class:`collections.namedtuple` (list/single) + * TODO: DB API cursor? + * TODO: json + + Supported outputs: + + * HTML + * Pretty text (also usable as GF Markdown) + * TODO: CSV + * TODO: json + * TODO: json lines + + To minimize resident size, the Table data is stored as a list of lists. + """ + + # order definitely matters here + _input_types = [DictInputType(), ListInputType(), + NamedTupleInputType(), TupleInputType(), + ObjectInputType()] + + _html_tr, _html_tr_close = '', '' + _html_th, _html_th_close = '', '' + _html_td, _html_td_close = '', '' + _html_thead, _html_thead_close = '', '' + _html_tbody, _html_tbody_close = '', '' + + # _html_tfoot, _html_tfoot_close = '', '' + _html_table_tag, _html_table_tag_close = '', '
' + + def __init__(self, data=None, headers=_MISSING, metadata=None): + if headers is _MISSING: + headers = [] + if data: + headers, data = list(data[0]), islice(data, 1, None) + self.headers = headers or [] + self.metadata = metadata or {} + self._data = [] + self._width = 0 + + self.extend(data) + + def extend(self, data): + """ + Append the given data to the end of the Table. + """ + if not data: + return + self._data.extend(data) + self._set_width() + self._fill() + + def _set_width(self, reset=False): + if reset: + self._width = 0 + if self._width: + return + if self.headers: + self._width = len(self.headers) + return + self._width = max([len(d) for d in self._data]) + + def _fill(self): + width, filler = self._width, [None] + if not width: + return + for d in self._data: + rem = width - len(d) + if rem > 0: + d.extend(filler * rem) + return + + @classmethod + def from_dict(cls, data, headers=_MISSING, max_depth=1, metadata=None): + """Create a Table from a :class:`dict`. Operates the same as + :meth:`from_data`, but forces interpretation of the data as a + Mapping. + """ + return cls.from_data(data=data, headers=headers, + max_depth=max_depth, _data_type=DictInputType(), + metadata=metadata) + + @classmethod + def from_list(cls, data, headers=_MISSING, max_depth=1, metadata=None): + """Create a Table from a :class:`list`. Operates the same as + :meth:`from_data`, but forces the interpretation of the data + as a Sequence. + """ + return cls.from_data(data=data, headers=headers, + max_depth=max_depth, _data_type=ListInputType(), + metadata=metadata) + + @classmethod + def from_object(cls, data, headers=_MISSING, max_depth=1, metadata=None): + """Create a Table from an :class:`object`. Operates the same as + :meth:`from_data`, but forces the interpretation of the data + as an object. May be useful for some :class:`dict` and + :class:`list` subtypes. + """ + return cls.from_data(data=data, headers=headers, + max_depth=max_depth, _data_type=ObjectInputType(), + metadata=metadata) + + @classmethod + def from_data(cls, data, headers=_MISSING, max_depth=1, **kwargs): + + """Create a Table from any supported data, heuristically + selecting how to represent the data in Table format. + + Args: + data (object): Any object or iterable with data to be + imported to the Table. + + headers (iterable): An iterable of headers to be matched + to the data. If not explicitly passed, headers will be + guessed for certain datatypes. + + max_depth (int): The level to which nested Tables should + be created (default: 1). + + _data_type (InputType subclass): For advanced use cases, + do not guess the type of the input data, use this data + type instead. + """ + # TODO: seen/cycle detection/reuse ? + # maxdepth follows the same behavior as find command + # i.e., it doesn't work if max_depth=0 is passed in + metadata = kwargs.pop('metadata', None) + _data_type = kwargs.pop('_data_type', None) + + if max_depth < 1: + # return data instead? + return cls(headers=headers, metadata=metadata) + is_seq = isinstance(data, Sequence) + if is_seq: + if not data: + return cls(headers=headers, metadata=metadata) + to_check = data[0] + if not _data_type: + for it in cls._input_types: + if it.check_type(to_check): + _data_type = it + break + else: + # not particularly happy about this rewind-y approach + is_seq = False + to_check = data + else: + if type(data) in _DNR: + # hmm, got scalar data. + # raise an exception or make an exception, nahmsayn? + return cls([[data]], headers=headers, metadata=metadata) + to_check = data + if not _data_type: + for it in cls._input_types: + if it.check_type(to_check): + _data_type = it + break + else: + raise UnsupportedData('unsupported data type %r' + % type(data)) + if headers is _MISSING: + headers = _data_type.guess_headers(to_check) + if is_seq: + entries = _data_type.get_entry_seq(data, headers) + else: + entries = [_data_type.get_entry(data, headers)] + if max_depth > 1: + new_max_depth = max_depth - 1 + for i, entry in enumerate(entries): + for j, cell in enumerate(entry): + if type(cell) in _DNR: + # optimization to avoid function overhead + continue + try: + entries[i][j] = cls.from_data(cell, + max_depth=new_max_depth) + except UnsupportedData: + continue + return cls(entries, headers=headers, metadata=metadata) + + def __len__(self): + return len(self._data) + + def __getitem__(self, idx): + return self._data[idx] + + def __repr__(self): + cn = self.__class__.__name__ + if self.headers: + return f'{cn}(headers={self.headers!r}, data={self._data!r})' + else: + return f'{cn}({self._data!r})' + + def to_html(self, orientation=None, wrapped=True, + with_headers=True, with_newlines=True, + with_metadata=False, max_depth=1): + """Render this Table to HTML. Configure the structure of Table + HTML by subclassing and overriding ``_html_*`` class + attributes. + + Args: + orientation (str): one of 'auto', 'horizontal', or + 'vertical' (or the first letter of any of + those). Default 'auto'. + wrapped (bool): whether or not to include the wrapping + '
' tags. Default ``True``, set to + ``False`` if appending multiple Table outputs or an + otherwise customized HTML wrapping tag is needed. + with_newlines (bool): Set to ``True`` if output should + include added newlines to make the HTML more + readable. Default ``False``. + with_metadata (bool/str): Set to ``True`` if output should + be preceded with a Table of preset metadata, if it + exists. Set to special value ``'bottom'`` if the + metadata Table HTML should come *after* the main HTML output. + max_depth (int): Indicate how deeply to nest HTML tables + before simply reverting to :func:`repr`-ing the nested + data. + + Returns: + A text string of the HTML of the rendered table. + + """ + lines = [] + headers = [] + if with_metadata and self.metadata: + metadata_table = Table.from_data(self.metadata, + max_depth=max_depth) + metadata_html = metadata_table.to_html(with_headers=True, + with_newlines=with_newlines, + with_metadata=False, + max_depth=max_depth) + if with_metadata != 'bottom': + lines.append(metadata_html) + lines.append('
') + + if with_headers and self.headers: + headers.extend(self.headers) + headers.extend([None] * (self._width - len(self.headers))) + if wrapped: + lines.append(self._html_table_tag) + orientation = orientation or 'auto' + ol = orientation[0].lower() + if ol == 'a': + ol = 'h' if len(self) > 1 else 'v' + if ol == 'h': + self._add_horizontal_html_lines(lines, headers=headers, + max_depth=max_depth) + elif ol == 'v': + self._add_vertical_html_lines(lines, headers=headers, + max_depth=max_depth) + else: + raise ValueError("expected one of 'auto', 'vertical', or" + " 'horizontal', not %r" % orientation) + if with_metadata and self.metadata and with_metadata == 'bottom': + lines.append('
') + lines.append(metadata_html) + + if wrapped: + lines.append(self._html_table_tag_close) + sep = '\n' if with_newlines else '' + return sep.join(lines) + + def get_cell_html(self, value): + """Called on each value in an HTML table. By default it simply escapes + the HTML. Override this method to add additional conditions + and behaviors, but take care to ensure the final output is + HTML escaped. + """ + return escape_html(value) + + def _add_horizontal_html_lines(self, lines, headers, max_depth): + esc = self.get_cell_html + new_depth = max_depth - 1 if max_depth > 1 else max_depth + if max_depth > 1: + new_depth = max_depth - 1 + if headers: + _thth = self._html_th_close + self._html_th + lines.append(self._html_thead) + lines.append(self._html_tr + self._html_th + + _thth.join([esc(h) for h in headers]) + + self._html_th_close + self._html_tr_close) + lines.append(self._html_thead_close) + trtd, _tdtd, _td_tr = (self._html_tr + self._html_td, + self._html_td_close + self._html_td, + self._html_td_close + self._html_tr_close) + lines.append(self._html_tbody) + for row in self._data: + if max_depth > 1: + _fill_parts = [] + for cell in row: + if isinstance(cell, Table): + _fill_parts.append(cell.to_html(max_depth=new_depth)) + else: + _fill_parts.append(esc(cell)) + else: + _fill_parts = [esc(c) for c in row] + lines.append(''.join([trtd, _tdtd.join(_fill_parts), _td_tr])) + lines.append(self._html_tbody_close) + + def _add_vertical_html_lines(self, lines, headers, max_depth): + esc = self.get_cell_html + new_depth = max_depth - 1 if max_depth > 1 else max_depth + tr, th, _th = self._html_tr, self._html_th, self._html_th_close + td, _tdtd = self._html_td, self._html_td_close + self._html_td + _td_tr = self._html_td_close + self._html_tr_close + for i in range(self._width): + line_parts = [tr] + if headers: + line_parts.extend([th, esc(headers[i]), _th]) + if max_depth > 1: + new_depth = max_depth - 1 + _fill_parts = [] + for row in self._data: + cell = row[i] + if isinstance(cell, Table): + _fill_parts.append(cell.to_html(max_depth=new_depth)) + else: + _fill_parts.append(esc(row[i])) + else: + _fill_parts = [esc(row[i]) for row in self._data] + line_parts.extend([td, _tdtd.join(_fill_parts), _td_tr]) + lines.append(''.join(line_parts)) + + def to_text(self, with_headers=True, maxlen=None): + """Get the Table's textual representation. Only works well + for Tables with non-recursive data. + + Args: + with_headers (bool): Whether to include a header row at the top. + maxlen (int): Max length of data in each cell. + """ + lines = [] + widths = [] + headers = list(self.headers) + text_data = [[to_text(cell, maxlen=maxlen) for cell in row] + for row in self._data] + for idx in range(self._width): + cur_widths = [len(cur) for cur in text_data] + if with_headers: + cur_widths.append(len(to_text(headers[idx], maxlen=maxlen))) + widths.append(max(cur_widths)) + if with_headers: + lines.append(' | '.join([h.center(widths[i]) + for i, h in enumerate(headers)])) + lines.append('-|-'.join(['-' * w for w in widths])) + for row in text_data: + lines.append(' | '.join([cell.center(widths[j]) + for j, cell in enumerate(row)])) + return '\n'.join(lines) diff --git a/data/miniconda3/lib/python3.13/site-packages/boltons/tbutils.py b/data/miniconda3/lib/python3.13/site-packages/boltons/tbutils.py new file mode 100644 index 0000000000000000000000000000000000000000..bfc49840cc92ccebf5506914c69c14252b158cfe --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/boltons/tbutils.py @@ -0,0 +1,820 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# * The names of the contributors may not be used to endorse or +# promote products derived from this software without specific +# prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""One of the oft-cited tenets of Python is that it is better to ask +forgiveness than permission. That is, there are many cases where it is +more inclusive and correct to handle exceptions than spend extra lines +and execution time checking for conditions. This philosophy makes good +exception handling features all the more important. Unfortunately +Python's :mod:`traceback` module is woefully behind the times. + +The ``tbutils`` module provides two disparate but complementary featuresets: + + 1. With :class:`ExceptionInfo` and :class:`TracebackInfo`, the + ability to extract, construct, manipulate, format, and serialize + exceptions, tracebacks, and callstacks. + 2. With :class:`ParsedException`, the ability to find and parse tracebacks + from captured output such as logs and stdout. + +There is also the :class:`ContextualTracebackInfo` variant of +:class:`TracebackInfo`, which includes much more information from each +frame of the callstack, including values of locals and neighboring +lines of code. +""" + + +import re +import sys +import linecache + + +# TODO: chaining primitives? what are real use cases where these help? + +# TODO: print_* for backwards compatibility +# __all__ = ['extract_stack', 'extract_tb', 'format_exception', +# 'format_exception_only', 'format_list', 'format_stack', +# 'format_tb', 'print_exc', 'format_exc', 'print_exception', +# 'print_last', 'print_stack', 'print_tb'] + + +__all__ = ['ExceptionInfo', 'TracebackInfo', 'Callpoint', + 'ContextualExceptionInfo', 'ContextualTracebackInfo', + 'ContextualCallpoint', 'print_exception', 'ParsedException'] + + +class Callpoint: + """The Callpoint is a lightweight object used to represent a single + entry in the code of a call stack. It stores the code-related + metadata of a given frame. Available attributes are the same as + the parameters below. + + Args: + func_name (str): the function name + lineno (int): the line number + module_name (str): the module name + module_path (str): the filesystem path of the module + lasti (int): the index of bytecode execution + line (str): the single-line code content (if available) + + """ + __slots__ = ('func_name', 'lineno', 'module_name', 'module_path', 'lasti', + 'line') + + def __init__(self, module_name, module_path, func_name, + lineno, lasti, line=None): + self.func_name = func_name + self.lineno = lineno + self.module_name = module_name + self.module_path = module_path + self.lasti = lasti + self.line = line + + def to_dict(self): + "Get a :class:`dict` copy of the Callpoint. Useful for serialization." + ret = {} + for slot in self.__slots__: + try: + val = getattr(self, slot) + except AttributeError: + pass + else: + ret[slot] = str(val) if isinstance(val, _DeferredLine) else val + return ret + + @classmethod + def from_current(cls, level=1): + "Creates a Callpoint from the location of the calling function." + frame = sys._getframe(level) + return cls.from_frame(frame) + + @classmethod + def from_frame(cls, frame): + "Create a Callpoint object from data extracted from the given frame." + func_name = frame.f_code.co_name + lineno = frame.f_lineno + module_name = frame.f_globals.get('__name__', '') + module_path = frame.f_code.co_filename + lasti = frame.f_lasti + line = _DeferredLine(module_path, lineno, frame.f_globals) + return cls(module_name, module_path, func_name, + lineno, lasti, line=line) + + @classmethod + def from_tb(cls, tb): + """Create a Callpoint from the traceback of the current + exception. Main difference with :meth:`from_frame` is that + ``lineno`` and ``lasti`` come from the traceback, which is to + say the line that failed in the try block, not the line + currently being executed (in the except block). + """ + func_name = tb.tb_frame.f_code.co_name + lineno = tb.tb_lineno + lasti = tb.tb_lasti + module_name = tb.tb_frame.f_globals.get('__name__', '') + module_path = tb.tb_frame.f_code.co_filename + line = _DeferredLine(module_path, lineno, tb.tb_frame.f_globals) + return cls(module_name, module_path, func_name, + lineno, lasti, line=line) + + def __repr__(self): + cn = self.__class__.__name__ + args = [getattr(self, s, None) for s in self.__slots__] + if not any(args): + return super().__repr__() + else: + return '{}({})'.format(cn, ', '.join([repr(a) for a in args])) + + def tb_frame_str(self): + """Render the Callpoint as it would appear in a standard printed + Python traceback. Returns a string with filename, line number, + function name, and the actual code line of the error on up to + two lines. + """ + ret = ' File "{}", line {}, in {}\n'.format(self.module_path, + self.lineno, + self.func_name) + if self.line: + ret += f' {str(self.line).strip()}\n' + return ret + + +class _DeferredLine: + """The _DeferredLine type allows Callpoints and TracebackInfos to be + constructed without potentially hitting the filesystem, as is the + normal behavior of the standard Python :mod:`traceback` and + :mod:`linecache` modules. Calling :func:`str` fetches and caches + the line. + + Args: + filename (str): the path of the file containing the line + lineno (int): the number of the line in question + module_globals (dict): an optional dict of module globals, + used to handle advanced use cases using custom module loaders. + + """ + __slots__ = ('filename', 'lineno', '_line', '_mod_name', '_mod_loader') + + def __init__(self, filename, lineno, module_globals=None): + self.filename = filename + self.lineno = lineno + if module_globals is None: + self._mod_name = None + self._mod_loader = None + else: + self._mod_name = module_globals.get('__name__') + self._mod_loader = module_globals.get('__loader__') + + def __eq__(self, other): + return (self.lineno, self.filename) == (other.lineno, other.filename) + + def __ne__(self, other): + return not self == other + + def __str__(self): + ret = getattr(self, '_line', None) + if ret is not None: + return ret + try: + linecache.checkcache(self.filename) + mod_globals = {'__name__': self._mod_name, + '__loader__': self._mod_loader} + line = linecache.getline(self.filename, + self.lineno, + mod_globals) + line = line.rstrip() + except KeyError: + line = '' + self._line = line + return line + + def __repr__(self): + return repr(str(self)) + + def __len__(self): + return len(str(self)) + + +# TODO: dedup frames, look at __eq__ on _DeferredLine +class TracebackInfo: + """The TracebackInfo class provides a basic representation of a stack + trace, be it from an exception being handled or just part of + normal execution. It is basically a wrapper around a list of + :class:`Callpoint` objects representing frames. + + Args: + frames (list): A list of frame objects in the stack. + + .. note :: + + ``TracebackInfo`` can represent both exception tracebacks and + non-exception tracebacks (aka stack traces). As a result, there + is no ``TracebackInfo.from_current()``, as that would be + ambiguous. Instead, call :meth:`TracebackInfo.from_frame` + without the *frame* argument for a stack trace, or + :meth:`TracebackInfo.from_traceback` without the *tb* argument + for an exception traceback. + """ + callpoint_type = Callpoint + + def __init__(self, frames): + self.frames = frames + + @classmethod + def from_frame(cls, frame=None, level=1, limit=None): + """Create a new TracebackInfo *frame* by recurring up in the stack a + max of *limit* times. If *frame* is unset, get the frame from + :func:`sys._getframe` using *level*. + + Args: + frame (types.FrameType): frame object from + :func:`sys._getframe` or elsewhere. Defaults to result + of :func:`sys.get_frame`. + level (int): If *frame* is unset, the desired frame is + this many levels up the stack from the invocation of + this method. Default ``1`` (i.e., caller of this method). + limit (int): max number of parent frames to extract + (defaults to :data:`sys.tracebacklimit`) + + """ + ret = [] + if frame is None: + frame = sys._getframe(level) + if limit is None: + limit = getattr(sys, 'tracebacklimit', 1000) + n = 0 + while frame is not None and n < limit: + item = cls.callpoint_type.from_frame(frame) + ret.append(item) + frame = frame.f_back + n += 1 + ret.reverse() + return cls(ret) + + @classmethod + def from_traceback(cls, tb=None, limit=None): + """Create a new TracebackInfo from the traceback *tb* by recurring + up in the stack a max of *limit* times. If *tb* is unset, get + the traceback from the currently handled exception. If no + exception is being handled, raise a :exc:`ValueError`. + + Args: + + frame (types.TracebackType): traceback object from + :func:`sys.exc_info` or elsewhere. If absent or set to + ``None``, defaults to ``sys.exc_info()[2]``, and + raises a :exc:`ValueError` if no exception is + currently being handled. + limit (int): max number of parent frames to extract + (defaults to :data:`sys.tracebacklimit`) + + """ + ret = [] + if tb is None: + tb = sys.exc_info()[2] + if tb is None: + raise ValueError('no tb set and no exception being handled') + if limit is None: + limit = getattr(sys, 'tracebacklimit', 1000) + n = 0 + while tb is not None and n < limit: + item = cls.callpoint_type.from_tb(tb) + ret.append(item) + tb = tb.tb_next + n += 1 + return cls(ret) + + @classmethod + def from_dict(cls, d): + "Complements :meth:`TracebackInfo.to_dict`." + # TODO: check this. + return cls(d['frames']) + + def to_dict(self): + """Returns a dict with a list of :class:`Callpoint` frames converted + to dicts. + """ + return {'frames': [f.to_dict() for f in self.frames]} + + def __len__(self): + return len(self.frames) + + def __iter__(self): + return iter(self.frames) + + def __repr__(self): + cn = self.__class__.__name__ + + if self.frames: + frame_part = f' last={self.frames[-1]!r}' + else: + frame_part = '' + + return f'<{cn} frames={len(self.frames)}{frame_part}>' + + def __str__(self): + return self.get_formatted() + + def get_formatted(self): + """Returns a string as formatted in the traditional Python + built-in style observable when an exception is not caught. In + other words, mimics :func:`traceback.format_tb` and + :func:`traceback.format_stack`. + """ + ret = 'Traceback (most recent call last):\n' + ret += ''.join([f.tb_frame_str() for f in self.frames]) + return ret + + +class ExceptionInfo: + """An ExceptionInfo object ties together three main fields suitable + for representing an instance of an exception: The exception type + name, a string representation of the exception itself (the + exception message), and information about the traceback (stored as + a :class:`TracebackInfo` object). + + These fields line up with :func:`sys.exc_info`, but unlike the + values returned by that function, ExceptionInfo does not hold any + references to the real exception or traceback. This property makes + it suitable for serialization or long-term retention, without + worrying about formatting pitfalls, circular references, or leaking memory. + + Args: + + exc_type (str): The exception type name. + exc_msg (str): String representation of the exception value. + tb_info (TracebackInfo): Information about the stack trace of the + exception. + + Like the :class:`TracebackInfo`, ExceptionInfo is most commonly + instantiated from one of its classmethods: :meth:`from_exc_info` + or :meth:`from_current`. + """ + + #: Override this in inherited types to control the TracebackInfo type used + tb_info_type = TracebackInfo + + def __init__(self, exc_type, exc_msg, tb_info): + # TODO: additional fields for SyntaxErrors + self.exc_type = exc_type + self.exc_msg = exc_msg + self.tb_info = tb_info + + @classmethod + def from_exc_info(cls, exc_type, exc_value, traceback): + """Create an :class:`ExceptionInfo` object from the exception's type, + value, and traceback, as returned by :func:`sys.exc_info`. See + also :meth:`from_current`. + """ + type_str = exc_type.__name__ + type_mod = exc_type.__module__ + if type_mod not in ("__main__", "__builtin__", "exceptions", "builtins"): + type_str = f'{type_mod}.{type_str}' + val_str = _some_str(exc_value) + tb_info = cls.tb_info_type.from_traceback(traceback) + return cls(type_str, val_str, tb_info) + + @classmethod + def from_current(cls): + """Create an :class:`ExceptionInfo` object from the current exception + being handled, by way of :func:`sys.exc_info`. Will raise an + exception if no exception is currently being handled. + """ + return cls.from_exc_info(*sys.exc_info()) + + def to_dict(self): + """Get a :class:`dict` representation of the ExceptionInfo, suitable + for JSON serialization. + """ + return {'exc_type': self.exc_type, + 'exc_msg': self.exc_msg, + 'exc_tb': self.tb_info.to_dict()} + + def __repr__(self): + cn = self.__class__.__name__ + try: + len_frames = len(self.tb_info.frames) + last_frame = f', last={self.tb_info.frames[-1]!r}' + except Exception: + len_frames = 0 + last_frame = '' + args = (cn, self.exc_type, self.exc_msg, len_frames, last_frame) + return '<%s [%s: %s] (%s frames%s)>' % args + + def get_formatted(self): + """Returns a string formatted in the traditional Python + built-in style observable when an exception is not caught. In + other words, mimics :func:`traceback.format_exception`. + """ + # TODO: add SyntaxError formatting + tb_str = self.tb_info.get_formatted() + return ''.join([tb_str, f'{self.exc_type}: {self.exc_msg}']) + + def get_formatted_exception_only(self): + return f'{self.exc_type}: {self.exc_msg}' + + +class ContextualCallpoint(Callpoint): + """The ContextualCallpoint is a :class:`Callpoint` subtype with the + exact same API and storing two additional values: + + 1. :func:`repr` outputs for local variables from the Callpoint's scope + 2. A number of lines before and after the Callpoint's line of code + + The ContextualCallpoint is used by the :class:`ContextualTracebackInfo`. + """ + def __init__(self, *a, **kw): + self.local_reprs = kw.pop('local_reprs', {}) + self.pre_lines = kw.pop('pre_lines', []) + self.post_lines = kw.pop('post_lines', []) + super().__init__(*a, **kw) + + @classmethod + def from_frame(cls, frame): + "Identical to :meth:`Callpoint.from_frame`" + ret = super().from_frame(frame) + ret._populate_local_reprs(frame.f_locals) + ret._populate_context_lines() + return ret + + @classmethod + def from_tb(cls, tb): + "Identical to :meth:`Callpoint.from_tb`" + ret = super().from_tb(tb) + ret._populate_local_reprs(tb.tb_frame.f_locals) + ret._populate_context_lines() + return ret + + def _populate_context_lines(self, pivot=8): + DL, lineno = _DeferredLine, self.lineno + try: + module_globals = self.line.module_globals + except AttributeError: + module_globals = None + start_line = max(0, lineno - pivot) + pre_lines = [DL(self.module_path, ln, module_globals) + for ln in range(start_line, lineno)] + self.pre_lines[:] = pre_lines + post_lines = [DL(self.module_path, ln, module_globals) + for ln in range(lineno + 1, lineno + 1 + pivot)] + self.post_lines[:] = post_lines + return + + def _populate_local_reprs(self, f_locals): + local_reprs = self.local_reprs + for k, v in f_locals.items(): + try: + local_reprs[k] = repr(v) + except Exception: + surrogate = '' % type(v).__name__ + local_reprs[k] = surrogate + return + + def to_dict(self): + """ + Same principle as :meth:`Callpoint.to_dict`, but with the added + contextual values. With ``ContextualCallpoint.to_dict()``, + each frame will now be represented like:: + + {'func_name': 'print_example', + 'lineno': 0, + 'module_name': 'example_module', + 'module_path': '/home/example/example_module.pyc', + 'lasti': 0, + 'line': 'print "example"', + 'locals': {'variable': '"value"'}, + 'pre_lines': ['variable = "value"'], + 'post_lines': []} + + The locals dictionary and line lists are copies and can be mutated + freely. + """ + ret = super().to_dict() + ret['locals'] = dict(self.local_reprs) + + # get the line numbers and textual lines + # without assuming DeferredLines + start_line = self.lineno - len(self.pre_lines) + pre_lines = [{'lineno': start_line + i, 'line': str(l)} + for i, l in enumerate(self.pre_lines)] + # trim off leading empty lines + for i, item in enumerate(pre_lines): + if item['line']: + break + if i: + pre_lines = pre_lines[i:] + ret['pre_lines'] = pre_lines + + # now post_lines + post_lines = [{'lineno': self.lineno + i, 'line': str(l)} + for i, l in enumerate(self.post_lines)] + _last = 0 + for i, item in enumerate(post_lines): + if item['line']: + _last = i + post_lines = post_lines[:_last + 1] + ret['post_lines'] = post_lines + return ret + + +class ContextualTracebackInfo(TracebackInfo): + """The ContextualTracebackInfo type is a :class:`TracebackInfo` + subtype that is used by :class:`ContextualExceptionInfo` and uses + the :class:`ContextualCallpoint` as its frame-representing + primitive. + """ + callpoint_type = ContextualCallpoint + + +class ContextualExceptionInfo(ExceptionInfo): + """The ContextualTracebackInfo type is a :class:`TracebackInfo` + subtype that uses the :class:`ContextualCallpoint` as its + frame-representing primitive. + + It carries with it most of the exception information required to + recreate the widely recognizable "500" page for debugging Django + applications. + """ + tb_info_type = ContextualTracebackInfo + + +# TODO: clean up & reimplement -- specifically for syntax errors +def format_exception_only(etype, value): + """Format the exception part of a traceback. + + The arguments are the exception type and value such as given by + sys.last_type and sys.last_value. The return value is a list of + strings, each ending in a newline. + + Normally, the list contains a single string; however, for + SyntaxError exceptions, it contains several lines that (when + printed) display detailed information about where the syntax + error occurred. + + The message indicating which exception occurred is always the last + string in the list. + + """ + # Gracefully handle (the way Python 2.4 and earlier did) the case of + # being called with (None, None). + if etype is None: + return [_format_final_exc_line(etype, value)] + + stype = etype.__name__ + smod = etype.__module__ + if smod not in ("__main__", "builtins", "exceptions"): + stype = smod + '.' + stype + + if not issubclass(etype, SyntaxError): + return [_format_final_exc_line(stype, value)] + + # It was a syntax error; show exactly where the problem was found. + lines = [] + filename = value.filename or "" + lineno = str(value.lineno) or '?' + lines.append(f' File "{filename}", line {lineno}\n') + badline = value.text + offset = value.offset + if badline is not None: + lines.append(' %s\n' % badline.strip()) + if offset is not None: + caretspace = badline.rstrip('\n')[:offset].lstrip() + # non-space whitespace (likes tabs) must be kept for alignment + caretspace = ((c.isspace() and c or ' ') for c in caretspace) + # only three spaces to account for offset1 == pos 0 + lines.append(' %s^\n' % ''.join(caretspace)) + msg = value.msg or "" + lines.append(f"{stype}: {msg}\n") + return lines + + +# TODO: use asciify, improved if necessary +def _some_str(value): + try: + return str(value) + except Exception: + pass + return '' % type(value).__name__ + + +def _format_final_exc_line(etype, value): + valuestr = _some_str(value) + if value is None or not valuestr: + line = "%s\n" % etype + else: + line = f"{etype}: {valuestr}\n" + return line + + +def print_exception(etype, value, tb, limit=None, file=None): + """Print exception up to 'limit' stack trace entries from 'tb' to 'file'. + + This differs from print_tb() in the following ways: (1) if + traceback is not None, it prints a header "Traceback (most recent + call last):"; (2) it prints the exception type and value after the + stack trace; (3) if type is SyntaxError and value has the + appropriate format, it prints the line where the syntax error + occurred with a caret on the next line indicating the approximate + position of the error. + """ + + if file is None: + file = sys.stderr + if tb: + tbi = TracebackInfo.from_traceback(tb, limit) + print(str(tbi), end='', file=file) + + for line in format_exception_only(etype, value): + print(line, end='', file=file) + + +def fix_print_exception(): + """ + Sets the default exception hook :func:`sys.excepthook` to the + :func:`tbutils.print_exception` that uses all the ``tbutils`` + facilities to provide a consistent output behavior. + """ + sys.excepthook = print_exception + + +_frame_re = re.compile(r'^File "(?P.+)", line (?P\d+)' + r', in (?P.+)$') +_se_frame_re = re.compile(r'^File "(?P.+)", line (?P\d+)') +_underline_re = re.compile(r'^[~^ ]*$') + +# TODO: ParsedException generator over large bodies of text + +class ParsedException: + """Stores a parsed traceback and exception as would be typically + output by :func:`sys.excepthook` or + :func:`traceback.print_exception`. + + .. note: + + Does not currently store SyntaxError details such as column. + + """ + def __init__(self, exc_type_name, exc_msg, frames=None): + self.exc_type = exc_type_name + self.exc_msg = exc_msg + self.frames = list(frames or []) + + @property + def source_file(self): + """ + The file path of module containing the function that raised the + exception, or None if not available. + """ + try: + return self.frames[-1]['filepath'] + except IndexError: + return None + + def to_dict(self): + "Get a copy as a JSON-serializable :class:`dict`." + return {'exc_type': self.exc_type, + 'exc_msg': self.exc_msg, + 'frames': list(self.frames)} + + def __repr__(self): + cn = self.__class__.__name__ + return ('%s(%r, %r, frames=%r)' + % (cn, self.exc_type, self.exc_msg, self.frames)) + + def to_string(self): + """Formats the exception and its traceback into the standard format, + as returned by the traceback module. + + ``ParsedException.from_string(text).to_string()`` should yield + ``text``. + + .. note:: + + Note that this method does not output "anchors" (e.g., + ``~~~~~^^``), as were added in Python 3.13. See the built-in + ``traceback`` module if these are necessary. + """ + lines = ['Traceback (most recent call last):'] + + for frame in self.frames: + lines.append(' File "{}", line {}, in {}'.format(frame['filepath'], + frame['lineno'], + frame['funcname'])) + source_line = frame.get('source_line') + if source_line: + lines.append(f' {source_line}') + if self.exc_msg: + lines.append(f'{self.exc_type}: {self.exc_msg}') + else: + lines.append(f'{self.exc_type}') + return '\n'.join(lines) + + @classmethod + def from_string(cls, tb_str): + """Parse a traceback and exception from the text *tb_str*. This text + is expected to have been decoded, otherwise it will be + interpreted as UTF-8. + + This method does not search a larger body of text for + tracebacks. If the first line of the text passed does not + match one of the known patterns, a :exc:`ValueError` will be + raised. This method will ignore trailing text after the end of + the first traceback. + + Args: + tb_str (str): The traceback text (:class:`unicode` or UTF-8 bytes) + """ + if not isinstance(tb_str, str): + tb_str = tb_str.decode('utf-8') + tb_lines = tb_str.lstrip().splitlines() + + # First off, handle some ignored exceptions. These can be the + # result of exceptions raised by __del__ during garbage + # collection + while tb_lines: + cl = tb_lines[-1] + if cl.startswith('Exception ') and cl.endswith('ignored'): + tb_lines.pop() + else: + break + if tb_lines and tb_lines[0].strip() == 'Traceback (most recent call last):': + start_line = 1 + frame_re = _frame_re + elif len(tb_lines) > 1 and tb_lines[-2].lstrip().startswith('^'): + # This is to handle the slight formatting difference + # associated with SyntaxErrors, which also don't really + # have tracebacks + start_line = 0 + frame_re = _se_frame_re + else: + raise ValueError('unrecognized traceback string format') + + frames = [] + line_no = start_line + while True: + frame_line = tb_lines[line_no].strip() + frame_match = frame_re.match(frame_line) + if frame_match: + frame_dict = frame_match.groupdict() + try: + next_line = tb_lines[line_no + 1] + except IndexError: + # We read what we could + next_line = '' + next_line_stripped = next_line.strip() + if ( + frame_re.match(next_line_stripped) or + # The exception message will not be indented + # This check is to avoid overrunning on eval-like + # tracebacks where the last frame doesn't have source + # code in the traceback + not next_line.startswith(' ') + ): + frame_dict['source_line'] = '' + else: + frame_dict['source_line'] = next_line_stripped + line_no += 1 + if _underline_re.match(tb_lines[line_no + 1]): + # To deal with anchors + line_no += 1 + else: + break + line_no += 1 + frames.append(frame_dict) + + try: + exc_line = '\n'.join(tb_lines[line_no:]) + exc_type, _, exc_msg = exc_line.partition(': ') + except Exception: + exc_type, exc_msg = '', '' + + return cls(exc_type, exc_msg, frames) + + +ParsedTB = ParsedException # legacy alias diff --git a/data/miniconda3/lib/python3.13/site-packages/boltons/timeutils.py b/data/miniconda3/lib/python3.13/site-packages/boltons/timeutils.py new file mode 100644 index 0000000000000000000000000000000000000000..82f201ee94699223728de0cc1799b755707e2b65 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/boltons/timeutils.py @@ -0,0 +1,566 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# * The names of the contributors may not be used to endorse or +# promote products derived from this software without specific +# prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Python's :mod:`datetime` module provides some of the most complex +and powerful primitives in the Python standard library. Time is +nontrivial, but thankfully its support is first-class in +Python. ``dateutils`` provides some additional tools for working with +time. + +Additionally, timeutils provides a few basic utilities for working +with timezones in Python. The Python :mod:`datetime` module's +documentation describes how to create a +:class:`~datetime.datetime`-compatible :class:`~datetime.tzinfo` +subtype. It even provides a few examples. + +The following module defines usable forms of the timezones in those +docs, as well as a couple other useful ones, :data:`UTC` (aka GMT) and +:data:`LocalTZ` (representing the local timezone as configured in the +operating system). For timezones beyond these, as well as a higher +degree of accuracy in corner cases, check out `pytz`_ and `dateutil`_. + +.. _pytz: https://pypi.python.org/pypi/pytz +.. _dateutil: https://dateutil.readthedocs.io/en/stable/index.html +""" + +import re +import time +import bisect +import operator +from datetime import tzinfo, timedelta, date, datetime, timezone + + +# For legacy compatibility. +# boltons used to offer an implementation of total_seconds for Python <2.7 +total_seconds = timedelta.total_seconds + + +def dt_to_timestamp(dt): + """Converts from a :class:`~datetime.datetime` object to an integer + timestamp, suitable interoperation with :func:`time.time` and + other `Epoch-based timestamps`. + + .. _Epoch-based timestamps: https://en.wikipedia.org/wiki/Unix_time + + >>> timestamp = int(time.time()) + >>> utc_dt = datetime.fromtimestamp(timestamp, timezone.utc) + >>> timestamp - dt_to_timestamp(utc_dt) + 0.0 + + ``dt_to_timestamp`` supports both timezone-aware and naïve + :class:`~datetime.datetime` objects. Note that it assumes naïve + datetime objects are implied UTC, such as those generated with + :meth:`datetime.datetime.utcnow`. If your datetime objects are + local time, such as those generated with + :meth:`datetime.datetime.now`, first convert it using the + :meth:`datetime.datetime.replace` method with ``tzinfo=`` + :class:`LocalTZ` object in this module, then pass the result of + that to ``dt_to_timestamp``. + """ + if dt.tzinfo: + td = dt - EPOCH_AWARE + else: + td = dt.replace(tzinfo=timezone.utc) - EPOCH_AWARE + return timedelta.total_seconds(td) + + +_NONDIGIT_RE = re.compile(r'\D') + + +def isoparse(iso_str): + """Parses the limited subset of `ISO8601-formatted time`_ strings as + returned by :meth:`datetime.datetime.isoformat`. + + >>> epoch_dt = datetime.fromtimestamp(0, timezone.utc).replace(tzinfo=None) + >>> iso_str = epoch_dt.isoformat() + >>> print(iso_str) + 1970-01-01T00:00:00 + >>> isoparse(iso_str) + datetime.datetime(1970, 1, 1, 0, 0) + + >>> utcnow = datetime.now(timezone.utc).replace(tzinfo=None) + >>> utcnow == isoparse(utcnow.isoformat()) + True + + For further datetime parsing, see the `iso8601`_ package for strict + ISO parsing and `dateutil`_ package for loose parsing and more. + + .. _ISO8601-formatted time: https://en.wikipedia.org/wiki/ISO_8601 + .. _iso8601: https://pypi.python.org/pypi/iso8601 + .. _dateutil: https://pypi.python.org/pypi/python-dateutil + + """ + dt_args = [int(p) for p in _NONDIGIT_RE.split(iso_str)] + return datetime(*dt_args) + + +_BOUNDS = [(0, timedelta(seconds=1), 'second'), + (1, timedelta(seconds=60), 'minute'), + (1, timedelta(seconds=3600), 'hour'), + (1, timedelta(days=1), 'day'), + (1, timedelta(days=7), 'week'), + (2, timedelta(days=30), 'month'), + (1, timedelta(days=365), 'year')] +_BOUNDS = [(b[0] * b[1], b[1], b[2]) for b in _BOUNDS] +_BOUND_DELTAS = [b[0] for b in _BOUNDS] + +_FLOAT_PATTERN = r'[+-]?\ *(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?' +_PARSE_TD_RE = re.compile(r"((?P%s)\s*(?P\w)\w*)" % _FLOAT_PATTERN) +_PARSE_TD_KW_MAP = {unit[0]: unit + 's' + for _, _, unit in reversed(_BOUNDS[:-2])} + + +def parse_timedelta(text): + """Robustly parses a short text description of a time period into a + :class:`datetime.timedelta`. Supports weeks, days, hours, minutes, + and seconds, with or without decimal points: + + Args: + text (str): Text to parse. + Returns: + datetime.timedelta + Raises: + ValueError: on parse failure. + + >>> parse_td('1d 2h 3.5m 0s') == timedelta(days=1, seconds=7410) + True + + Also supports full words and whitespace. + + >>> parse_td('2 weeks 1 day') == timedelta(days=15) + True + + Negative times are supported, too: + + >>> parse_td('-1.5 weeks 3m 20s') == timedelta(days=-11, seconds=43400) + True + """ + td_kwargs = {} + for match in _PARSE_TD_RE.finditer(text): + value, unit = match.group('value'), match.group('unit') + try: + unit_key = _PARSE_TD_KW_MAP[unit] + except KeyError: + raise ValueError('invalid time unit %r, expected one of %r' + % (unit, _PARSE_TD_KW_MAP.keys())) + try: + value = float(value) + except ValueError: + raise ValueError('invalid time value for unit %r: %r' + % (unit, value)) + td_kwargs[unit_key] = value + return timedelta(**td_kwargs) + + +parse_td = parse_timedelta # legacy alias + + +def _cardinalize_time_unit(unit, value): + # removes dependency on strutils; nice and simple because + # all time units cardinalize normally + if value == 1: + return unit + return unit + 's' + + +def decimal_relative_time(d, other=None, ndigits=0, cardinalize=True): + """Get a tuple representing the relative time difference between two + :class:`~datetime.datetime` objects or one + :class:`~datetime.datetime` and now. + + Args: + d (datetime): The first datetime object. + other (datetime): An optional second datetime object. If + unset, defaults to the current time as determined + :meth:`datetime.utcnow`. + ndigits (int): The number of decimal digits to round to, + defaults to ``0``. + cardinalize (bool): Whether to pluralize the time unit if + appropriate, defaults to ``True``. + Returns: + (float, str): A tuple of the :class:`float` difference and + respective unit of time, pluralized if appropriate and + *cardinalize* is set to ``True``. + + Unlike :func:`relative_time`, this method's return is amenable to + localization into other languages and custom phrasing and + formatting. + + >>> now = datetime.now(timezone.utc).replace(tzinfo=None) + >>> decimal_relative_time(now - timedelta(days=1, seconds=3600), now) + (1.0, 'day') + >>> decimal_relative_time(now - timedelta(seconds=0.002), now, ndigits=5) + (0.002, 'seconds') + >>> decimal_relative_time(now, now - timedelta(days=900), ndigits=1) + (-2.5, 'years') + + """ + if other is None: + other = datetime.now(timezone.utc).replace(tzinfo=None) + diff = other - d + diff_seconds = timedelta.total_seconds(diff) + abs_diff = abs(diff) + b_idx = bisect.bisect(_BOUND_DELTAS, abs_diff) - 1 + bbound, bunit, bname = _BOUNDS[b_idx] + f_diff = diff_seconds / timedelta.total_seconds(bunit) + rounded_diff = round(f_diff, ndigits) + if cardinalize: + return rounded_diff, _cardinalize_time_unit(bname, abs(rounded_diff)) + return rounded_diff, bname + + +def relative_time(d, other=None, ndigits=0): + """Get a string representation of the difference between two + :class:`~datetime.datetime` objects or one + :class:`~datetime.datetime` and the current time. Handles past and + future times. + + Args: + d (datetime): The first datetime object. + other (datetime): An optional second datetime object. If + unset, defaults to the current time as determined + :meth:`datetime.utcnow`. + ndigits (int): The number of decimal digits to round to, + defaults to ``0``. + Returns: + A short English-language string. + + >>> now = datetime.now(timezone.utc).replace(tzinfo=None) + >>> relative_time(now, ndigits=1) + '0 seconds ago' + >>> relative_time(now - timedelta(days=1, seconds=36000), ndigits=1) + '1.4 days ago' + >>> relative_time(now + timedelta(days=7), now, ndigits=1) + '1 week from now' + + """ + drt, unit = decimal_relative_time(d, other, ndigits, cardinalize=True) + phrase = 'ago' + if drt < 0: + phrase = 'from now' + return f'{abs(drt):g} {unit} {phrase}' + + +def strpdate(string, format): + """Parse the date string according to the format in `format`. Returns a + :class:`date` object. Internally, :meth:`datetime.strptime` is used to + parse the string and thus conversion specifiers for time fields (e.g. `%H`) + may be provided; these will be parsed but ignored. + + Args: + string (str): The date string to be parsed. + format (str): The `strptime`_-style date format string. + Returns: + datetime.date + + .. _`strptime`: https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior + + >>> strpdate('2016-02-14', '%Y-%m-%d') + datetime.date(2016, 2, 14) + >>> strpdate('26/12 (2015)', '%d/%m (%Y)') + datetime.date(2015, 12, 26) + >>> strpdate('20151231 23:59:59', '%Y%m%d %H:%M:%S') + datetime.date(2015, 12, 31) + >>> strpdate('20160101 00:00:00.001', '%Y%m%d %H:%M:%S.%f') + datetime.date(2016, 1, 1) + """ + whence = datetime.strptime(string, format) + return whence.date() + + +def daterange(start, stop, step=1, inclusive=False): + """In the spirit of :func:`range` and :func:`xrange`, the `daterange` + generator that yields a sequence of :class:`~datetime.date` + objects, starting at *start*, incrementing by *step*, until *stop* + is reached. + + When *inclusive* is True, the final date may be *stop*, **if** + *step* falls evenly on it. By default, *step* is one day. See + details below for many more details. + + Args: + start (datetime.date): The starting date The first value in + the sequence. + stop (datetime.date): The stopping date. By default not + included in return. Can be `None` to yield an infinite + sequence. + step (int): The value to increment *start* by to reach + *stop*. Can be an :class:`int` number of days, a + :class:`datetime.timedelta`, or a :class:`tuple` of integers, + `(year, month, day)`. Positive and negative *step* values + are supported. + inclusive (bool): Whether or not the *stop* date can be + returned. *stop* is only returned when a *step* falls evenly + on it. + + >>> christmas = date(year=2015, month=12, day=25) + >>> boxing_day = date(year=2015, month=12, day=26) + >>> new_year = date(year=2016, month=1, day=1) + >>> for day in daterange(christmas, new_year): + ... print(repr(day)) + datetime.date(2015, 12, 25) + datetime.date(2015, 12, 26) + datetime.date(2015, 12, 27) + datetime.date(2015, 12, 28) + datetime.date(2015, 12, 29) + datetime.date(2015, 12, 30) + datetime.date(2015, 12, 31) + >>> for day in daterange(christmas, boxing_day): + ... print(repr(day)) + datetime.date(2015, 12, 25) + >>> for day in daterange(date(2017, 5, 1), date(2017, 8, 1), + ... step=(0, 1, 0), inclusive=True): + ... print(repr(day)) + datetime.date(2017, 5, 1) + datetime.date(2017, 6, 1) + datetime.date(2017, 7, 1) + datetime.date(2017, 8, 1) + + *Be careful when using stop=None, as this will yield an infinite + sequence of dates.* + """ + if not isinstance(start, date): + raise TypeError("start expected datetime.date instance") + if stop and not isinstance(stop, date): + raise TypeError("stop expected datetime.date instance or None") + try: + y_step, m_step, d_step = step + except TypeError: + y_step, m_step, d_step = 0, 0, step + else: + y_step, m_step = int(y_step), int(m_step) + if isinstance(d_step, int): + d_step = timedelta(days=int(d_step)) + elif isinstance(d_step, timedelta): + pass + else: + raise ValueError('step expected int, timedelta, or tuple' + ' (year, month, day), not: %r' % step) + + m_step += y_step * 12 + + if stop is None: + finished = lambda now, stop: False + elif start <= stop: + finished = operator.gt if inclusive else operator.ge + else: + finished = operator.lt if inclusive else operator.le + now = start + + while not finished(now, stop): + yield now + if m_step: + m_y_step, cur_month = divmod((now.month - 1) + m_step, 12) + now = now.replace(year=now.year + m_y_step, + month=(cur_month + 1)) + now = now + d_step + return + + +# Timezone support (brought in from tzutils) + + +ZERO = timedelta(0) +HOUR = timedelta(hours=1) + + +class ConstantTZInfo(tzinfo): + """ + A :class:`~datetime.tzinfo` subtype whose *offset* remains constant + (no daylight savings). + + Args: + name (str): Name of the timezone. + offset (datetime.timedelta): Offset of the timezone. + """ + def __init__(self, name="ConstantTZ", offset=ZERO): + self.name = name + self.offset = offset + + @property + def utcoffset_hours(self): + return timedelta.total_seconds(self.offset) / (60 * 60) + + def utcoffset(self, dt): + return self.offset + + def tzname(self, dt): + return self.name + + def dst(self, dt): + return ZERO + + def __repr__(self): + cn = self.__class__.__name__ + return f'{cn}(name={self.name!r}, offset={self.offset!r})' + + +UTC = ConstantTZInfo('UTC') +EPOCH_AWARE = datetime.fromtimestamp(0, UTC) + + +class LocalTZInfo(tzinfo): + """The ``LocalTZInfo`` type takes data available in the time module + about the local timezone and makes a practical + :class:`datetime.tzinfo` to represent the timezone settings of the + operating system. + + For a more in-depth integration with the operating system, check + out `tzlocal`_. It builds on `pytz`_ and implements heuristics for + many versions of major operating systems to provide the official + ``pytz`` tzinfo, instead of the LocalTZ generalization. + + .. _tzlocal: https://pypi.python.org/pypi/tzlocal + .. _pytz: https://pypi.python.org/pypi/pytz + + """ + _std_offset = timedelta(seconds=-time.timezone) + _dst_offset = _std_offset + if time.daylight: + _dst_offset = timedelta(seconds=-time.altzone) + + def is_dst(self, dt): + dt_t = (dt.year, dt.month, dt.day, dt.hour, dt.minute, + dt.second, dt.weekday(), 0, -1) + local_t = time.localtime(time.mktime(dt_t)) + return local_t.tm_isdst > 0 + + def utcoffset(self, dt): + if self.is_dst(dt): + return self._dst_offset + return self._std_offset + + def dst(self, dt): + if self.is_dst(dt): + return self._dst_offset - self._std_offset + return ZERO + + def tzname(self, dt): + return time.tzname[self.is_dst(dt)] + + def __repr__(self): + return '%s()' % self.__class__.__name__ + + +LocalTZ = LocalTZInfo() + + +def _first_sunday_on_or_after(dt): + days_to_go = 6 - dt.weekday() + if days_to_go: + dt += timedelta(days_to_go) + return dt + + +# US DST Rules +# +# This is a simplified (i.e., wrong for a few cases) set of rules for US +# DST start and end times. For a complete and up-to-date set of DST rules +# and timezone definitions, visit the Olson Database (or try pytz): +# http://www.twinsun.com/tz/tz-link.htm +# http://sourceforge.net/projects/pytz/ (might not be up-to-date) +# +# In the US, since 2007, DST starts at 2am (standard time) on the second +# Sunday in March, which is the first Sunday on or after Mar 8. +DSTSTART_2007 = datetime(1, 3, 8, 2) +# and ends at 2am (DST time; 1am standard time) on the first Sunday of Nov. +DSTEND_2007 = datetime(1, 11, 1, 1) +# From 1987 to 2006, DST used to start at 2am (standard time) on the first +# Sunday in April and to end at 2am (DST time; 1am standard time) on the last +# Sunday of October, which is the first Sunday on or after Oct 25. +DSTSTART_1987_2006 = datetime(1, 4, 1, 2) +DSTEND_1987_2006 = datetime(1, 10, 25, 1) +# From 1967 to 1986, DST used to start at 2am (standard time) on the last +# Sunday in April (the one on or after April 24) and to end at 2am (DST time; +# 1am standard time) on the last Sunday of October, which is the first Sunday +# on or after Oct 25. +DSTSTART_1967_1986 = datetime(1, 4, 24, 2) +DSTEND_1967_1986 = DSTEND_1987_2006 + + +class USTimeZone(tzinfo): + """Copied directly from the Python docs, the ``USTimeZone`` is a + :class:`datetime.tzinfo` subtype used to create the + :data:`Eastern`, :data:`Central`, :data:`Mountain`, and + :data:`Pacific` tzinfo types. + """ + def __init__(self, hours, reprname, stdname, dstname): + self.stdoffset = timedelta(hours=hours) + self.reprname = reprname + self.stdname = stdname + self.dstname = dstname + + def __repr__(self): + return self.reprname + + def tzname(self, dt): + if self.dst(dt): + return self.dstname + else: + return self.stdname + + def utcoffset(self, dt): + return self.stdoffset + self.dst(dt) + + def dst(self, dt): + if dt is None or dt.tzinfo is None: + # An exception may be sensible here, in one or both cases. + # It depends on how you want to treat them. The default + # fromutc() implementation (called by the default astimezone() + # implementation) passes a datetime with dt.tzinfo is self. + return ZERO + assert dt.tzinfo is self + + # Find start and end times for US DST. For years before 1967, return + # ZERO for no DST. + if 2006 < dt.year: + dststart, dstend = DSTSTART_2007, DSTEND_2007 + elif 1986 < dt.year < 2007: + dststart, dstend = DSTSTART_1987_2006, DSTEND_1987_2006 + elif 1966 < dt.year < 1987: + dststart, dstend = DSTSTART_1967_1986, DSTEND_1967_1986 + else: + return ZERO + + start = _first_sunday_on_or_after(dststart.replace(year=dt.year)) + end = _first_sunday_on_or_after(dstend.replace(year=dt.year)) + + # Can't compare naive to aware objects, so strip the timezone + # from dt first. + if start <= dt.replace(tzinfo=None) < end: + return HOUR + else: + return ZERO + + +Eastern = USTimeZone(-5, "Eastern", "EST", "EDT") +Central = USTimeZone(-6, "Central", "CST", "CDT") +Mountain = USTimeZone(-7, "Mountain", "MST", "MDT") +Pacific = USTimeZone(-8, "Pacific", "PST", "PDT") diff --git a/data/miniconda3/lib/python3.13/site-packages/boltons/typeutils.py b/data/miniconda3/lib/python3.13/site-packages/boltons/typeutils.py new file mode 100644 index 0000000000000000000000000000000000000000..875e2e2b0412bc7fee0a11726371bac402566ee5 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/boltons/typeutils.py @@ -0,0 +1,180 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# * The names of the contributors may not be used to endorse or +# promote products derived from this software without specific +# prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Python's built-in :mod:`functools` module builds several useful +utilities on top of Python's first-class function support. +``typeutils`` attempts to do the same for metaprogramming with types +and instances. +""" +import sys +from collections import deque + +_issubclass = issubclass + + +def make_sentinel(name='_MISSING', var_name=None): + """Creates and returns a new **instance** of a new class, suitable for + usage as a "sentinel", a kind of singleton often used to indicate + a value is missing when ``None`` is a valid input. + + Args: + name (str): Name of the Sentinel + var_name (str): Set this name to the name of the variable in + its respective module enable pickleability. Note: + pickleable sentinels should be global constants at the top + level of their module. + + >>> make_sentinel(var_name='_MISSING') + _MISSING + + The most common use cases here in boltons are as default values + for optional function arguments, partly because of its + less-confusing appearance in automatically generated + documentation. Sentinels also function well as placeholders in queues + and linked lists. + + .. note:: + + By design, additional calls to ``make_sentinel`` with the same + values will not produce equivalent objects. + + >>> make_sentinel('TEST') == make_sentinel('TEST') + False + >>> type(make_sentinel('TEST')) == type(make_sentinel('TEST')) + False + + """ + class Sentinel: + def __init__(self): + self.name = name + self.var_name = var_name + + def __repr__(self): + if self.var_name: + return self.var_name + return f'{self.__class__.__name__}({self.name!r})' + + if var_name: + def __reduce__(self): + return self.var_name + + def __bool__(self): + return False + + def __copy__(self): + return self + + def __deepcopy__(self, _memo): + return self + + if var_name: + frame = sys._getframe(1) + module = frame.f_globals.get('__name__') + if not module or module not in sys.modules: + raise ValueError('Pickleable sentinel objects (with var_name) can only' + ' be created from top-level module scopes') + Sentinel.__module__ = module + + return Sentinel() + + +def issubclass(subclass, baseclass): + """Just like the built-in :func:`issubclass`, this function checks + whether *subclass* is inherited from *baseclass*. Unlike the + built-in function, this ``issubclass`` will simply return + ``False`` if either argument is not suitable (e.g., if *subclass* + is not an instance of :class:`type`), instead of raising + :exc:`TypeError`. + + Args: + subclass (type): The target class to check. + baseclass (type): The base class *subclass* will be checked against. + + >>> class MyObject(object): pass + ... + >>> issubclass(MyObject, object) # always a fun fact + True + >>> issubclass('hi', 'friend') + False + """ + try: + return _issubclass(subclass, baseclass) + except TypeError: + return False + + +def get_all_subclasses(cls): + """Recursively finds and returns a :class:`list` of all types + inherited from *cls*. + + >>> class A(object): + ... pass + ... + >>> class B(A): + ... pass + ... + >>> class C(B): + ... pass + ... + >>> class D(A): + ... pass + ... + >>> [t.__name__ for t in get_all_subclasses(A)] + ['B', 'D', 'C'] + >>> [t.__name__ for t in get_all_subclasses(B)] + ['C'] + + """ + try: + to_check = deque(cls.__subclasses__()) + except (AttributeError, TypeError): + raise TypeError('expected type object, not %r' % cls) + seen, ret = set(), [] + while to_check: + cur = to_check.popleft() + if cur in seen: + continue + ret.append(cur) + seen.add(cur) + to_check.extend(cur.__subclasses__()) + return ret + + +class classproperty: + """Much like a :class:`property`, but the wrapped get function is a + class method. For simplicity, only read-only properties are + implemented. + """ + + def __init__(self, fn): + self.fn = fn + + def __get__(self, instance, cls): + return self.fn(cls) diff --git a/data/miniconda3/lib/python3.13/site-packages/boltons/urlutils.py b/data/miniconda3/lib/python3.13/site-packages/boltons/urlutils.py new file mode 100644 index 0000000000000000000000000000000000000000..45d3e73e87820a34a622540cdf1a29cb34b895c3 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/boltons/urlutils.py @@ -0,0 +1,1606 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# * The names of the contributors may not be used to endorse or +# promote products derived from this software without specific +# prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +""":mod:`urlutils` is a module dedicated to one of software's most +versatile, well-aged, and beloved data structures: the URL, also known +as the `Uniform Resource Locator`_. + +Among other things, this module is a full reimplementation of URLs, +without any reliance on the :mod:`urlparse` or :mod:`urllib` standard +library modules. The centerpiece and top-level interface of urlutils +is the :class:`URL` type. Also featured is the :func:`find_all_links` +convenience function. Some low-level functions and constants are also +below. + +The implementations in this module are based heavily on `RFC 3986`_ and +`RFC 3987`_, and incorporates details from several other RFCs and `W3C +documents`_. + +.. _Uniform Resource Locator: https://en.wikipedia.org/wiki/Uniform_Resource_Locator +.. _RFC 3986: https://tools.ietf.org/html/rfc3986 +.. _RFC 3987: https://tools.ietf.org/html/rfc3987 +.. _W3C documents: https://www.w3.org/TR/uri-clarification/ + +""" + +import re +import socket +import string +from unicodedata import normalize + +# The unreserved URI characters (per RFC 3986 Section 2.3) +_UNRESERVED_CHARS = frozenset('~-._0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz') + +# URL parsing regex (based on RFC 3986 Appendix B, with modifications) +_URL_RE = re.compile(r'^((?P[^:/?#]+):)?' + r'((?P<_netloc_sep>//)(?P[^/?#]*))?' + r'(?P[^?#]*)' + r'(\?(?P[^#]*))?' + r'(#(?P.*))?') + + +_HEX_CHAR_MAP = {(a + b).encode('ascii'): + chr(int(a + b, 16)).encode('charmap') + for a in string.hexdigits for b in string.hexdigits} +_ASCII_RE = re.compile('([\x00-\x7f]+)') + + +# This port list painstakingly curated by hand searching through +# https://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml +# and +# https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml +SCHEME_PORT_MAP = {'acap': 674, 'afp': 548, 'dict': 2628, 'dns': 53, + 'file': None, 'ftp': 21, 'git': 9418, 'gopher': 70, + 'http': 80, 'https': 443, 'imap': 143, 'ipp': 631, + 'ipps': 631, 'irc': 194, 'ircs': 6697, 'ldap': 389, + 'ldaps': 636, 'mms': 1755, 'msrp': 2855, 'msrps': None, + 'mtqp': 1038, 'nfs': 111, 'nntp': 119, 'nntps': 563, + 'pop': 110, 'prospero': 1525, 'redis': 6379, 'rsync': 873, + 'rtsp': 554, 'rtsps': 322, 'rtspu': 5005, 'sftp': 22, + 'smb': 445, 'snmp': 161, 'ssh': 22, 'steam': None, + 'svn': 3690, 'telnet': 23, 'ventrilo': 3784, 'vnc': 5900, + 'wais': 210, 'ws': 80, 'wss': 443, 'xmpp': None} + +# This list of schemes that don't use authorities is also from the link above. +NO_NETLOC_SCHEMES = {'urn', 'about', 'bitcoin', 'blob', 'data', 'geo', + 'magnet', 'mailto', 'news', 'pkcs11', + 'sip', 'sips', 'tel'} +# As of Mar 11, 2017, there were 44 netloc schemes, and 13 non-netloc + +# RFC 3986 section 2.2, Reserved Characters +_GEN_DELIMS = frozenset(':/?#[]@') +_SUB_DELIMS = frozenset("!$&'()*+,;=") +_ALL_DELIMS = _GEN_DELIMS | _SUB_DELIMS + +_USERINFO_SAFE = _UNRESERVED_CHARS | _SUB_DELIMS +_USERINFO_DELIMS = _ALL_DELIMS - _USERINFO_SAFE +_PATH_SAFE = _UNRESERVED_CHARS | _SUB_DELIMS | set(':@') +_PATH_DELIMS = _ALL_DELIMS - _PATH_SAFE +_FRAGMENT_SAFE = _UNRESERVED_CHARS | _PATH_SAFE | set('/?') +_FRAGMENT_DELIMS = _ALL_DELIMS - _FRAGMENT_SAFE +_QUERY_SAFE = _UNRESERVED_CHARS | _FRAGMENT_SAFE - set('&=+') +_QUERY_DELIMS = _ALL_DELIMS - _QUERY_SAFE + + +class URLParseError(ValueError): + """Exception inheriting from :exc:`ValueError`, raised when failing to + parse a URL. Mostly raised on invalid ports and IPv6 addresses. + """ + pass + + +DEFAULT_ENCODING = 'utf8' + + +def to_unicode(obj): + try: + return str(obj) + except UnicodeDecodeError: + return str(obj, encoding=DEFAULT_ENCODING) + + +# regex from gruber via tornado +# doesn't support ipv6 +# doesn't support mailto (netloc-less schemes) +_FIND_ALL_URL_RE = re.compile(r"""\b((?:([\w-]+):(/{1,3})|www[.])(?:(?:(?:[^\s&()<>]|&|")*(?:[^!"#$%'()*+,.:;<=>?@\[\]^`{|}~\s]))|(?:\((?:[^\s&()]|&|")*\)))+)""") + + +def find_all_links(text, with_text=False, default_scheme='https', schemes=()): + """This function uses heuristics to searches plain text for strings + that look like URLs, returning a :class:`list` of :class:`URL` + objects. It supports limiting the accepted schemes, and returning + interleaved text as well. + + >>> find_all_links('Visit https://boltons.rtfd.org!') + [URL(u'https://boltons.rtfd.org')] + >>> find_all_links('Visit https://boltons.rtfd.org!', with_text=True) + [u'Visit ', URL(u'https://boltons.rtfd.org'), u'!'] + + Args: + text (str): The text to search. + + with_text (bool): Whether or not to interleave plaintext blocks + with the returned URL objects. Having all tokens can be + useful for transforming the text, e.g., replacing links with + HTML equivalents. Defaults to ``False``. + + default_scheme (str): Many URLs are written without the scheme + component. This function can match a reasonable subset of + those, provided *default_scheme* is set to a string. Set to + ``False`` to disable matching scheme-less URLs. Defaults to + ``'https'``. + + schemes (list): A list of strings that a URL's scheme must + match in order to be included in the results. Defaults to + empty, which matches all schemes. + + .. note:: Currently this function does not support finding IPv6 + addresses or URLs with netloc-less schemes, like mailto. + + """ + text = to_unicode(text) + prev_end, start, end = 0, None, None + ret = [] + _add = ret.append + + def _add_text(t): + if ret and isinstance(ret[-1], str): + ret[-1] += t + else: + _add(t) + + for match in _FIND_ALL_URL_RE.finditer(text): + start, end = match.start(1), match.end(1) + if prev_end < start and with_text: + _add(text[prev_end:start]) + prev_end = end + try: + cur_url_text = match.group(0) + cur_url = URL(cur_url_text) + if not cur_url.scheme: + if default_scheme: + cur_url = URL(default_scheme + '://' + cur_url_text) + else: + _add_text(text[start:end]) + continue + if schemes and cur_url.scheme not in schemes: + _add_text(text[start:end]) + else: + _add(cur_url) + except URLParseError: + # currently this should only be hit with broken port + # strings. the regex above doesn't support ipv6 addresses + if with_text: + _add_text(text[start:end]) + + if with_text: + tail = text[prev_end:] + if tail: + _add_text(tail) + + return ret + + +def _make_quote_map(safe_chars): + ret = {} + # v is included in the dict for py3 mostly, because bytestrings + # are iterables of ints, of course! + for i, v in zip(range(256), range(256)): + c = chr(v) + if c in safe_chars: + ret[c] = ret[v] = c + else: + ret[c] = ret[v] = f'%{i:02X}' + return ret + + +_USERINFO_PART_QUOTE_MAP = _make_quote_map(_USERINFO_SAFE) +_PATH_PART_QUOTE_MAP = _make_quote_map(_PATH_SAFE) +_QUERY_PART_QUOTE_MAP = _make_quote_map(_QUERY_SAFE) +_FRAGMENT_QUOTE_MAP = _make_quote_map(_FRAGMENT_SAFE) + + +def quote_path_part(text, full_quote=True): + """ + Percent-encode a single segment of a URL path. + """ + if full_quote: + bytestr = normalize('NFC', to_unicode(text)).encode('utf8') + return ''.join([_PATH_PART_QUOTE_MAP[b] for b in bytestr]) + return ''.join([_PATH_PART_QUOTE_MAP[t] if t in _PATH_DELIMS else t + for t in text]) + + +def quote_query_part(text, full_quote=True): + """ + Percent-encode a single query string key or value. + """ + if full_quote: + bytestr = normalize('NFC', to_unicode(text)).encode('utf8') + return ''.join([_QUERY_PART_QUOTE_MAP[b] for b in bytestr]) + return ''.join([_QUERY_PART_QUOTE_MAP[t] if t in _QUERY_DELIMS else t + for t in text]) + + +def quote_fragment_part(text, full_quote=True): + """Quote the fragment part of the URL. Fragments don't have + subdelimiters, so the whole URL fragment can be passed. + """ + if full_quote: + bytestr = normalize('NFC', to_unicode(text)).encode('utf8') + return ''.join([_FRAGMENT_QUOTE_MAP[b] for b in bytestr]) + return ''.join([_FRAGMENT_QUOTE_MAP[t] if t in _FRAGMENT_DELIMS else t + for t in text]) + + +def quote_userinfo_part(text, full_quote=True): + """Quote special characters in either the username or password + section of the URL. Note that userinfo in URLs is considered + deprecated in many circles (especially browsers), and support for + percent-encoded userinfo can be spotty. + """ + if full_quote: + bytestr = normalize('NFC', to_unicode(text)).encode('utf8') + return ''.join([_USERINFO_PART_QUOTE_MAP[b] for b in bytestr]) + return ''.join([_USERINFO_PART_QUOTE_MAP[t] if t in _USERINFO_DELIMS + else t for t in text]) + + +def unquote(string, encoding='utf-8', errors='replace'): + """Percent-decode a string, by replacing %xx escapes with their + single-character equivalent. The optional *encoding* and *errors* + parameters specify how to decode percent-encoded sequences into + Unicode characters, as accepted by the :meth:`bytes.decode()` method. By + default, percent-encoded sequences are decoded with UTF-8, and + invalid sequences are replaced by a placeholder character. + + >>> unquote(u'abc%20def') + u'abc def' + """ + if '%' not in string: + string.split + return string + if encoding is None: + encoding = 'utf-8' + if errors is None: + errors = 'replace' + bits = _ASCII_RE.split(string) + res = [bits[0]] + append = res.append + for i in range(1, len(bits), 2): + append(unquote_to_bytes(bits[i]).decode(encoding, errors)) + append(bits[i + 1]) + return ''.join(res) + + +def unquote_to_bytes(string): + """unquote_to_bytes('abc%20def') -> b'abc def'.""" + # Note: strings are encoded as UTF-8. This is only an issue if it contains + # unescaped non-ASCII characters, which URIs should not. + if not string: + # Is it a string-like object? + string.split + return b'' + if isinstance(string, str): + string = string.encode('utf-8') + bits = string.split(b'%') + if len(bits) == 1: + return string + # import pdb;pdb.set_trace() + res = [bits[0]] + append = res.append + + for item in bits[1:]: + try: + append(_HEX_CHAR_MAP[item[:2]]) + append(item[2:]) + except KeyError: + append(b'%') + append(item) + return b''.join(res) + + +def register_scheme(text, uses_netloc=None, default_port=None): + """Registers new scheme information, resulting in correct port and + slash behavior from the URL object. There are dozens of standard + schemes preregistered, so this function is mostly meant for + proprietary internal customizations or stopgaps on missing + standards information. If a scheme seems to be missing, please + `file an issue`_! + + Args: + text (str): Text representing the scheme. + (the 'http' in 'http://hatnote.com') + uses_netloc (bool): Does the scheme support specifying a + network host? For instance, "http" does, "mailto" does not. + default_port (int): The default port, if any, for netloc-using + schemes. + + .. _file an issue: https://github.com/mahmoud/boltons/issues + """ + text = text.lower() + if default_port is not None: + try: + default_port = int(default_port) + except ValueError: + raise ValueError('default_port expected integer or None, not %r' + % (default_port,)) + + if uses_netloc is True: + SCHEME_PORT_MAP[text] = default_port + elif uses_netloc is False: + if default_port is not None: + raise ValueError('unexpected default port while specifying' + ' non-netloc scheme: %r' % default_port) + NO_NETLOC_SCHEMES.add(text) + elif uses_netloc is not None: + raise ValueError('uses_netloc expected True, False, or None') + + return + + +def resolve_path_parts(path_parts): + """Normalize the URL path by resolving segments of '.' and '..', + resulting in a dot-free path. See RFC 3986 section 5.2.4, Remove + Dot Segments. + """ + # TODO: what to do with multiple slashes + ret = [] + + for part in path_parts: + if part == '.': + pass + elif part == '..': + if ret and (len(ret) > 1 or ret[0]): # prevent unrooting + ret.pop() + else: + ret.append(part) + + if list(path_parts[-1:]) in (['.'], ['..']): + ret.append('') + + return ret + + +class cachedproperty: + """The ``cachedproperty`` is used similar to :class:`property`, except + that the wrapped method is only called once. This is commonly used + to implement lazy attributes. + + After the property has been accessed, the value is stored on the + instance itself, using the same name as the cachedproperty. This + allows the cache to be cleared with :func:`delattr`, or through + manipulating the object's ``__dict__``. + """ + def __init__(self, func): + self.__doc__ = getattr(func, '__doc__') + self.func = func + + def __get__(self, obj, objtype=None): + if obj is None: + return self + value = obj.__dict__[self.func.__name__] = self.func(obj) + return value + + def __repr__(self): + cn = self.__class__.__name__ + return f'<{cn} func={self.func}>' + + +class URL: + r"""The URL is one of the most ubiquitous data structures in the + virtual and physical landscape. From blogs to billboards, URLs are + so common, that it's easy to overlook their complexity and + power. + + There are 8 parts of a URL, each with its own semantics and + special characters: + + * :attr:`~URL.scheme` + * :attr:`~URL.username` + * :attr:`~URL.password` + * :attr:`~URL.host` + * :attr:`~URL.port` + * :attr:`~URL.path` + * :attr:`~URL.query_params` (query string parameters) + * :attr:`~URL.fragment` + + Each is exposed as an attribute on the URL object. RFC 3986 offers + this brief structural summary of the main URL components:: + + foo://user:pass@example.com:8042/over/there?name=ferret#nose + \_/ \_______/ \_________/ \__/\_________/ \_________/ \__/ + | | | | | | | + scheme userinfo host port path query fragment + + And here's how that example can be manipulated with the URL type: + + >>> url = URL('foo://example.com:8042/over/there?name=ferret#nose') + >>> print(url.host) + example.com + >>> print(url.get_authority()) + example.com:8042 + >>> print(url.qp['name']) # qp is a synonym for query_params + ferret + + URL's approach to encoding is that inputs are decoded as much as + possible, and data remains in this decoded state until re-encoded + using the :meth:`~URL.to_text()` method. In this way, it's similar + to Python's current approach of encouraging immediate decoding of + bytes to text. + + Note that URL instances are mutable objects. If an immutable + representation of the URL is desired, the string from + :meth:`~URL.to_text()` may be used. For an immutable, but + almost-as-featureful, URL object, check out the `hyperlink + package`_. + + .. _hyperlink package: https://github.com/mahmoud/hyperlink + + """ + + # public attributes (for comparison, see __eq__): + _cmp_attrs = ('scheme', 'uses_netloc', 'username', 'password', + 'family', 'host', 'port', 'path', 'query_params', 'fragment') + + def __init__(self, url=''): + # TODO: encoding param. The encoding that underlies the + # percent-encoding is always utf8 for IRIs, but can be Latin-1 + # for other usage schemes. + ud = DEFAULT_PARSED_URL + if url: + if isinstance(url, URL): + url = url.to_text() # better way to copy URLs? + elif isinstance(url, bytes): + try: + url = url.decode(DEFAULT_ENCODING) + except UnicodeDecodeError as ude: + raise URLParseError('expected text or %s-encoded bytes.' + ' try decoding the url bytes and' + ' passing the result. (got: %s)' + % (DEFAULT_ENCODING, ude)) + ud = parse_url(url) + + _e = '' + self.scheme = ud['scheme'] or _e + self._netloc_sep = ud['_netloc_sep'] or _e + self.username = (unquote(ud['username']) + if '%' in (ud['username'] or _e) else ud['username'] or _e) + self.password = (unquote(ud['password']) + if '%' in (ud['password'] or _e) else ud['password'] or _e) + self.family = ud['family'] + + if not ud['host']: + self.host = _e + else: + try: + self.host = ud['host'].encode("ascii") + except UnicodeEncodeError: + self.host = ud['host'] # already non-ascii text + else: + self.host = self.host.decode("idna") + + self.port = ud['port'] + self.path_parts = tuple([unquote(p) if '%' in p else p for p + in (ud['path'] or _e).split('/')]) + self._query = ud['query'] or _e + self.fragment = (unquote(ud['fragment']) + if '%' in (ud['fragment'] or _e) else ud['fragment'] or _e) + # TODO: possibly use None as marker for empty vs missing + return + + @classmethod + def from_parts(cls, scheme=None, host=None, path_parts=(), query_params=(), + fragment='', port=None, username=None, password=None): + """Build a new URL from parts. Note that the respective arguments are + not in the order they would appear in a URL: + + Args: + scheme (str): The scheme of a URL, e.g., 'http' + host (str): The host string, e.g., 'hatnote.com' + path_parts (tuple): The individual text segments of the + path, e.g., ('post', '123') + query_params (dict): An OMD, dict, or list of (key, value) + pairs representing the keys and values of the URL's query + parameters. + fragment (str): The fragment of the URL, e.g., 'anchor1' + port (int): The integer port of URL, automatic defaults are + available for registered schemes. + username (str): The username for the userinfo part of the URL. + password (str): The password for the userinfo part of the URL. + + Note that this method does relatively little + validation. :meth:`URL.to_text()` should be used to check if + any errors are produced while composing the final textual URL. + """ + ret = cls() + + ret.scheme = scheme + ret.host = host + ret.path_parts = tuple(path_parts) or ('',) + ret.query_params.update(query_params) + ret.fragment = fragment + ret.port = port + ret.username = username + ret.password = password + + return ret + + @cachedproperty + def query_params(self): + """The parsed form of the query string of the URL, represented as a + :class:`~dictutils.OrderedMultiDict`. Also available as the + handy alias ``qp``. + + >>> url = URL('http://boltons.readthedocs.io/?utm_source=doctest&python=great') + >>> url.qp.keys() + [u'utm_source', u'python'] + """ + return QueryParamDict.from_text(self._query) + + qp = query_params + + @property + def path(self): + "The URL's path, in text form." + return '/'.join([quote_path_part(p, full_quote=False) + for p in self.path_parts]) + + @path.setter + def path(self, path_text): + self.path_parts = tuple([unquote(p) if '%' in p else p + for p in to_unicode(path_text).split('/')]) + return + + @property + def uses_netloc(self): + """Whether or not a URL uses :code:`:` or :code:`://` to separate the + scheme from the rest of the URL depends on the scheme's own + standard definition. There is no way to infer this behavior + from other parts of the URL. A scheme either supports network + locations or it does not. + + The URL type's approach to this is to check for explicitly + registered schemes, with common schemes like HTTP + preregistered. This is the same approach taken by + :mod:`urlparse`. + + URL adds two additional heuristics if the scheme as a whole is + not registered. First, it attempts to check the subpart of the + scheme after the last ``+`` character. This adds intuitive + behavior for schemes like ``git+ssh``. Second, if a URL with + an unrecognized scheme is loaded, it will maintain the + separator it sees. + + >>> print(URL('fakescheme://test.com').to_text()) + fakescheme://test.com + >>> print(URL('mockscheme:hello:world').to_text()) + mockscheme:hello:world + + """ + default = self._netloc_sep + if self.scheme in SCHEME_PORT_MAP: + return True + if self.scheme in NO_NETLOC_SCHEMES: + return False + if self.scheme.split('+')[-1] in SCHEME_PORT_MAP: + return True + return default + + @property + def default_port(self): + """Return the default port for the currently-set scheme. Returns + ``None`` if the scheme is unrecognized. See + :func:`register_scheme` above. If :attr:`~URL.port` matches + this value, no port is emitted in the output of + :meth:`~URL.to_text()`. + + Applies the same '+' heuristic detailed in :meth:`URL.uses_netloc`. + """ + try: + return SCHEME_PORT_MAP[self.scheme] + except KeyError: + return SCHEME_PORT_MAP.get(self.scheme.split('+')[-1]) + + def normalize(self, with_case=True): + """Resolve any "." and ".." references in the path, as well as + normalize scheme and host casing. To turn off case + normalization, pass ``with_case=False``. + + More information can be found in `Section 6.2.2 of RFC 3986`_. + + .. _Section 6.2.2 of RFC 3986: https://tools.ietf.org/html/rfc3986#section-6.2.2 + """ + self.path_parts = resolve_path_parts(self.path_parts) + + if with_case: + self.scheme = self.scheme.lower() + self.host = self.host.lower() + return + + def navigate(self, dest): + """Factory method that returns a _new_ :class:`URL` based on a given + destination, *dest*. Useful for navigating those relative + links with ease. + + The newly created :class:`URL` is normalized before being returned. + + >>> url = URL('http://boltons.readthedocs.io') + >>> url.navigate('en/latest/') + URL(u'http://boltons.readthedocs.io/en/latest/') + + Args: + dest (str): A string or URL object representing the destination + + More information can be found in `Section 5 of RFC 3986`_. + + .. _Section 5 of RFC 3986: https://tools.ietf.org/html/rfc3986#section-5 + """ + orig_dest = None + if not isinstance(dest, URL): + dest, orig_dest = URL(dest), dest + if dest.scheme and dest.host: + # absolute URLs replace everything, but don't make an + # extra copy if we don't have to + return URL(dest) if orig_dest is None else dest + query_params = dest.query_params + + if dest.path: + if dest.path.startswith('/'): # absolute path + new_path_parts = list(dest.path_parts) + else: # relative path + new_path_parts = list(self.path_parts[:-1]) \ + + list(dest.path_parts) + else: + new_path_parts = list(self.path_parts) + if not query_params: + query_params = self.query_params + + ret = self.from_parts(scheme=dest.scheme or self.scheme, + host=dest.host or self.host, + port=dest.port or self.port, + path_parts=new_path_parts, + query_params=query_params, + fragment=dest.fragment, + username=dest.username or self.username, + password=dest.password or self.password) + ret.normalize() + return ret + + def get_authority(self, full_quote=False, with_userinfo=False): + """Used by URL schemes that have a network location, + :meth:`~URL.get_authority` combines :attr:`username`, + :attr:`password`, :attr:`host`, and :attr:`port` into one + string, the *authority*, that is used for + connecting to a network-accessible resource. + + Used internally by :meth:`~URL.to_text()` and can be useful + for labeling connections. + + >>> url = URL('ftp://user@ftp.debian.org:2121/debian/README') + >>> print(url.get_authority()) + ftp.debian.org:2121 + >>> print(url.get_authority(with_userinfo=True)) + user@ftp.debian.org:2121 + + Args: + full_quote (bool): Whether or not to apply IDNA encoding. + Defaults to ``False``. + with_userinfo (bool): Whether or not to include username + and password, technically part of the + authority. Defaults to ``False``. + + """ + parts = [] + _add = parts.append + if self.username and with_userinfo: + _add(quote_userinfo_part(self.username)) + if self.password: + _add(':') + _add(quote_userinfo_part(self.password)) + _add('@') + if self.host: + if self.family == socket.AF_INET6: + _add('[') + _add(self.host) + _add(']') + elif full_quote: + _add(self.host.encode('idna').decode('ascii')) + else: + _add(self.host) + # TODO: 0 port? + if self.port and self.port != self.default_port: + _add(':') + _add(str(self.port)) + return ''.join(parts) + + def to_text(self, full_quote=False): + """Render a string representing the current state of the URL + object. + + >>> url = URL('http://listen.hatnote.com') + >>> url.fragment = 'en' + >>> print(url.to_text()) + http://listen.hatnote.com#en + + By setting the *full_quote* flag, the URL can either be fully + quoted or minimally quoted. The most common characteristic of + an encoded-URL is the presence of percent-encoded text (e.g., + %60). Unquoted URLs are more readable and suitable + for display, whereas fully-quoted URLs are more conservative + and generally necessary for sending over the network. + """ + scheme = self.scheme + path = '/'.join([quote_path_part(p, full_quote=full_quote) + for p in self.path_parts]) + authority = self.get_authority(full_quote=full_quote, + with_userinfo=True) + query_string = self.query_params.to_text(full_quote=full_quote) + fragment = quote_fragment_part(self.fragment, full_quote=full_quote) + + parts = [] + _add = parts.append + if scheme: + _add(scheme) + _add(':') + if authority: + _add('//') + _add(authority) + elif (scheme and path[:2] != '//' and self.uses_netloc): + _add('//') + if path: + if scheme and authority and path[:1] != '/': + _add('/') + # TODO: i think this is here because relative paths + # with absolute authorities = undefined + _add(path) + if query_string: + _add('?') + _add(query_string) + if fragment: + _add('#') + _add(fragment) + return ''.join(parts) + + def __repr__(self): + cn = self.__class__.__name__ + return f'{cn}({self.to_text()!r})' + + def __str__(self): + return self.to_text() + + def __unicode__(self): + return self.to_text() + + def __eq__(self, other): + for attr in self._cmp_attrs: + if not getattr(self, attr) == getattr(other, attr, None): + return False + return True + + def __ne__(self, other): + return not self == other + + +try: + from socket import inet_pton +except ImportError: + # from https://gist.github.com/nnemkin/4966028 + import ctypes + + class _sockaddr(ctypes.Structure): + _fields_ = [("sa_family", ctypes.c_short), + ("__pad1", ctypes.c_ushort), + ("ipv4_addr", ctypes.c_byte * 4), + ("ipv6_addr", ctypes.c_byte * 16), + ("__pad2", ctypes.c_ulong)] + + WSAStringToAddressA = ctypes.windll.ws2_32.WSAStringToAddressA + WSAAddressToStringA = ctypes.windll.ws2_32.WSAAddressToStringA + + def inet_pton(address_family, ip_string): + addr = _sockaddr() + ip_string = ip_string.encode('ascii') + addr.sa_family = address_family + addr_size = ctypes.c_int(ctypes.sizeof(addr)) + + if WSAStringToAddressA(ip_string, address_family, None, ctypes.byref(addr), ctypes.byref(addr_size)) != 0: + raise OSError(ctypes.FormatError()) + + if address_family == socket.AF_INET: + return ctypes.string_at(addr.ipv4_addr, 4) + if address_family == socket.AF_INET6: + return ctypes.string_at(addr.ipv6_addr, 16) + raise OSError('unknown address family') + + +def parse_host(host): + """\ + Low-level function used to parse the host portion of a URL. + + Returns a tuple of (family, host) where *family* is a + :mod:`socket` module constant or ``None``, and host is a string. + + >>> parse_host('googlewebsite.com') == (None, 'googlewebsite.com') + True + >>> parse_host('[::1]') == (socket.AF_INET6, '::1') + True + >>> parse_host('192.168.1.1') == (socket.AF_INET, '192.168.1.1') + True + + Odd doctest formatting above due to py3's switch from int to enums + for :mod:`socket` constants. + + """ + if not host: + return None, '' + if ':' in host and '[' == host[0] and ']' == host[-1]: + host = host[1:-1] + try: + inet_pton(socket.AF_INET6, host) + except OSError as se: + raise URLParseError(f'invalid IPv6 host: {host!r} ({se!r})') + except UnicodeEncodeError: + pass # TODO: this can't be a real host right? + else: + family = socket.AF_INET6 + return family, host + try: + inet_pton(socket.AF_INET, host) + except (OSError, UnicodeEncodeError): + family = None # not an IP + else: + family = socket.AF_INET + return family, host + + +def parse_url(url_text): + """\ + Used to parse the text for a single URL into a dictionary, used + internally by the :class:`URL` type. + + Note that "URL" has a very narrow, standards-based + definition. While :func:`parse_url` may raise + :class:`URLParseError` under a very limited number of conditions, + such as non-integer port, a surprising number of strings are + technically valid URLs. For instance, the text ``"url"`` is a + valid URL, because it is a relative path. + + In short, do not expect this function to validate form inputs or + other more colloquial usages of URLs. + + >>> res = parse_url('http://127.0.0.1:3000/?a=1') + >>> sorted(res.keys()) # res is a basic dictionary + ['_netloc_sep', 'authority', 'family', 'fragment', 'host', 'password', 'path', 'port', 'query', 'scheme', 'username'] + """ + url_text = str(url_text) + # raise TypeError('parse_url expected text, not %r' % url_str) + um = _URL_RE.match(url_text) + try: + gs = um.groupdict() + except AttributeError: + raise URLParseError('could not parse url: %r' % url_text) + + au_text = gs['authority'] + user, pw, hostinfo = None, None, au_text + + if au_text: + userinfo, sep, hostinfo = au_text.rpartition('@') + if sep: + # TODO: empty userinfo error? + user, _, pw = userinfo.partition(':') + + host, port = None, None + if hostinfo: + host, sep, port_str = hostinfo.partition(':') + if sep: + if host and host[0] == '[' and ']' in port_str: + host_right, _, port_str = port_str.partition(']') + host = host + ':' + host_right + ']' + if port_str and port_str[0] == ':': + port_str = port_str[1:] + + try: + port = int(port_str) + except ValueError: + if port_str: # empty ports ok according to RFC 3986 6.2.3 + raise URLParseError('expected integer for port, not %r' + % port_str) + port = None + + family, host = parse_host(host) + + gs['username'] = user + gs['password'] = pw + gs['family'] = family + gs['host'] = host + gs['port'] = port + return gs + + +DEFAULT_PARSED_URL = parse_url('') + + +def parse_qsl(qs, keep_blank_values=True, encoding=DEFAULT_ENCODING): + """ + Converts a query string into a list of (key, value) pairs. + """ + pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')] + ret = [] + for pair in pairs: + if not pair: + continue + key, _, value = pair.partition('=') + if not value: + if keep_blank_values: + value = None + else: + continue + key = unquote(key.replace('+', ' ')) + if value: + value = unquote(value.replace('+', ' ')) + ret.append((key, value)) + return ret + + +""" +# What follows is the OrderedMultiDict from dictutils.py, circa +# 20161021, used for the QueryParamDict, toward the bottom. +""" + +from collections.abc import KeysView, ValuesView, ItemsView +from itertools import zip_longest + +try: + from .typeutils import make_sentinel + _MISSING = make_sentinel(var_name='_MISSING') +except ImportError: + _MISSING = object() + + +PREV, NEXT, KEY, VALUE, SPREV, SNEXT = range(6) + + +class OrderedMultiDict(dict): + """A MultiDict is a dictionary that can have multiple values per key + and the OrderedMultiDict (OMD) is a MultiDict that retains + original insertion order. Common use cases include: + + * handling query strings parsed from URLs + * inverting a dictionary to create a reverse index (values to keys) + * stacking data from multiple dictionaries in a non-destructive way + + The OrderedMultiDict constructor is identical to the built-in + :class:`dict`, and overall the API constitutes an intuitive + superset of the built-in type: + + >>> omd = OrderedMultiDict() + >>> omd['a'] = 1 + >>> omd['b'] = 2 + >>> omd.add('a', 3) + >>> omd.get('a') + 3 + >>> omd.getlist('a') + [1, 3] + + Some non-:class:`dict`-like behaviors also make an appearance, + such as support for :func:`reversed`: + + >>> list(reversed(omd)) + ['b', 'a'] + + Note that unlike some other MultiDicts, this OMD gives precedence + to the most recent value added. ``omd['a']`` refers to ``3``, not + ``1``. + + >>> omd + OrderedMultiDict([('a', 1), ('b', 2), ('a', 3)]) + >>> omd.poplast('a') + 3 + >>> omd + OrderedMultiDict([('a', 1), ('b', 2)]) + >>> omd.pop('a') + 1 + >>> omd + OrderedMultiDict([('b', 2)]) + + If you want a safe-to-modify or flat dictionary, use + :meth:`OrderedMultiDict.todict()`. + + >>> from pprint import pprint as pp # preserve printed ordering + >>> omd = OrderedMultiDict([('a', 1), ('b', 2), ('a', 3)]) + >>> pp(omd.todict()) + {'a': 3, 'b': 2} + >>> pp(omd.todict(multi=True)) + {'a': [1, 3], 'b': [2]} + + With ``multi=False``, items appear with the keys in to original + insertion order, alongside the most-recently inserted value for + that key. + + >>> OrderedMultiDict([('a', 1), ('b', 2), ('a', 3)]).items(multi=False) + [('a', 3), ('b', 2)] + + .. warning:: + + ``dict(omd)`` changed behavior `in Python 3.7 + `_ due to changes made to + support the transition from :class:`collections.OrderedDict` to + the built-in dictionary being ordered. Before 3.7, the result + would be a new dictionary, with values that were lists, similar + to ``omd.todict(multi=True)`` (but only shallow-copy; the lists + were direct references to OMD internal structures). From 3.7 + onward, the values became singular, like + ``omd.todict(multi=False)``. For reliable cross-version + behavior, just use :meth:`~OrderedMultiDict.todict()`. + + """ + def __new__(cls, *a, **kw): + ret = super().__new__(cls) + ret._clear_ll() + return ret + + def __init__(self, *args, **kwargs): + if len(args) > 1: + raise TypeError('%s expected at most 1 argument, got %s' + % (self.__class__.__name__, len(args))) + super().__init__() + + if args: + self.update_extend(args[0]) + if kwargs: + self.update(kwargs) + + def __getstate__(self): + return list(self.iteritems(multi=True)) + + def __setstate__(self, state): + self.clear() + self.update_extend(state) + + def _clear_ll(self): + try: + _map = self._map + except AttributeError: + _map = self._map = {} + self.root = [] + _map.clear() + self.root[:] = [self.root, self.root, None] + + def _insert(self, k, v): + root = self.root + cells = self._map.setdefault(k, []) + last = root[PREV] + cell = [last, root, k, v] + last[NEXT] = root[PREV] = cell + cells.append(cell) + + def add(self, k, v): + """Add a single value *v* under a key *k*. Existing values under *k* + are preserved. + """ + values = super().setdefault(k, []) + self._insert(k, v) + values.append(v) + + def addlist(self, k, v): + """Add an iterable of values underneath a specific key, preserving + any values already under that key. + + >>> omd = OrderedMultiDict([('a', -1)]) + >>> omd.addlist('a', range(3)) + >>> omd + OrderedMultiDict([('a', -1), ('a', 0), ('a', 1), ('a', 2)]) + + Called ``addlist`` for consistency with :meth:`getlist`, but + tuples and other sequences and iterables work. + """ + if not v: + return + self_insert = self._insert + values = super().setdefault(k, []) + for subv in v: + self_insert(k, subv) + values.extend(v) + + def get(self, k, default=None): + """Return the value for key *k* if present in the dictionary, else + *default*. If *default* is not given, ``None`` is returned. + This method never raises a :exc:`KeyError`. + + To get all values under a key, use :meth:`OrderedMultiDict.getlist`. + """ + return super().get(k, [default])[-1] + + def getlist(self, k, default=_MISSING): + """Get all values for key *k* as a list, if *k* is in the + dictionary, else *default*. The list returned is a copy and + can be safely mutated. If *default* is not given, an empty + :class:`list` is returned. + """ + try: + return super().__getitem__(k)[:] + except KeyError: + if default is _MISSING: + return [] + return default + + def clear(self): + "Empty the dictionary." + super().clear() + self._clear_ll() + + def setdefault(self, k, default=_MISSING): + """If key *k* is in the dictionary, return its value. If not, insert + *k* with a value of *default* and return *default*. *default* + defaults to ``None``. See :meth:`dict.setdefault` for more + information. + """ + if not super().__contains__(k): + self[k] = None if default is _MISSING else default + return self[k] + + def copy(self): + "Return a shallow copy of the dictionary." + return self.__class__(self.iteritems(multi=True)) + + @classmethod + def fromkeys(cls, keys, default=None): + """Create a dictionary from a list of keys, with all the values + set to *default*, or ``None`` if *default* is not set. + """ + return cls([(k, default) for k in keys]) + + def update(self, E, **F): + """Add items from a dictionary or iterable (and/or keyword arguments), + overwriting values under an existing key. See + :meth:`dict.update` for more details. + """ + # E and F are throwback names to the dict() __doc__ + if E is self: + return + self_add = self.add + if isinstance(E, OrderedMultiDict): + for k in E: + if k in self: + del self[k] + for k, v in E.iteritems(multi=True): + self_add(k, v) + elif callable(getattr(E, 'keys', None)): + for k in E.keys(): + self[k] = E[k] + else: + seen = set() + seen_add = seen.add + for k, v in E: + if k not in seen and k in self: + del self[k] + seen_add(k) + self_add(k, v) + for k in F: + self[k] = F[k] + return + + def update_extend(self, E, **F): + """Add items from a dictionary, iterable, and/or keyword + arguments without overwriting existing items present in the + dictionary. Like :meth:`update`, but adds to existing keys + instead of overwriting them. + """ + if E is self: + iterator = iter(E.items()) + elif isinstance(E, OrderedMultiDict): + iterator = E.iteritems(multi=True) + elif hasattr(E, 'keys'): + iterator = ((k, E[k]) for k in E.keys()) + else: + iterator = E + + self_add = self.add + for k, v in iterator: + self_add(k, v) + + def __setitem__(self, k, v): + if super().__contains__(k): + self._remove_all(k) + self._insert(k, v) + super().__setitem__(k, [v]) + + def __getitem__(self, k): + return super().__getitem__(k)[-1] + + def __delitem__(self, k): + super().__delitem__(k) + self._remove_all(k) + + def __eq__(self, other): + if self is other: + return True + try: + if len(other) != len(self): + return False + except TypeError: + return False + if isinstance(other, OrderedMultiDict): + selfi = self.iteritems(multi=True) + otheri = other.iteritems(multi=True) + zipped_items = zip_longest(selfi, otheri, fillvalue=(None, None)) + for (selfk, selfv), (otherk, otherv) in zipped_items: + if selfk != otherk or selfv != otherv: + return False + if not(next(selfi, _MISSING) is _MISSING + and next(otheri, _MISSING) is _MISSING): + # leftovers (TODO: watch for StopIteration?) + return False + return True + elif hasattr(other, 'keys'): + for selfk in self: + try: + other[selfk] == self[selfk] + except KeyError: + return False + return True + return False + + def __ne__(self, other): + return not (self == other) + + def __ior__(self, other): + self.update(other) + return self + + def pop(self, k, default=_MISSING): + """Remove all values under key *k*, returning the most-recently + inserted value. Raises :exc:`KeyError` if the key is not + present and no *default* is provided. + """ + try: + return self.popall(k)[-1] + except KeyError: + if default is _MISSING: + raise KeyError(k) + return default + + def popall(self, k, default=_MISSING): + """Remove all values under key *k*, returning them in the form of + a list. Raises :exc:`KeyError` if the key is not present and no + *default* is provided. + """ + super_self = super() + if super_self.__contains__(k): + self._remove_all(k) + if default is _MISSING: + return super_self.pop(k) + return super_self.pop(k, default) + + def poplast(self, k=_MISSING, default=_MISSING): + """Remove and return the most-recently inserted value under the key + *k*, or the most-recently inserted key if *k* is not + provided. If no values remain under *k*, it will be removed + from the OMD. Raises :exc:`KeyError` if *k* is not present in + the dictionary, or the dictionary is empty. + """ + if k is _MISSING: + if self: + k = self.root[PREV][KEY] + else: + if default is _MISSING: + raise KeyError('empty %r' % type(self)) + return default + try: + self._remove(k) + except KeyError: + if default is _MISSING: + raise KeyError(k) + return default + values = super().__getitem__(k) + v = values.pop() + if not values: + super().__delitem__(k) + return v + + def _remove(self, k): + values = self._map[k] + cell = values.pop() + cell[PREV][NEXT], cell[NEXT][PREV] = cell[NEXT], cell[PREV] + if not values: + del self._map[k] + + def _remove_all(self, k): + values = self._map[k] + while values: + cell = values.pop() + cell[PREV][NEXT], cell[NEXT][PREV] = cell[NEXT], cell[PREV] + del self._map[k] + + def iteritems(self, multi=False): + """Iterate over the OMD's items in insertion order. By default, + yields only the most-recently inserted value for each key. Set + *multi* to ``True`` to get all inserted items. + """ + root = self.root + curr = root[NEXT] + if multi: + while curr is not root: + yield curr[KEY], curr[VALUE] + curr = curr[NEXT] + else: + for key in self.iterkeys(): + yield key, self[key] + + def iterkeys(self, multi=False): + """Iterate over the OMD's keys in insertion order. By default, yields + each key once, according to the most recent insertion. Set + *multi* to ``True`` to get all keys, including duplicates, in + insertion order. + """ + root = self.root + curr = root[NEXT] + if multi: + while curr is not root: + yield curr[KEY] + curr = curr[NEXT] + else: + yielded = set() + yielded_add = yielded.add + while curr is not root: + k = curr[KEY] + if k not in yielded: + yielded_add(k) + yield k + curr = curr[NEXT] + + def itervalues(self, multi=False): + """Iterate over the OMD's values in insertion order. By default, + yields the most-recently inserted value per unique key. Set + *multi* to ``True`` to get all values according to insertion + order. + """ + for k, v in self.iteritems(multi=multi): + yield v + + def todict(self, multi=False): + """Gets a basic :class:`dict` of the items in this dictionary. Keys + are the same as the OMD, values are the most recently inserted + values for each key. + + Setting the *multi* arg to ``True`` is yields the same + result as calling :class:`dict` on the OMD, except that all the + value lists are copies that can be safely mutated. + """ + if multi: + return {k: self.getlist(k) for k in self} + return {k: self[k] for k in self} + + def sorted(self, key=None, reverse=False): + """Similar to the built-in :func:`sorted`, except this method returns + a new :class:`OrderedMultiDict` sorted by the provided key + function, optionally reversed. + + Args: + key (callable): A callable to determine the sort key of + each element. The callable should expect an **item** + (key-value pair tuple). + reverse (bool): Set to ``True`` to reverse the ordering. + + >>> omd = OrderedMultiDict(zip(range(3), range(3))) + >>> omd.sorted(reverse=True) + OrderedMultiDict([(2, 2), (1, 1), (0, 0)]) + + Note that the key function receives an **item** (key-value + tuple), so the recommended signature looks like: + + >>> omd = OrderedMultiDict(zip('hello', 'world')) + >>> omd.sorted(key=lambda i: i[1]) # i[0] is the key, i[1] is the val + OrderedMultiDict([('o', 'd'), ('l', 'l'), ('e', 'o'), ('l', 'r'), ('h', 'w')]) + """ + cls = self.__class__ + return cls(sorted(self.iteritems(multi=True), key=key, reverse=reverse)) + + def sortedvalues(self, key=None, reverse=False): + """Returns a copy of the :class:`OrderedMultiDict` with the same keys + in the same order as the original OMD, but the values within + each keyspace have been sorted according to *key* and + *reverse*. + + Args: + key (callable): A single-argument callable to determine + the sort key of each element. The callable should expect + an **item** (key-value pair tuple). + reverse (bool): Set to ``True`` to reverse the ordering. + + >>> omd = OrderedMultiDict() + >>> omd.addlist('even', [6, 2]) + >>> omd.addlist('odd', [1, 5]) + >>> omd.add('even', 4) + >>> omd.add('odd', 3) + >>> somd = omd.sortedvalues() + >>> somd.getlist('even') + [2, 4, 6] + >>> somd.keys(multi=True) == omd.keys(multi=True) + True + >>> omd == somd + False + >>> somd + OrderedMultiDict([('even', 2), ('even', 4), ('odd', 1), ('odd', 3), ('even', 6), ('odd', 5)]) + + As demonstrated above, contents and key order are + retained. Only value order changes. + """ + try: + superself_iteritems = super().iteritems() + except AttributeError: + superself_iteritems = super().items() + # (not reverse) because they pop off in reverse order for reinsertion + sorted_val_map = {k: sorted(v, key=key, reverse=(not reverse)) + for k, v in superself_iteritems} + ret = self.__class__() + for k in self.iterkeys(multi=True): + ret.add(k, sorted_val_map[k].pop()) + return ret + + def inverted(self): + """Returns a new :class:`OrderedMultiDict` with values and keys + swapped, like creating dictionary transposition or reverse + index. Insertion order is retained and all keys and values + are represented in the output. + + >>> omd = OMD([(0, 2), (1, 2)]) + >>> omd.inverted().getlist(2) + [0, 1] + + Inverting twice yields a copy of the original: + + >>> omd.inverted().inverted() + OrderedMultiDict([(0, 2), (1, 2)]) + """ + return self.__class__((v, k) for k, v in self.iteritems(multi=True)) + + def counts(self): + """Returns a mapping from key to number of values inserted under that + key. Like :py:class:`collections.Counter`, but returns a new + :class:`OrderedMultiDict`. + """ + # Returns an OMD because Counter/OrderedDict may not be + # available, and neither Counter nor dict maintain order. + super_getitem = super().__getitem__ + return self.__class__((k, len(super_getitem(k))) for k in self) + + def keys(self, multi=False): + """Returns a list containing the output of :meth:`iterkeys`. See + that method's docs for more details. + """ + return list(self.iterkeys(multi=multi)) + + def values(self, multi=False): + """Returns a list containing the output of :meth:`itervalues`. See + that method's docs for more details. + """ + return list(self.itervalues(multi=multi)) + + def items(self, multi=False): + """Returns a list containing the output of :meth:`iteritems`. See + that method's docs for more details. + """ + return list(self.iteritems(multi=multi)) + + def __iter__(self): + return self.iterkeys() + + def __reversed__(self): + root = self.root + curr = root[PREV] + lengths = {} + lengths_sd = lengths.setdefault + get_values = super().__getitem__ + while curr is not root: + k = curr[KEY] + vals = get_values(k) + if lengths_sd(k, 1) == len(vals): + yield k + lengths[k] += 1 + curr = curr[PREV] + + def __repr__(self): + cn = self.__class__.__name__ + kvs = ', '.join([repr((k, v)) for k, v in self.iteritems(multi=True)]) + return f'{cn}([{kvs}])' + + def viewkeys(self): + "OMD.viewkeys() -> a set-like object providing a view on OMD's keys" + return KeysView(self) + + def viewvalues(self): + "OMD.viewvalues() -> an object providing a view on OMD's values" + return ValuesView(self) + + def viewitems(self): + "OMD.viewitems() -> a set-like object providing a view on OMD's items" + return ItemsView(self) + + + +try: + # try to import the built-in one anyways + from .dictutils import OrderedMultiDict +except ImportError: + pass + +OMD = OrderedMultiDict + + +class QueryParamDict(OrderedMultiDict): + """A subclass of :class:`~dictutils.OrderedMultiDict` specialized for + representing query string values. Everything is fully unquoted on + load and all parsed keys and values are strings by default. + + As the name suggests, multiple values are supported and insertion + order is preserved. + + >>> qp = QueryParamDict.from_text(u'key=val1&key=val2&utm_source=rtd') + >>> qp.getlist('key') + [u'val1', u'val2'] + >>> qp['key'] + u'val2' + >>> qp.add('key', 'val3') + >>> qp.to_text() + 'key=val1&key=val2&utm_source=rtd&key=val3' + + See :class:`~dictutils.OrderedMultiDict` for more API features. + """ + + @classmethod + def from_text(cls, query_string): + """ + Parse *query_string* and return a new :class:`QueryParamDict`. + """ + pairs = parse_qsl(query_string, keep_blank_values=True) + return cls(pairs) + + def to_text(self, full_quote=False): + """ + Render and return a query string. + + Args: + full_quote (bool): Whether or not to percent-quote special + characters or leave them decoded for readability. + """ + ret_list = [] + for k, v in self.iteritems(multi=True): + key = quote_query_part(to_unicode(k), full_quote=full_quote) + if v is None: + ret_list.append(key) + else: + val = quote_query_part(to_unicode(v), full_quote=full_quote) + ret_list.append('='.join((key, val))) + return '&'.join(ret_list) + +# end urlutils.py diff --git a/data/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/INSTALLER b/data/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..f79e4cb9aaf0b2d9e8ba78861e2071317b2384b3 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/INSTALLER @@ -0,0 +1 @@ +conda \ No newline at end of file diff --git a/data/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/METADATA b/data/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..8d32edcc9f0aa2057cc7844f7bb36b2c8c2e41d7 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/METADATA @@ -0,0 +1,764 @@ +Metadata-Version: 2.4 +Name: charset-normalizer +Version: 3.4.4 +Summary: The Real First Universal Charset Detector. Open, modern and actively maintained alternative to Chardet. +Author-email: "Ahmed R. TAHRI" +Maintainer-email: "Ahmed R. TAHRI" +License: MIT +Project-URL: Changelog, https://github.com/jawah/charset_normalizer/blob/master/CHANGELOG.md +Project-URL: Documentation, https://charset-normalizer.readthedocs.io/ +Project-URL: Code, https://github.com/jawah/charset_normalizer +Project-URL: Issue tracker, https://github.com/jawah/charset_normalizer/issues +Keywords: encoding,charset,charset-detector,detector,normalization,unicode,chardet,detect +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Text Processing :: Linguistic +Classifier: Topic :: Utilities +Classifier: Typing :: Typed +Requires-Python: >=3.7 +Description-Content-Type: text/markdown +License-File: LICENSE +Provides-Extra: unicode-backport +Dynamic: license-file + +

Charset Detection, for Everyone 👋

+ +

+ The Real First Universal Charset Detector
+ + + + + Download Count Total + + + + +

+

+ Featured Packages
+ + Static Badge + + + Static Badge + +

+

+ In other language (unofficial port - by the community)
+ + Static Badge + +

+ +> A library that helps you read text from an unknown charset encoding.
Motivated by `chardet`, +> I'm trying to resolve the issue by taking a new approach. +> All IANA character set names for which the Python core library provides codecs are supported. + +

+ >>>>> 👉 Try Me Online Now, Then Adopt Me 👈 <<<<< +

+ +This project offers you an alternative to **Universal Charset Encoding Detector**, also known as **Chardet**. + +| Feature | [Chardet](https://github.com/chardet/chardet) | Charset Normalizer | [cChardet](https://github.com/PyYoshi/cChardet) | +|--------------------------------------------------|:---------------------------------------------:|:--------------------------------------------------------------------------------------------------:|:-----------------------------------------------:| +| `Fast` | ❌ | ✅ | ✅ | +| `Universal**` | ❌ | ✅ | ❌ | +| `Reliable` **without** distinguishable standards | ❌ | ✅ | ✅ | +| `Reliable` **with** distinguishable standards | ✅ | ✅ | ✅ | +| `License` | LGPL-2.1
_restrictive_ | MIT | MPL-1.1
_restrictive_ | +| `Native Python` | ✅ | ✅ | ❌ | +| `Detect spoken language` | ❌ | ✅ | N/A | +| `UnicodeDecodeError Safety` | ❌ | ✅ | ❌ | +| `Whl Size (min)` | 193.6 kB | 42 kB | ~200 kB | +| `Supported Encoding` | 33 | 🎉 [99](https://charset-normalizer.readthedocs.io/en/latest/user/support.html#supported-encodings) | 40 | + +

+Reading Normalized TextCat Reading Text +

+ +*\*\* : They are clearly using specific code for a specific encoding even if covering most of used one*
+ +## ⚡ Performance + +This package offer better performance than its counterpart Chardet. Here are some numbers. + +| Package | Accuracy | Mean per file (ms) | File per sec (est) | +|-----------------------------------------------|:--------:|:------------------:|:------------------:| +| [chardet](https://github.com/chardet/chardet) | 86 % | 63 ms | 16 file/sec | +| charset-normalizer | **98 %** | **10 ms** | 100 file/sec | + +| Package | 99th percentile | 95th percentile | 50th percentile | +|-----------------------------------------------|:---------------:|:---------------:|:---------------:| +| [chardet](https://github.com/chardet/chardet) | 265 ms | 71 ms | 7 ms | +| charset-normalizer | 100 ms | 50 ms | 5 ms | + +_updated as of december 2024 using CPython 3.12_ + +Chardet's performance on larger file (1MB+) are very poor. Expect huge difference on large payload. + +> Stats are generated using 400+ files using default parameters. More details on used files, see GHA workflows. +> And yes, these results might change at any time. The dataset can be updated to include more files. +> The actual delays heavily depends on your CPU capabilities. The factors should remain the same. +> Keep in mind that the stats are generous and that Chardet accuracy vs our is measured using Chardet initial capability +> (e.g. Supported Encoding) Challenge-them if you want. + +## ✨ Installation + +Using pip: + +```sh +pip install charset-normalizer -U +``` + +## 🚀 Basic Usage + +### CLI +This package comes with a CLI. + +``` +usage: normalizer [-h] [-v] [-a] [-n] [-m] [-r] [-f] [-t THRESHOLD] + file [file ...] + +The Real First Universal Charset Detector. Discover originating encoding used +on text file. Normalize text to unicode. + +positional arguments: + files File(s) to be analysed + +optional arguments: + -h, --help show this help message and exit + -v, --verbose Display complementary information about file if any. + Stdout will contain logs about the detection process. + -a, --with-alternative + Output complementary possibilities if any. Top-level + JSON WILL be a list. + -n, --normalize Permit to normalize input file. If not set, program + does not write anything. + -m, --minimal Only output the charset detected to STDOUT. Disabling + JSON output. + -r, --replace Replace file when trying to normalize it instead of + creating a new one. + -f, --force Replace file without asking if you are sure, use this + flag with caution. + -t THRESHOLD, --threshold THRESHOLD + Define a custom maximum amount of chaos allowed in + decoded content. 0. <= chaos <= 1. + --version Show version information and exit. +``` + +```bash +normalizer ./data/sample.1.fr.srt +``` + +or + +```bash +python -m charset_normalizer ./data/sample.1.fr.srt +``` + +🎉 Since version 1.4.0 the CLI produce easily usable stdout result in JSON format. + +```json +{ + "path": "/home/default/projects/charset_normalizer/data/sample.1.fr.srt", + "encoding": "cp1252", + "encoding_aliases": [ + "1252", + "windows_1252" + ], + "alternative_encodings": [ + "cp1254", + "cp1256", + "cp1258", + "iso8859_14", + "iso8859_15", + "iso8859_16", + "iso8859_3", + "iso8859_9", + "latin_1", + "mbcs" + ], + "language": "French", + "alphabets": [ + "Basic Latin", + "Latin-1 Supplement" + ], + "has_sig_or_bom": false, + "chaos": 0.149, + "coherence": 97.152, + "unicode_path": null, + "is_preferred": true +} +``` + +### Python +*Just print out normalized text* +```python +from charset_normalizer import from_path + +results = from_path('./my_subtitle.srt') + +print(str(results.best())) +``` + +*Upgrade your code without effort* +```python +from charset_normalizer import detect +``` + +The above code will behave the same as **chardet**. We ensure that we offer the best (reasonable) BC result possible. + +See the docs for advanced usage : [readthedocs.io](https://charset-normalizer.readthedocs.io/en/latest/) + +## 😇 Why + +When I started using Chardet, I noticed that it was not suited to my expectations, and I wanted to propose a +reliable alternative using a completely different method. Also! I never back down on a good challenge! + +I **don't care** about the **originating charset** encoding, because **two different tables** can +produce **two identical rendered string.** +What I want is to get readable text, the best I can. + +In a way, **I'm brute forcing text decoding.** How cool is that ? 😎 + +Don't confuse package **ftfy** with charset-normalizer or chardet. ftfy goal is to repair Unicode string whereas charset-normalizer to convert raw file in unknown encoding to unicode. + +## 🍰 How + + - Discard all charset encoding table that could not fit the binary content. + - Measure noise, or the mess once opened (by chunks) with a corresponding charset encoding. + - Extract matches with the lowest mess detected. + - Additionally, we measure coherence / probe for a language. + +**Wait a minute**, what is noise/mess and coherence according to **YOU ?** + +*Noise :* I opened hundred of text files, **written by humans**, with the wrong encoding table. **I observed**, then +**I established** some ground rules about **what is obvious** when **it seems like** a mess (aka. defining noise in rendered text). + I know that my interpretation of what is noise is probably incomplete, feel free to contribute in order to + improve or rewrite it. + +*Coherence :* For each language there is on earth, we have computed ranked letter appearance occurrences (the best we can). So I thought +that intel is worth something here. So I use those records against decoded text to check if I can detect intelligent design. + +## ⚡ Known limitations + + - Language detection is unreliable when text contains two or more languages sharing identical letters. (eg. HTML (english tags) + Turkish content (Sharing Latin characters)) + - Every charset detector heavily depends on sufficient content. In common cases, do not bother run detection on very tiny content. + +## ⚠️ About Python EOLs + +**If you are running:** + +- Python >=2.7,<3.5: Unsupported +- Python 3.5: charset-normalizer < 2.1 +- Python 3.6: charset-normalizer < 3.1 +- Python 3.7: charset-normalizer < 4.0 + +Upgrade your Python interpreter as soon as possible. + +## 👤 Contributing + +Contributions, issues and feature requests are very much welcome.
+Feel free to check [issues page](https://github.com/ousret/charset_normalizer/issues) if you want to contribute. + +## 📝 License + +Copyright © [Ahmed TAHRI @Ousret](https://github.com/Ousret).
+This project is [MIT](https://github.com/Ousret/charset_normalizer/blob/master/LICENSE) licensed. + +Characters frequencies used in this project © 2012 [Denny Vrandečić](http://simia.net/letters/) + +## 💼 For Enterprise + +Professional support for charset-normalizer is available as part of the [Tidelift +Subscription][1]. Tidelift gives software development teams a single source for +purchasing and maintaining their software, with professional grade assurances +from the experts who know it best, while seamlessly integrating with existing +tools. + +[1]: https://tidelift.com/subscription/pkg/pypi-charset-normalizer?utm_source=pypi-charset-normalizer&utm_medium=readme + +[![OpenSSF Best Practices](https://www.bestpractices.dev/projects/7297/badge)](https://www.bestpractices.dev/projects/7297) + +# Changelog +All notable changes to charset-normalizer will be documented in this file. This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). + +## [3.4.4](https://github.com/Ousret/charset_normalizer/compare/3.4.2...3.4.4) (2025-10-13) + +### Changed +- Bound `setuptools` to a specific constraint `setuptools>=68,<=81`. +- Raised upper bound of mypyc for the optional pre-built extension to v1.18.2 + +### Removed +- `setuptools-scm` as a build dependency. + +### Misc +- Enforced hashes in `dev-requirements.txt` and created `ci-requirements.txt` for security purposes. +- Additional pre-built wheels for riscv64, s390x, and armv7l architectures. +- Restore ` multiple.intoto.jsonl` in GitHub releases in addition to individual attestation file per wheel. + +## [3.4.3](https://github.com/Ousret/charset_normalizer/compare/3.4.2...3.4.3) (2025-08-09) + +### Changed +- mypy(c) is no longer a required dependency at build time if `CHARSET_NORMALIZER_USE_MYPYC` isn't set to `1`. (#595) (#583) +- automatically lower confidence on small bytes samples that are not Unicode in `detect` output legacy function. (#391) + +### Added +- Custom build backend to overcome inability to mark mypy as an optional dependency in the build phase. +- Support for Python 3.14 + +### Fixed +- sdist archive contained useless directories. +- automatically fallback on valid UTF-16 or UTF-32 even if the md says it's noisy. (#633) + +### Misc +- SBOM are automatically published to the relevant GitHub release to comply with regulatory changes. + Each published wheel comes with its SBOM. We choose CycloneDX as the format. +- Prebuilt optimized wheel are no longer distributed by default for CPython 3.7 due to a change in cibuildwheel. + +## [3.4.2](https://github.com/Ousret/charset_normalizer/compare/3.4.1...3.4.2) (2025-05-02) + +### Fixed +- Addressed the DeprecationWarning in our CLI regarding `argparse.FileType` by backporting the target class into the package. (#591) +- Improved the overall reliability of the detector with CJK Ideographs. (#605) (#587) + +### Changed +- Optional mypyc compilation upgraded to version 1.15 for Python >= 3.8 + +## [3.4.1](https://github.com/Ousret/charset_normalizer/compare/3.4.0...3.4.1) (2024-12-24) + +### Changed +- Project metadata are now stored using `pyproject.toml` instead of `setup.cfg` using setuptools as the build backend. +- Enforce annotation delayed loading for a simpler and consistent types in the project. +- Optional mypyc compilation upgraded to version 1.14 for Python >= 3.8 + +### Added +- pre-commit configuration. +- noxfile. + +### Removed +- `build-requirements.txt` as per using `pyproject.toml` native build configuration. +- `bin/integration.py` and `bin/serve.py` in favor of downstream integration test (see noxfile). +- `setup.cfg` in favor of `pyproject.toml` metadata configuration. +- Unused `utils.range_scan` function. + +### Fixed +- Converting content to Unicode bytes may insert `utf_8` instead of preferred `utf-8`. (#572) +- Deprecation warning "'count' is passed as positional argument" when converting to Unicode bytes on Python 3.13+ + +## [3.4.0](https://github.com/Ousret/charset_normalizer/compare/3.3.2...3.4.0) (2024-10-08) + +### Added +- Argument `--no-preemptive` in the CLI to prevent the detector to search for hints. +- Support for Python 3.13 (#512) + +### Fixed +- Relax the TypeError exception thrown when trying to compare a CharsetMatch with anything else than a CharsetMatch. +- Improved the general reliability of the detector based on user feedbacks. (#520) (#509) (#498) (#407) (#537) +- Declared charset in content (preemptive detection) not changed when converting to utf-8 bytes. (#381) + +## [3.3.2](https://github.com/Ousret/charset_normalizer/compare/3.3.1...3.3.2) (2023-10-31) + +### Fixed +- Unintentional memory usage regression when using large payload that match several encoding (#376) +- Regression on some detection case showcased in the documentation (#371) + +### Added +- Noise (md) probe that identify malformed arabic representation due to the presence of letters in isolated form (credit to my wife) + +## [3.3.1](https://github.com/Ousret/charset_normalizer/compare/3.3.0...3.3.1) (2023-10-22) + +### Changed +- Optional mypyc compilation upgraded to version 1.6.1 for Python >= 3.8 +- Improved the general detection reliability based on reports from the community + +## [3.3.0](https://github.com/Ousret/charset_normalizer/compare/3.2.0...3.3.0) (2023-09-30) + +### Added +- Allow to execute the CLI (e.g. normalizer) through `python -m charset_normalizer.cli` or `python -m charset_normalizer` +- Support for 9 forgotten encoding that are supported by Python but unlisted in `encoding.aliases` as they have no alias (#323) + +### Removed +- (internal) Redundant utils.is_ascii function and unused function is_private_use_only +- (internal) charset_normalizer.assets is moved inside charset_normalizer.constant + +### Changed +- (internal) Unicode code blocks in constants are updated using the latest v15.0.0 definition to improve detection +- Optional mypyc compilation upgraded to version 1.5.1 for Python >= 3.8 + +### Fixed +- Unable to properly sort CharsetMatch when both chaos/noise and coherence were close due to an unreachable condition in \_\_lt\_\_ (#350) + +## [3.2.0](https://github.com/Ousret/charset_normalizer/compare/3.1.0...3.2.0) (2023-06-07) + +### Changed +- Typehint for function `from_path` no longer enforce `PathLike` as its first argument +- Minor improvement over the global detection reliability + +### Added +- Introduce function `is_binary` that relies on main capabilities, and optimized to detect binaries +- Propagate `enable_fallback` argument throughout `from_bytes`, `from_path`, and `from_fp` that allow a deeper control over the detection (default True) +- Explicit support for Python 3.12 + +### Fixed +- Edge case detection failure where a file would contain 'very-long' camel cased word (Issue #289) + +## [3.1.0](https://github.com/Ousret/charset_normalizer/compare/3.0.1...3.1.0) (2023-03-06) + +### Added +- Argument `should_rename_legacy` for legacy function `detect` and disregard any new arguments without errors (PR #262) + +### Removed +- Support for Python 3.6 (PR #260) + +### Changed +- Optional speedup provided by mypy/c 1.0.1 + +## [3.0.1](https://github.com/Ousret/charset_normalizer/compare/3.0.0...3.0.1) (2022-11-18) + +### Fixed +- Multi-bytes cutter/chunk generator did not always cut correctly (PR #233) + +### Changed +- Speedup provided by mypy/c 0.990 on Python >= 3.7 + +## [3.0.0](https://github.com/Ousret/charset_normalizer/compare/2.1.1...3.0.0) (2022-10-20) + +### Added +- Extend the capability of explain=True when cp_isolation contains at most two entries (min one), will log in details of the Mess-detector results +- Support for alternative language frequency set in charset_normalizer.assets.FREQUENCIES +- Add parameter `language_threshold` in `from_bytes`, `from_path` and `from_fp` to adjust the minimum expected coherence ratio +- `normalizer --version` now specify if current version provide extra speedup (meaning mypyc compilation whl) + +### Changed +- Build with static metadata using 'build' frontend +- Make the language detection stricter +- Optional: Module `md.py` can be compiled using Mypyc to provide an extra speedup up to 4x faster than v2.1 + +### Fixed +- CLI with opt --normalize fail when using full path for files +- TooManyAccentuatedPlugin induce false positive on the mess detection when too few alpha character have been fed to it +- Sphinx warnings when generating the documentation + +### Removed +- Coherence detector no longer return 'Simple English' instead return 'English' +- Coherence detector no longer return 'Classical Chinese' instead return 'Chinese' +- Breaking: Method `first()` and `best()` from CharsetMatch +- UTF-7 will no longer appear as "detected" without a recognized SIG/mark (is unreliable/conflict with ASCII) +- Breaking: Class aliases CharsetDetector, CharsetDoctor, CharsetNormalizerMatch and CharsetNormalizerMatches +- Breaking: Top-level function `normalize` +- Breaking: Properties `chaos_secondary_pass`, `coherence_non_latin` and `w_counter` from CharsetMatch +- Support for the backport `unicodedata2` + +## [3.0.0rc1](https://github.com/Ousret/charset_normalizer/compare/3.0.0b2...3.0.0rc1) (2022-10-18) + +### Added +- Extend the capability of explain=True when cp_isolation contains at most two entries (min one), will log in details of the Mess-detector results +- Support for alternative language frequency set in charset_normalizer.assets.FREQUENCIES +- Add parameter `language_threshold` in `from_bytes`, `from_path` and `from_fp` to adjust the minimum expected coherence ratio + +### Changed +- Build with static metadata using 'build' frontend +- Make the language detection stricter + +### Fixed +- CLI with opt --normalize fail when using full path for files +- TooManyAccentuatedPlugin induce false positive on the mess detection when too few alpha character have been fed to it + +### Removed +- Coherence detector no longer return 'Simple English' instead return 'English' +- Coherence detector no longer return 'Classical Chinese' instead return 'Chinese' + +## [3.0.0b2](https://github.com/Ousret/charset_normalizer/compare/3.0.0b1...3.0.0b2) (2022-08-21) + +### Added +- `normalizer --version` now specify if current version provide extra speedup (meaning mypyc compilation whl) + +### Removed +- Breaking: Method `first()` and `best()` from CharsetMatch +- UTF-7 will no longer appear as "detected" without a recognized SIG/mark (is unreliable/conflict with ASCII) + +### Fixed +- Sphinx warnings when generating the documentation + +## [3.0.0b1](https://github.com/Ousret/charset_normalizer/compare/2.1.0...3.0.0b1) (2022-08-15) + +### Changed +- Optional: Module `md.py` can be compiled using Mypyc to provide an extra speedup up to 4x faster than v2.1 + +### Removed +- Breaking: Class aliases CharsetDetector, CharsetDoctor, CharsetNormalizerMatch and CharsetNormalizerMatches +- Breaking: Top-level function `normalize` +- Breaking: Properties `chaos_secondary_pass`, `coherence_non_latin` and `w_counter` from CharsetMatch +- Support for the backport `unicodedata2` + +## [2.1.1](https://github.com/Ousret/charset_normalizer/compare/2.1.0...2.1.1) (2022-08-19) + +### Deprecated +- Function `normalize` scheduled for removal in 3.0 + +### Changed +- Removed useless call to decode in fn is_unprintable (#206) + +### Fixed +- Third-party library (i18n xgettext) crashing not recognizing utf_8 (PEP 263) with underscore from [@aleksandernovikov](https://github.com/aleksandernovikov) (#204) + +## [2.1.0](https://github.com/Ousret/charset_normalizer/compare/2.0.12...2.1.0) (2022-06-19) + +### Added +- Output the Unicode table version when running the CLI with `--version` (PR #194) + +### Changed +- Re-use decoded buffer for single byte character sets from [@nijel](https://github.com/nijel) (PR #175) +- Fixing some performance bottlenecks from [@deedy5](https://github.com/deedy5) (PR #183) + +### Fixed +- Workaround potential bug in cpython with Zero Width No-Break Space located in Arabic Presentation Forms-B, Unicode 1.1 not acknowledged as space (PR #175) +- CLI default threshold aligned with the API threshold from [@oleksandr-kuzmenko](https://github.com/oleksandr-kuzmenko) (PR #181) + +### Removed +- Support for Python 3.5 (PR #192) + +### Deprecated +- Use of backport unicodedata from `unicodedata2` as Python is quickly catching up, scheduled for removal in 3.0 (PR #194) + +## [2.0.12](https://github.com/Ousret/charset_normalizer/compare/2.0.11...2.0.12) (2022-02-12) + +### Fixed +- ASCII miss-detection on rare cases (PR #170) + +## [2.0.11](https://github.com/Ousret/charset_normalizer/compare/2.0.10...2.0.11) (2022-01-30) + +### Added +- Explicit support for Python 3.11 (PR #164) + +### Changed +- The logging behavior have been completely reviewed, now using only TRACE and DEBUG levels (PR #163 #165) + +## [2.0.10](https://github.com/Ousret/charset_normalizer/compare/2.0.9...2.0.10) (2022-01-04) + +### Fixed +- Fallback match entries might lead to UnicodeDecodeError for large bytes sequence (PR #154) + +### Changed +- Skipping the language-detection (CD) on ASCII (PR #155) + +## [2.0.9](https://github.com/Ousret/charset_normalizer/compare/2.0.8...2.0.9) (2021-12-03) + +### Changed +- Moderating the logging impact (since 2.0.8) for specific environments (PR #147) + +### Fixed +- Wrong logging level applied when setting kwarg `explain` to True (PR #146) + +## [2.0.8](https://github.com/Ousret/charset_normalizer/compare/2.0.7...2.0.8) (2021-11-24) +### Changed +- Improvement over Vietnamese detection (PR #126) +- MD improvement on trailing data and long foreign (non-pure latin) data (PR #124) +- Efficiency improvements in cd/alphabet_languages from [@adbar](https://github.com/adbar) (PR #122) +- call sum() without an intermediary list following PEP 289 recommendations from [@adbar](https://github.com/adbar) (PR #129) +- Code style as refactored by Sourcery-AI (PR #131) +- Minor adjustment on the MD around european words (PR #133) +- Remove and replace SRTs from assets / tests (PR #139) +- Initialize the library logger with a `NullHandler` by default from [@nmaynes](https://github.com/nmaynes) (PR #135) +- Setting kwarg `explain` to True will add provisionally (bounded to function lifespan) a specific stream handler (PR #135) + +### Fixed +- Fix large (misleading) sequence giving UnicodeDecodeError (PR #137) +- Avoid using too insignificant chunk (PR #137) + +### Added +- Add and expose function `set_logging_handler` to configure a specific StreamHandler from [@nmaynes](https://github.com/nmaynes) (PR #135) +- Add `CHANGELOG.md` entries, format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) (PR #141) + +## [2.0.7](https://github.com/Ousret/charset_normalizer/compare/2.0.6...2.0.7) (2021-10-11) +### Added +- Add support for Kazakh (Cyrillic) language detection (PR #109) + +### Changed +- Further, improve inferring the language from a given single-byte code page (PR #112) +- Vainly trying to leverage PEP263 when PEP3120 is not supported (PR #116) +- Refactoring for potential performance improvements in loops from [@adbar](https://github.com/adbar) (PR #113) +- Various detection improvement (MD+CD) (PR #117) + +### Removed +- Remove redundant logging entry about detected language(s) (PR #115) + +### Fixed +- Fix a minor inconsistency between Python 3.5 and other versions regarding language detection (PR #117 #102) + +## [2.0.6](https://github.com/Ousret/charset_normalizer/compare/2.0.5...2.0.6) (2021-09-18) +### Fixed +- Unforeseen regression with the loss of the backward-compatibility with some older minor of Python 3.5.x (PR #100) +- Fix CLI crash when using --minimal output in certain cases (PR #103) + +### Changed +- Minor improvement to the detection efficiency (less than 1%) (PR #106 #101) + +## [2.0.5](https://github.com/Ousret/charset_normalizer/compare/2.0.4...2.0.5) (2021-09-14) +### Changed +- The project now comply with: flake8, mypy, isort and black to ensure a better overall quality (PR #81) +- The BC-support with v1.x was improved, the old staticmethods are restored (PR #82) +- The Unicode detection is slightly improved (PR #93) +- Add syntax sugar \_\_bool\_\_ for results CharsetMatches list-container (PR #91) + +### Removed +- The project no longer raise warning on tiny content given for detection, will be simply logged as warning instead (PR #92) + +### Fixed +- In some rare case, the chunks extractor could cut in the middle of a multi-byte character and could mislead the mess detection (PR #95) +- Some rare 'space' characters could trip up the UnprintablePlugin/Mess detection (PR #96) +- The MANIFEST.in was not exhaustive (PR #78) + +## [2.0.4](https://github.com/Ousret/charset_normalizer/compare/2.0.3...2.0.4) (2021-07-30) +### Fixed +- The CLI no longer raise an unexpected exception when no encoding has been found (PR #70) +- Fix accessing the 'alphabets' property when the payload contains surrogate characters (PR #68) +- The logger could mislead (explain=True) on detected languages and the impact of one MBCS match (PR #72) +- Submatch factoring could be wrong in rare edge cases (PR #72) +- Multiple files given to the CLI were ignored when publishing results to STDOUT. (After the first path) (PR #72) +- Fix line endings from CRLF to LF for certain project files (PR #67) + +### Changed +- Adjust the MD to lower the sensitivity, thus improving the global detection reliability (PR #69 #76) +- Allow fallback on specified encoding if any (PR #71) + +## [2.0.3](https://github.com/Ousret/charset_normalizer/compare/2.0.2...2.0.3) (2021-07-16) +### Changed +- Part of the detection mechanism has been improved to be less sensitive, resulting in more accurate detection results. Especially ASCII. (PR #63) +- According to the community wishes, the detection will fall back on ASCII or UTF-8 in a last-resort case. (PR #64) + +## [2.0.2](https://github.com/Ousret/charset_normalizer/compare/2.0.1...2.0.2) (2021-07-15) +### Fixed +- Empty/Too small JSON payload miss-detection fixed. Report from [@tseaver](https://github.com/tseaver) (PR #59) + +### Changed +- Don't inject unicodedata2 into sys.modules from [@akx](https://github.com/akx) (PR #57) + +## [2.0.1](https://github.com/Ousret/charset_normalizer/compare/2.0.0...2.0.1) (2021-07-13) +### Fixed +- Make it work where there isn't a filesystem available, dropping assets frequencies.json. Report from [@sethmlarson](https://github.com/sethmlarson). (PR #55) +- Using explain=False permanently disable the verbose output in the current runtime (PR #47) +- One log entry (language target preemptive) was not show in logs when using explain=True (PR #47) +- Fix undesired exception (ValueError) on getitem of instance CharsetMatches (PR #52) + +### Changed +- Public function normalize default args values were not aligned with from_bytes (PR #53) + +### Added +- You may now use charset aliases in cp_isolation and cp_exclusion arguments (PR #47) + +## [2.0.0](https://github.com/Ousret/charset_normalizer/compare/1.4.1...2.0.0) (2021-07-02) +### Changed +- 4x to 5 times faster than the previous 1.4.0 release. At least 2x faster than Chardet. +- Accent has been made on UTF-8 detection, should perform rather instantaneous. +- The backward compatibility with Chardet has been greatly improved. The legacy detect function returns an identical charset name whenever possible. +- The detection mechanism has been slightly improved, now Turkish content is detected correctly (most of the time) +- The program has been rewritten to ease the readability and maintainability. (+Using static typing)+ +- utf_7 detection has been reinstated. + +### Removed +- This package no longer require anything when used with Python 3.5 (Dropped cached_property) +- Removed support for these languages: Catalan, Esperanto, Kazakh, Baque, Volapük, Azeri, Galician, Nynorsk, Macedonian, and Serbocroatian. +- The exception hook on UnicodeDecodeError has been removed. + +### Deprecated +- Methods coherence_non_latin, w_counter, chaos_secondary_pass of the class CharsetMatch are now deprecated and scheduled for removal in v3.0 + +### Fixed +- The CLI output used the relative path of the file(s). Should be absolute. + +## [1.4.1](https://github.com/Ousret/charset_normalizer/compare/1.4.0...1.4.1) (2021-05-28) +### Fixed +- Logger configuration/usage no longer conflict with others (PR #44) + +## [1.4.0](https://github.com/Ousret/charset_normalizer/compare/1.3.9...1.4.0) (2021-05-21) +### Removed +- Using standard logging instead of using the package loguru. +- Dropping nose test framework in favor of the maintained pytest. +- Choose to not use dragonmapper package to help with gibberish Chinese/CJK text. +- Require cached_property only for Python 3.5 due to constraint. Dropping for every other interpreter version. +- Stop support for UTF-7 that does not contain a SIG. +- Dropping PrettyTable, replaced with pure JSON output in CLI. + +### Fixed +- BOM marker in a CharsetNormalizerMatch instance could be False in rare cases even if obviously present. Due to the sub-match factoring process. +- Not searching properly for the BOM when trying utf32/16 parent codec. + +### Changed +- Improving the package final size by compressing frequencies.json. +- Huge improvement over the larges payload. + +### Added +- CLI now produces JSON consumable output. +- Return ASCII if given sequences fit. Given reasonable confidence. + +## [1.3.9](https://github.com/Ousret/charset_normalizer/compare/1.3.8...1.3.9) (2021-05-13) + +### Fixed +- In some very rare cases, you may end up getting encode/decode errors due to a bad bytes payload (PR #40) + +## [1.3.8](https://github.com/Ousret/charset_normalizer/compare/1.3.7...1.3.8) (2021-05-12) + +### Fixed +- Empty given payload for detection may cause an exception if trying to access the `alphabets` property. (PR #39) + +## [1.3.7](https://github.com/Ousret/charset_normalizer/compare/1.3.6...1.3.7) (2021-05-12) + +### Fixed +- The legacy detect function should return UTF-8-SIG if sig is present in the payload. (PR #38) + +## [1.3.6](https://github.com/Ousret/charset_normalizer/compare/1.3.5...1.3.6) (2021-02-09) + +### Changed +- Amend the previous release to allow prettytable 2.0 (PR #35) + +## [1.3.5](https://github.com/Ousret/charset_normalizer/compare/1.3.4...1.3.5) (2021-02-08) + +### Fixed +- Fix error while using the package with a python pre-release interpreter (PR #33) + +### Changed +- Dependencies refactoring, constraints revised. + +### Added +- Add python 3.9 and 3.10 to the supported interpreters + +MIT License + +Copyright (c) 2025 TAHRI Ahmed R. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/data/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/RECORD b/data/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..25c3b759281a52b16eea9e818cea01e8df91f373 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/RECORD @@ -0,0 +1,35 @@ +../../../bin/normalizer,sha256=s5v8Ryd-_lpO2PkK5C9ZdpVwagkAdUiW5pCMn9OzTfc,489 +charset_normalizer-3.4.4.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +charset_normalizer-3.4.4.dist-info/METADATA,sha256=jVuUFBti8dav19YLvWissTihVdF2ozUY4KKMw7jdkBQ,37303 +charset_normalizer-3.4.4.dist-info/RECORD,, +charset_normalizer-3.4.4.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +charset_normalizer-3.4.4.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91 +charset_normalizer-3.4.4.dist-info/direct_url.json,sha256=6aqycCnV6a-o8iGsXH78ZoChM3iBG1zOfPuoOW7PAAY,108 +charset_normalizer-3.4.4.dist-info/entry_points.txt,sha256=ADSTKrkXZ3hhdOVFi6DcUEHQRS0xfxDIE_pEz4wLIXA,65 +charset_normalizer-3.4.4.dist-info/licenses/LICENSE,sha256=bQ1Bv-FwrGx9wkjJpj4lTQ-0WmDVCoJX0K-SxuJJuIc,1071 +charset_normalizer-3.4.4.dist-info/top_level.txt,sha256=7ASyzePr8_xuZWJsnqJjIBtyV8vhEo0wBCv1MPRRi3Q,19 +charset_normalizer/__init__.py,sha256=OKRxRv2Zhnqk00tqkN0c1BtJjm165fWXLydE52IKuHc,1590 +charset_normalizer/__main__.py,sha256=yzYxMR-IhKRHYwcSlavEv8oGdwxsR89mr2X09qXGdps,109 +charset_normalizer/__pycache__/__init__.cpython-313.pyc,, +charset_normalizer/__pycache__/__main__.cpython-313.pyc,, +charset_normalizer/__pycache__/api.cpython-313.pyc,, +charset_normalizer/__pycache__/cd.cpython-313.pyc,, +charset_normalizer/__pycache__/constant.cpython-313.pyc,, +charset_normalizer/__pycache__/legacy.cpython-313.pyc,, +charset_normalizer/__pycache__/md.cpython-313.pyc,, +charset_normalizer/__pycache__/models.cpython-313.pyc,, +charset_normalizer/__pycache__/utils.cpython-313.pyc,, +charset_normalizer/__pycache__/version.cpython-313.pyc,, +charset_normalizer/api.py,sha256=V07i8aVeCD8T2fSia3C-fn0i9t8qQguEBhsqszg32Ns,22668 +charset_normalizer/cd.py,sha256=WKTo1HDb-H9HfCDc3Bfwq5jzS25Ziy9SE2a74SgTq88,12522 +charset_normalizer/cli/__init__.py,sha256=D8I86lFk2-py45JvqxniTirSj_sFyE6sjaY_0-G1shc,136 +charset_normalizer/cli/__main__.py,sha256=dMaXG6IJXRvqq8z2tig7Qb83-BpWTln55ooiku5_uvg,12646 +charset_normalizer/cli/__pycache__/__init__.cpython-313.pyc,, +charset_normalizer/cli/__pycache__/__main__.cpython-313.pyc,, +charset_normalizer/constant.py,sha256=7UVY4ldYhmQMHUdgQ_sgZmzcQ0xxYxpBunqSZ-XJZ8U,42713 +charset_normalizer/legacy.py,sha256=sYBzSpzsRrg_wF4LP536pG64BItw7Tqtc3SMQAHvFLM,2731 +charset_normalizer/md.py,sha256=-_oN3h3_X99nkFfqamD3yu45DC_wfk5odH0Tr_CQiXs,20145 +charset_normalizer/models.py,sha256=lKXhOnIPtiakbK3i__J9wpOfzx3JDTKj7Dn3Rg0VaRI,12394 +charset_normalizer/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +charset_normalizer/utils.py,sha256=sTejPgrdlNsKNucZfJCxJ95lMTLA0ShHLLE3n5wpT9Q,12170 +charset_normalizer/version.py,sha256=nKE4qBNk5WA4LIJ_yIH_aSDfvtsyizkWMg-PUG-UZVk,115 diff --git a/data/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/REQUESTED b/data/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/WHEEL b/data/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..e7fa31b6f3f78deb1022c1f7927f07d4d16da822 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/data/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/direct_url.json b/data/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..ce8bd019755866d8cf7937f7b31ff445d2709dcc --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/direct_url.json @@ -0,0 +1 @@ +{"dir_info": {}, "url": "file:///home/task_176174481524083/conda-bld/charset-normalizer_1761744828711/work"} \ No newline at end of file diff --git a/data/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/entry_points.txt b/data/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..65619e73ec06c20c2a70c9507b872ad624d1a85c --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/entry_points.txt @@ -0,0 +1,2 @@ +[console_scripts] +normalizer = charset_normalizer.cli:cli_detect diff --git a/data/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/top_level.txt b/data/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..66958f0a069d7aea7939bed40b9197608e93b243 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/top_level.txt @@ -0,0 +1 @@ +charset_normalizer diff --git a/data/miniconda3/lib/python3.13/site-packages/click-8.2.1.dist-info/INSTALLER b/data/miniconda3/lib/python3.13/site-packages/click-8.2.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..f79e4cb9aaf0b2d9e8ba78861e2071317b2384b3 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/click-8.2.1.dist-info/INSTALLER @@ -0,0 +1 @@ +conda \ No newline at end of file diff --git a/data/miniconda3/lib/python3.13/site-packages/click-8.2.1.dist-info/METADATA b/data/miniconda3/lib/python3.13/site-packages/click-8.2.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..e6c05af4a78cabdf5689f3f6f7fd57304d8a0eb1 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/click-8.2.1.dist-info/METADATA @@ -0,0 +1,82 @@ +Metadata-Version: 2.4 +Name: click +Version: 8.2.1 +Summary: Composable command line interface toolkit +Maintainer-email: Pallets +Requires-Python: >=3.10 +Description-Content-Type: text/markdown +License-Expression: BSD-3-Clause +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Typing :: Typed +License-File: LICENSE.txt +Requires-Dist: colorama; platform_system == 'Windows' +Project-URL: Changes, https://click.palletsprojects.com/page/changes/ +Project-URL: Chat, https://discord.gg/pallets +Project-URL: Documentation, https://click.palletsprojects.com/ +Project-URL: Donate, https://palletsprojects.com/donate +Project-URL: Source, https://github.com/pallets/click/ + +# $ click_ + +Click is a Python package for creating beautiful command line interfaces +in a composable way with as little code as necessary. It's the "Command +Line Interface Creation Kit". It's highly configurable but comes with +sensible defaults out of the box. + +It aims to make the process of writing command line tools quick and fun +while also preventing any frustration caused by the inability to +implement an intended CLI API. + +Click in three points: + +- Arbitrary nesting of commands +- Automatic help page generation +- Supports lazy loading of subcommands at runtime + + +## A Simple Example + +```python +import click + +@click.command() +@click.option("--count", default=1, help="Number of greetings.") +@click.option("--name", prompt="Your name", help="The person to greet.") +def hello(count, name): + """Simple program that greets NAME for a total of COUNT times.""" + for _ in range(count): + click.echo(f"Hello, {name}!") + +if __name__ == '__main__': + hello() +``` + +``` +$ python hello.py --count=3 +Your name: Click +Hello, Click! +Hello, Click! +Hello, Click! +``` + + +## Donate + +The Pallets organization develops and supports Click and other popular +packages. In order to grow the community of contributors and users, and +allow the maintainers to devote more time to the projects, [please +donate today][]. + +[please donate today]: https://palletsprojects.com/donate + +## Contributing + +See our [detailed contributing documentation][contrib] for many ways to +contribute, including reporting issues, requesting features, asking or answering +questions, and making PRs. + +[contrib]: https://palletsprojects.com/contributing/ + diff --git a/data/miniconda3/lib/python3.13/site-packages/click-8.2.1.dist-info/RECORD b/data/miniconda3/lib/python3.13/site-packages/click-8.2.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..aa1899264e21c21eddb04967ef249c4b41a48f95 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/click-8.2.1.dist-info/RECORD @@ -0,0 +1,40 @@ +click-8.2.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +click-8.2.1.dist-info/METADATA,sha256=dI1MbhHTLoKD2tNCCGnx9rK2gok23HDNylFeLKdLSik,2471 +click-8.2.1.dist-info/RECORD,, +click-8.2.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +click-8.2.1.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82 +click-8.2.1.dist-info/direct_url.json,sha256=H8jZyz21jDDoaYECf18QQi8UqnE6A1SJVtMbWCMrPfo,95 +click-8.2.1.dist-info/licenses/LICENSE.txt,sha256=morRBqOU6FO_4h9C9OctWSgZoigF2ZG18ydQKSkrZY0,1475 +click/__init__.py,sha256=6YyS1aeyknZ0LYweWozNZy0A9nZ_11wmYIhv3cbQrYo,4473 +click/__pycache__/__init__.cpython-313.pyc,, +click/__pycache__/_compat.cpython-313.pyc,, +click/__pycache__/_termui_impl.cpython-313.pyc,, +click/__pycache__/_textwrap.cpython-313.pyc,, +click/__pycache__/_winconsole.cpython-313.pyc,, +click/__pycache__/core.cpython-313.pyc,, +click/__pycache__/decorators.cpython-313.pyc,, +click/__pycache__/exceptions.cpython-313.pyc,, +click/__pycache__/formatting.cpython-313.pyc,, +click/__pycache__/globals.cpython-313.pyc,, +click/__pycache__/parser.cpython-313.pyc,, +click/__pycache__/shell_completion.cpython-313.pyc,, +click/__pycache__/termui.cpython-313.pyc,, +click/__pycache__/testing.cpython-313.pyc,, +click/__pycache__/types.cpython-313.pyc,, +click/__pycache__/utils.cpython-313.pyc,, +click/_compat.py,sha256=v3xBZkFbvA1BXPRkFfBJc6-pIwPI7345m-kQEnpVAs4,18693 +click/_termui_impl.py,sha256=ASXhLi9IQIc0Js9KQSS-3-SLZcPet3VqysBf9WgbbpI,26712 +click/_textwrap.py,sha256=BOae0RQ6vg3FkNgSJyOoGzG1meGMxJ_ukWVZKx_v-0o,1400 +click/_winconsole.py,sha256=_vxUuUaxwBhoR0vUWCNuHY8VUefiMdCIyU2SXPqoF-A,8465 +click/core.py,sha256=gUhpNS9cFBGdEXXdisGVG-eRvGf49RTyFagxulqwdFw,117343 +click/decorators.py,sha256=5P7abhJtAQYp_KHgjUvhMv464ERwOzrv2enNknlwHyQ,18461 +click/exceptions.py,sha256=1rdtXgHJ1b3OjGkN-UpXB9t_HCBihJvh_DtpmLmwn9s,9891 +click/formatting.py,sha256=Bhqx4QXdKQ9W4WKknIwj5KPKFmtduGOuGq1yw_THLZ8,9726 +click/globals.py,sha256=gM-Nh6A4M0HB_SgkaF5M4ncGGMDHc_flHXu9_oh4GEU,1923 +click/parser.py,sha256=nU1Ah2p11q29ul1vNdU9swPo_PUuKrxU6YXToi71q1c,18979 +click/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +click/shell_completion.py,sha256=CQSGdjgun4ORbOZrXP0CVhEtPx4knsufOkRsDiK64cM,19857 +click/termui.py,sha256=vAYrKC2a7f_NfEIhAThEVYfa__ib5XQbTSCGtJlABRA,30847 +click/testing.py,sha256=2eLdAaCJCGToP5Tw-XN8JjrDb3wbJIfARxg3d0crW5M,18702 +click/types.py,sha256=KBTRxN28cR1VZ5mb9iJX98MQSw_p9SGzljqfEI8z5Tw,38389 +click/utils.py,sha256=b1Mm-usEDBHtEwcPltPIn3zSK4nw2KTp5GC7_oSTlLo,20245 diff --git a/data/miniconda3/lib/python3.13/site-packages/click-8.2.1.dist-info/REQUESTED b/data/miniconda3/lib/python3.13/site-packages/click-8.2.1.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/lib/python3.13/site-packages/click-8.2.1.dist-info/WHEEL b/data/miniconda3/lib/python3.13/site-packages/click-8.2.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..d8b9936dad9ab2513fa6979f411560d3b6b57e37 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/click-8.2.1.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: flit 3.12.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/data/miniconda3/lib/python3.13/site-packages/click-8.2.1.dist-info/direct_url.json b/data/miniconda3/lib/python3.13/site-packages/click-8.2.1.dist-info/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..bf3ebd0f8b03d230643ea84462c831c7c72cd3ec --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/click-8.2.1.dist-info/direct_url.json @@ -0,0 +1 @@ +{"dir_info": {}, "url": "file:///home/task_176433224228540/conda-bld/click_1764332256338/work"} \ No newline at end of file diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/__init__.py b/data/miniconda3/lib/python3.13/site-packages/collada/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..68b30093f33ae071fa5f18ebc203609679522c50 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/collada/__init__.py @@ -0,0 +1,561 @@ +#################################################################### +# # +# THIS FILE IS PART OF THE pycollada LIBRARY SOURCE CODE. # +# USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS # +# GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE # +# IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. # +# # +# THE pycollada SOURCE CODE IS (C) COPYRIGHT 2011 # +# by Jeff Terrace and contributors # +# # +#################################################################### + +"""Main module for collada (pycollada) package. + +You will find here class `Collada` which is the one to use to access +collada file, and some exceptions that are raised in case the input +file is not what is expected. + +""" + +__version__ = "0.9.3" + +import io +import os.path +import posixpath +import traceback +import zipfile + +from collada import animation +from collada import asset +from collada import camera +from collada import controller +from collada import geometry +from collada import light +from collada import material +from collada import scene +from collada.common import E, tagger, tag +from collada.common import DaeError, DaeIncompleteError, DaeBrokenRefError, \ + DaeMalformedError, DaeSaveValidationError +from collada.util import IndexedList +from collada.xmlutil import createElementTree +from collada.xmlutil import etree as ElementTree +from collada.xmlutil import writeXML + +try: + from collada import schema +except ImportError: # no lxml + schema = None + + +class Collada(object): + """This is the main class used to create and load collada documents""" + + geometries = property(lambda s: s._geometries, lambda s, v: s._setIndexedList('_geometries', v), doc=""" + A list of :class:`collada.geometry.Geometry` objects. Can also be indexed by id""") + controllers = property(lambda s: s._controllers, lambda s, v: s._setIndexedList('_controllers', v), doc=""" + A list of :class:`collada.controller.Controller` objects. Can also be indexed by id""") + animations = property(lambda s: s._animations, lambda s, v: s._setIndexedList('_animations', v), doc=""" + A list of :class:`collada.animation.Animation` objects. Can also be indexed by id""") + lights = property(lambda s: s._lights, lambda s, v: s._setIndexedList('_lights', v), doc=""" + A list of :class:`collada.light.Light` objects. Can also be indexed by id""") + cameras = property(lambda s: s._cameras, lambda s, v: s._setIndexedList('_cameras', v), doc=""" + A list of :class:`collada.camera.Camera` objects. Can also be indexed by id""") + images = property(lambda s: s._images, lambda s, v: s._setIndexedList('_images', v), doc=""" + A list of :class:`collada.material.CImage` objects. Can also be indexed by id""") + effects = property(lambda s: s._effects, lambda s, v: s._setIndexedList('_effects', v), doc=""" + A list of :class:`collada.material.Effect` objects. Can also be indexed by id""") + materials = property(lambda s: s._materials, lambda s, v: s._setIndexedList('_materials', v), doc=""" + A list of :class:`collada.material.Effect` objects. Can also be indexed by id""") + nodes = property(lambda s: s._nodes, lambda s, v: s._setIndexedList('_nodes', v), doc=""" + A list of :class:`collada.scene.Node` objects. Can also be indexed by id""") + scenes = property(lambda s: s._scenes, lambda s, v: s._setIndexedList('_scenes', v), doc=""" + A list of :class:`collada.scene.Scene` objects. Can also be indexed by id""") + + def __init__(self, + filename=None, + ignore=None, + aux_file_loader=None, + zip_filename=None, + validate_output=False): + """Load collada data from filename or file like object. + + :param filename: + String containing path to filename to open or file-like object. + Uncompressed .dae files are supported, as well as zip file archives. + If this is set to ``None``, a new collada instance is created. + :param list ignore: + A list of :class:`common.DaeError` types that should be ignored + when loading the collada document. Instances of these types will + be added to :attr:`errors` after loading but won't be raised. + Only used if `filename` is not ``None``. + :param function aux_file_loader: + Referenced files (e.g. texture images) are loaded from disk when + reading from the local filesystem and from the zip archive when + loading from a zip file. If these files are coming from another source + (e.g. database) and/or you're loading with StringIO, set this to + a function that given a filename, returns the binary data in the file. + If `filename` is ``None``, you must set this parameter if you want to + load auxiliary files. + :param str zip_filename: + If the file being loaded is a zip archive, you can set this parameter + to indicate the file within the archive that should be loaded. If not + set, a file that ends with .dae will be searched. + :param bool validate_output: + If set to True, the XML written when calling :meth:`save` will be + validated against the COLLADA 1.4.1 schema. If validation fails, the + :class:`common.DaeSaveValidationError` exception will be thrown. + """ + + self.errors = [] + """List of :class:`common.common.DaeError` objects representing errors encountered while loading collada file""" + self.assetInfo = None + """Instance of :class:`collada.asset.Asset` containing asset information""" + + self._geometries = IndexedList([], ('id',)) + self._controllers = IndexedList([], ('id',)) + self._animations = IndexedList([], ('id',)) + self._lights = IndexedList([], ('id',)) + self._cameras = IndexedList([], ('id',)) + self._images = IndexedList([], ('id',)) + self._effects = IndexedList([], ('id',)) + self._materials = IndexedList([], ('id',)) + self._nodes = IndexedList([], ('id',)) + self._scenes = IndexedList([], ('id',)) + + self.scene = None + """The default scene. This is either an instance of :class:`collada.scene.Scene` or `None`.""" + + # a function which will apply the namespace + self.tag = tag + + if validate_output and schema: + self.validator = schema.ColladaValidator() + else: + self.validator = None + + self.maskedErrors = [] + if ignore is not None: + self.ignoreErrors(*ignore) + + if filename is None: + self.filename = None + self.zfile = None + self.getFileData = self._nullGetFile + if aux_file_loader is not None: + self.getFileData = self._wrappedFileLoader(aux_file_loader) + + self.xmlnode = ElementTree.ElementTree( + E.COLLADA( + E.library_cameras(), + E.library_controllers(), + E.library_effects(), + E.library_geometries(), + E.library_images(), + E.library_lights(), + E.library_materials(), + E.library_nodes(), + E.library_visual_scenes(), + E.scene(), + version='1.4.1')) + """ElementTree representation of the collada document""" + + self.assetInfo = asset.Asset() + return + + strdata = None + if isinstance(filename, (str, bytes)): + with open(filename, 'rb') as f: + strdata = f.read() + self.filename = filename + self.getFileData = self._getFileFromDisk + else: + strdata = filename.read() # assume it is a file like object + self.filename = None + self.getFileData = self._nullGetFile + + try: + self.zfile = zipfile.ZipFile(io.BytesIO(strdata), 'r') + except BaseException: + self.zfile = None + + if self.zfile: + self.filename = '' + daefiles = [] + if zip_filename is not None: + self.filename = zip_filename + else: + for name in self.zfile.namelist(): + if name.upper().endswith('.DAE'): + daefiles.append(name) + for name in daefiles: + if not self.filename: + self.filename = name + elif "MACOSX" in self.filename: + self.filename = name + if not self.filename or self.filename not in self.zfile.namelist(): + raise DaeIncompleteError('COLLADA file not found inside zip compressed file') + data = self.zfile.read(self.filename) + self.getFileData = self._getFileFromZip + else: + data = strdata + + if aux_file_loader is not None: + self.getFileData = self._wrappedFileLoader(aux_file_loader) + + try: + self.xmlnode = createElementTree(io.BytesIO(data)) + except ElementTree.ParseError as e: + raise DaeMalformedError("XML Parsing Error: %s" % e) + + # if we can't get the current namespace + # the tagger from above will use a hardcoded default + try: + # get the root node (whose tag is assumed to be COLLADA), + # and extract ns from its tag + xml_root = self.xmlnode.getroot() + namespace = xml_root.tag.split('}')[0].lstrip('{') + + # create a tagging function using the extracted namespace + self.tag = tagger(namespace) + except BaseException: + # failed to extract a namespace, using default + traceback.print_exc() + + # functions which will load various things into collada object + self._loadAssetInfo() + self._loadImages() + self._loadEffects() + self._loadMaterials() + self._loadAnimations() + self._loadGeometry() + self._loadControllers() + self._loadLights() + self._loadCameras() + self._loadNodes() + self._loadScenes() + self._loadDefaultScene() + + def _setIndexedList(self, propname, data): + setattr(self, propname, IndexedList(data, ('id',))) + + def handleError(self, error): + self.errors.append(error) + # use `isinstance` to check this error which will + # correctly identify subclasses, i.e. if `DaeError` + # is passed as the ignore it will ignore everything + if not any(isinstance(error, mask) for mask in self.maskedErrors): + raise + + def ignoreErrors(self, *args): + """Add exceptions to the mask for ignoring or clear the mask if None given. + + You call c.ignoreErrors(e1, e2, ... ) if you want the loader to ignore those + exceptions and continue loading whatever it can. If you want to empty the + mask so all exceptions abort the load just call c.ignoreErrors(None). + + """ + if args == [None]: + self.maskedErrors = [] + else: + for e in args: + self.maskedErrors.append(e) + + def _getFileFromZip(self, fname): + """Return the binary data of an auxiliary file from a zip archive as a string.""" + if not self.zfile: + raise DaeBrokenRefError('Trying to load an auxiliary file %s but we are not reading from a zip' % fname) + basepath = posixpath.dirname(self.filename) + aux_path = posixpath.normpath(posixpath.join(basepath, fname)) + if aux_path not in self.zfile.namelist(): + raise DaeBrokenRefError('Auxiliar file %s not found in archive' % fname) + return self.zfile.read(aux_path) + + def _getFileFromDisk(self, fname): + """Return the binary data of an auxiliary file from the local disk relative to the file path loaded.""" + if self.zfile: + raise DaeBrokenRefError('Trying to load an auxiliary file %s from disk but we are reading from a zip file' % fname) + basepath = os.path.dirname(self.filename) + aux_path = os.path.normpath(os.path.join(basepath, fname)) + if not os.path.exists(aux_path): + raise DaeBrokenRefError('Auxiliar file %s not found on disk' % fname) + fdata = open(aux_path, 'rb') + return fdata.read() + + def _wrappedFileLoader(self, aux_file_loader): + def __wrapped(fname): + res = aux_file_loader(fname) + if res is None: + raise DaeBrokenRefError('Auxiliar file %s from auxiliary file loader not found' % fname) + return res + return __wrapped + + def _nullGetFile(self, fname): + raise DaeBrokenRefError('Trying to load auxiliary file but collada was not loaded from disk, zip, or with custom handler') + + def _loadAssetInfo(self): + """Load information in tag""" + assetnode = self.xmlnode.find(self.tag('asset')) + if assetnode is not None: + self.assetInfo = asset.Asset.load(self, {}, assetnode) + else: + self.assetInfo = asset.Asset() + + def _loadGeometry(self): + """Load geometry library.""" + libnodes = self.xmlnode.findall(self.tag('library_geometries')) + if libnodes is not None: + for libnode in libnodes: + if libnode is not None: + for geomnode in libnode.findall(self.tag('geometry')): + if geomnode.find(self.tag('mesh')) is None: + continue + try: + G = geometry.Geometry.load(self, {}, geomnode) + except DaeError as ex: + self.handleError(ex) + else: + self.geometries.append(G) + + def _loadControllers(self): + """Load controller library.""" + libnodes = self.xmlnode.findall(self.tag('library_controllers')) + if libnodes is not None: + for libnode in libnodes: + if libnode is not None: + for controlnode in libnode.findall(self.tag('controller')): + if controlnode.find(self.tag('skin')) is None \ + and controlnode.find(self.tag('morph')) is None: + continue + try: + C = controller.Controller.load(self, {}, controlnode) + except DaeError as ex: + self.handleError(ex) + else: + self.controllers.append(C) + + def _loadAnimations(self): + """Load animation library.""" + libnodes = self.xmlnode.findall(self.tag('library_animations')) + if libnodes is not None: + for libnode in libnodes: + if libnode is not None: + for animnode in libnode.findall(self.tag('animation')): + try: + A = animation.Animation.load(self, {}, animnode) + except DaeError as ex: + self.handleError(ex) + else: + self.animations.append(A) + + def _loadLights(self): + """Load light library.""" + libnodes = self.xmlnode.findall(self.tag('library_lights')) + if libnodes is not None: + for libnode in libnodes: + if libnode is not None: + for lightnode in libnode.findall(self.tag('light')): + try: + lig = light.Light.load(self, {}, lightnode) + except DaeError as ex: + self.handleError(ex) + else: + self.lights.append(lig) + + def _loadCameras(self): + """Load camera library.""" + libnodes = self.xmlnode.findall(self.tag('library_cameras')) + if libnodes is not None: + for libnode in libnodes: + if libnode is not None: + for cameranode in libnode.findall(self.tag('camera')): + try: + cam = camera.Camera.load(self, {}, cameranode) + except DaeError as ex: + self.handleError(ex) + else: + self.cameras.append(cam) + + def _loadImages(self): + """Load image library.""" + libnodes = self.xmlnode.findall(self.tag('library_images')) + if libnodes is not None: + for libnode in libnodes: + if libnode is not None: + for imgnode in libnode.findall(self.tag('image')): + try: + img = material.CImage.load(self, {}, imgnode) + except DaeError as ex: + self.handleError(ex) + else: + self.images.append(img) + + def _loadEffects(self): + """Load effect library.""" + libnodes = self.xmlnode.findall(self.tag('library_effects')) + if libnodes is not None: + for libnode in libnodes: + if libnode is not None: + for effectnode in libnode.findall(self.tag('effect')): + try: + effect = material.Effect.load(self, {}, effectnode) + except DaeError as ex: + self.handleError(ex) + else: + self.effects.append(effect) + + def _loadMaterials(self): + """Load material library.""" + libnodes = self.xmlnode.findall(self.tag('library_materials')) + if libnodes is not None: + for libnode in libnodes: + if libnode is not None: + for materialnode in libnode.findall(self.tag('material')): + try: + mat = material.Material.load(self, {}, materialnode) + except DaeError as ex: + self.handleError(ex) + else: + self.materials.append(mat) + + def _loadNodes(self): + libnodes = self.xmlnode.findall(self.tag('library_nodes')) + if libnodes is not None: + for libnode in libnodes: + if libnode is not None: + tried_loading = [] + succeeded = False + for node in libnode.findall(self.tag('node')): + try: + N = scene.loadNode(self, node, {}) + except scene.DaeInstanceNotLoadedError as ex: + tried_loading.append((node, ex)) + except DaeError as ex: + self.handleError(ex) + else: + if N is not None: + self.nodes.append(N) + succeeded = True + while len(tried_loading) > 0 and succeeded: + succeeded = False + next_tried = [] + for node, ex in tried_loading: + try: + N = scene.loadNode(self, node, {}) + except scene.DaeInstanceNotLoadedError as ex: + next_tried.append((node, ex)) + except DaeError as ex: + self.handleError(ex) + else: + if N is not None: + self.nodes.append(N) + succeeded = True + tried_loading = next_tried + if len(tried_loading) > 0: + for node, ex in tried_loading: + raise DaeBrokenRefError(ex.msg) + + def _loadScenes(self): + """Load scene library.""" + libnodes = self.xmlnode.findall(self.tag('library_visual_scenes')) + if libnodes is not None: + for libnode in libnodes: + if libnode is not None: + for scenenode in libnode.findall(self.tag('visual_scene')): + try: + S = scene.Scene.load(self, scenenode) + except DaeError as ex: + self.handleError(ex) + else: + self.scenes.append(S) + + def _loadDefaultScene(self): + """Loads the default scene from tag in the root node.""" + node = self.xmlnode.find(f"{self.tag('scene')}/{self.tag('instance_visual_scene')}") + try: + if node is not None: + sceneid = node.get('url') + if not sceneid.startswith('#'): + raise DaeMalformedError('Malformed default scene reference to %s: ' % sceneid) + self.scene = self.scenes.get(sceneid[1:]) + if not self.scene: + raise DaeBrokenRefError('Default scene %s not found' % sceneid) + except DaeError as ex: + self.handleError(ex) + + def save(self): + """Saves the collada document back to :attr:`xmlnode`""" + libraries = [(self.geometries, 'library_geometries'), + (self.controllers, 'library_controllers'), + (self.lights, 'library_lights'), + (self.cameras, 'library_cameras'), + (self.images, 'library_images'), + (self.effects, 'library_effects'), + (self.materials, 'library_materials'), + (self.nodes, 'library_nodes'), + (self.scenes, 'library_visual_scenes')] + + self.assetInfo.save() + assetnode = self.xmlnode.getroot().find(self.tag('asset')) + if assetnode is not None: + self.xmlnode.getroot().remove(assetnode) + self.xmlnode.getroot().insert(0, self.assetInfo.xmlnode) + + library_loc = 0 + for i, node in enumerate(self.xmlnode.getroot()): + if node.tag == self.tag('asset'): + library_loc = i + 1 + + for arr, name in libraries: + node = self.xmlnode.find(self.tag(name)) + if node is None: + if len(arr) == 0: + continue + self.xmlnode.getroot().insert(library_loc, E(name)) + node = self.xmlnode.find(self.tag(name)) + elif node is not None and len(arr) == 0: + self.xmlnode.getroot().remove(node) + continue + + for o in arr: + o.save() + if o.xmlnode not in node: + node.append(o.xmlnode) + xmlnodes = [o.xmlnode for o in arr] + for n in node: + if n not in xmlnodes: + node.remove(n) + + scenenode = self.xmlnode.find(self.tag('scene')) + scenenode.clear() + if self.scene is not None: + sceneid = self.scene.id + if sceneid not in self.scenes: + raise DaeBrokenRefError('Default scene %s not found' % sceneid) + scenenode.append(E.instance_visual_scene(url="#%s" % sceneid)) + + if self.validator is not None: + if not self.validator.validate(self.xmlnode): + raise DaeSaveValidationError( + "Validation error when saving: {}".format( + self.validator.COLLADA_SCHEMA_1_4_1_INSTANCE.error_log.last_error.message)) + + def write(self, fp): + """Writes out the collada document to a file. Note that this also + calls :meth:`save` so avoid calling both methods to save performance. + + :param file: + Either the file name to write to or a file-like object + + """ + + self.save() + if isinstance(fp, (str, bytes)): + fp = open(fp, 'wb') + writeXML(self.xmlnode, fp) + + def __str__(self): + return '' % (len(self.geometries)) + + def __repr__(self): + return str(self) diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/__main__.py b/data/miniconda3/lib/python3.13/site-packages/collada/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..939b51f390f547a59ede90bd9418017d6b8e7ed0 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/collada/__main__.py @@ -0,0 +1,24 @@ +#################################################################### +# # +# THIS FILE IS PART OF THE pycollada LIBRARY SOURCE CODE. # +# USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS # +# GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE # +# IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. # +# # +# THE pycollada SOURCE CODE IS (C) COPYRIGHT 2011 # +# by Jeff Terrace and contributors # +# # +#################################################################### + +import os +import sys +import unittest +sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) + + +if __name__ == '__main__': + suite = unittest.TestLoader().discover("collada.tests") + ret = unittest.TextTestRunner(verbosity=2).run(suite) + if ret.wasSuccessful(): + sys.exit(0) + sys.exit(1) diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/animation.py b/data/miniconda3/lib/python3.13/site-packages/collada/animation.py new file mode 100644 index 0000000000000000000000000000000000000000..b65783c267b7d3c996308cdc48daa0f06834e9c4 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/collada/animation.py @@ -0,0 +1,59 @@ +#################################################################### +# # +# THIS FILE IS PART OF THE pycollada LIBRARY SOURCE CODE. # +# USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS # +# GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE # +# IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. # +# # +# THE pycollada SOURCE CODE IS (C) COPYRIGHT 2011 # +# by Jeff Terrace and contributors # +# # +#################################################################### + +"""Contains objects representing animations.""" + +from collada import source +from collada.common import DaeObject +from collada.common import DaeError + + +class Animation(DaeObject): + """Class for holding animation data coming from tags.""" + + def __init__(self, id, name, sourceById, children, xmlnode=None): + self.id = id + self.name = name + self.children = children + self.sourceById = sourceById + self.xmlnode = xmlnode + if self.xmlnode is None: + self.xmlnode = None + + @staticmethod + def load(collada, localscope, node): + id = node.get('id') or '' + name = node.get('name') or '' + + sourcebyid = localscope + sourcenodes = node.findall(collada.tag('source')) + for sourcenode in sourcenodes: + ch = source.Source.load(collada, {}, sourcenode) + sourcebyid[ch.id] = ch + + child_nodes = node.findall(collada.tag('animation')) + children = [] + for child in child_nodes: + try: + child = Animation.load(collada, sourcebyid, child) + children.append(child) + except DaeError as ex: + collada.handleError(ex) + + anim = Animation(id, name, sourcebyid, children, node) + return anim + + def __str__(self): + return '' % (self.id, len(self.children)) + + def __repr__(self): + return str(self) diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/asset.py b/data/miniconda3/lib/python3.13/site-packages/collada/asset.py new file mode 100644 index 0000000000000000000000000000000000000000..c09ce8e0fb06e6e2928eacb11d877c65a91db03a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/collada/asset.py @@ -0,0 +1,271 @@ +#################################################################### +# # +# THIS FILE IS PART OF THE pycollada LIBRARY SOURCE CODE. # +# USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS # +# GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE # +# IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. # +# # +# THE pycollada SOURCE CODE IS (C) COPYRIGHT 2011 # +# by Jeff Terrace and contributors # +# # +#################################################################### + +"""Contains COLLADA asset information.""" + +import datetime +import dateutil.parser + +from collada.common import DaeObject, E +from collada.util import _correctValInNode + + +class UP_AXIS: + """The up-axis of the collada document.""" + X_UP = 'X_UP' + """Indicates X direction is up""" + Y_UP = 'Y_UP' + """Indicates Y direction is up""" + Z_UP = 'Z_UP' + """Indicates Z direction is up""" + + +class Contributor(DaeObject): + """Defines authoring information for asset management""" + + def __init__(self, author=None, authoring_tool=None, comments=None, copyright=None, source_data=None, xmlnode=None): + """Create a new contributor + + :param str author: + The author's name + :param str authoring_tool: + Name of the authoring tool + :param str comments: + Comments from the contributor + :param str copyright: + Copyright information + :param str source_data: + URI referencing the source data + :param xmlnode: + If loaded from xml, the xml node + + """ + self.author = author + """Contains a string with the author's name.""" + self.authoring_tool = authoring_tool + """Contains a string with the name of the authoring tool.""" + self.comments = comments + """Contains a string with comments from this contributor.""" + self.copyright = copyright + """Contains a string with copyright information.""" + self.source_data = source_data + """Contains a string with a URI referencing the source data for this asset.""" + + if xmlnode is not None: + self.xmlnode = xmlnode + """ElementTree representation of the contributor.""" + else: + self.xmlnode = E.contributor() + if author is not None: + self.xmlnode.append(E.author(str(author))) + if authoring_tool is not None: + self.xmlnode.append(E.authoring_tool(str(authoring_tool))) + if comments is not None: + self.xmlnode.append(E.comments(str(comments))) + if copyright is not None: + self.xmlnode.append(E.copyright(str(copyright))) + if source_data is not None: + self.xmlnode.append(E.source_data(str(source_data))) + + @staticmethod + def load(collada, localscope, node): + author = node.find(collada.tag('author')) + authoring_tool = node.find(collada.tag('authoring_tool')) + comments = node.find(collada.tag('comments')) + copyright = node.find(collada.tag('copyright')) + source_data = node.find(collada.tag('source_data')) + if author is not None: + author = author.text + if authoring_tool is not None: + authoring_tool = authoring_tool.text + if comments is not None: + comments = comments.text + if copyright is not None: + copyright = copyright.text + if source_data is not None: + source_data = source_data.text + return Contributor(author=author, authoring_tool=authoring_tool, + comments=comments, copyright=copyright, source_data=source_data, xmlnode=node) + + def save(self): + """Saves the contributor info back to :attr:`xmlnode`""" + _correctValInNode(self.xmlnode, 'author', self.author) + _correctValInNode(self.xmlnode, 'authoring_tool', self.authoring_tool) + _correctValInNode(self.xmlnode, 'comments', self.comments) + _correctValInNode(self.xmlnode, 'copyright', self.copyright) + _correctValInNode(self.xmlnode, 'source_data', self.source_data) + + def __str__(self): + return '' % (str(self.author),) + + def __repr__(self): + return str(self) + + +class Asset(DaeObject): + """Defines asset-management information""" + + def __init__(self, created=None, modified=None, title=None, subject=None, revision=None, + keywords=None, unitname=None, unitmeter=None, upaxis=None, contributors=None, xmlnode=None): + """Create a new set of information about an asset + + :param datetime.datetime created: + When the asset was created. If None, this will be set to the current date and time. + :param datetime.datetime modified: + When the asset was modified. If None, this will be set to the current date and time. + :param str title: + The title of the asset + :param str subject: + The description of the topical subject of the asset + :param str revision: + Revision information about the asset + :param str keywords: + A list of words used for search criteria for the asset + :param str unitname: + The name of the unit of distance for this asset + :param float unitmeter: + How many real-world meters are in one distance unit + :param `collada.asset.UP_AXIS` upaxis: + The up-axis of the asset. If None, this will be set to Y_UP + :param list contributors: + The list of contributors for the asset + :param xmlnode: + If loaded from xml, the xml node + + """ + + if created is None: + created = datetime.datetime.now() + self.created = created + """Instance of :class:`datetime.datetime` indicating when the asset was created""" + + if modified is None: + modified = datetime.datetime.now() + self.modified = modified + """Instance of :class:`datetime.datetime` indicating when the asset was modified""" + + self.title = title + """String containing the title of the asset""" + self.subject = subject + """String containing the description of the topical subject of the asset""" + self.revision = revision + """String containing revision information about the asset""" + self.keywords = keywords + """String containing a list of words used for search criteria for the asset""" + self.unitname = unitname + """String containing the name of the unit of distance for this asset""" + self.unitmeter = unitmeter + """Float containing how many real-world meters are in one distance unit""" + + if upaxis is None: + upaxis = UP_AXIS.Y_UP + self.upaxis = upaxis + """Instance of type :class:`collada.asset.UP_AXIS` indicating the up-axis of the asset""" + + if contributors is None: + contributors = [] + self.contributors = contributors + """A list of instances of :class:`collada.asset.Contributor`""" + + if xmlnode is not None: + self.xmlnode = xmlnode + """ElementTree representation of the asset.""" + else: + self._recreateXmlNode() + + def _recreateXmlNode(self): + self.xmlnode = E.asset() + for contributor in self.contributors: + self.xmlnode.append(contributor.xmlnode) + self.xmlnode.append(E.created(self.created.isoformat())) + if self.keywords is not None: + self.xmlnode.append(E.keywords(self.keywords)) + self.xmlnode.append(E.modified(self.modified.isoformat())) + if self.revision is not None: + self.xmlnode.append(E.revision(self.revision)) + if self.subject is not None: + self.xmlnode.append(E.subject(self.subject)) + if self.title is not None: + self.xmlnode.append(E.title(self.title)) + if self.unitmeter is not None and self.unitname is not None: + self.xmlnode.append(E.unit(name=self.unitname, meter=str(self.unitmeter))) + self.xmlnode.append(E.up_axis(self.upaxis)) + + def save(self): + """Saves the asset info back to :attr:`xmlnode`""" + self._recreateXmlNode() + + @staticmethod + def load(collada, localscope, node): + contributornodes = node.findall(collada.tag('contributor')) + contributors = [Contributor.load(collada, localscope, cn) for cn in contributornodes] + + created = node.find(collada.tag('created')) + if created is not None: + try: + created = dateutil.parser.parse(created.text) + except BaseException: + created = None + + keywords = node.find(collada.tag('keywords')) + if keywords is not None: + keywords = keywords.text + + modified = node.find(collada.tag('modified')) + if modified is not None: + try: + modified = dateutil.parser.parse(modified.text) + except BaseException: + modified = None + + revision = node.find(collada.tag('revision')) + if revision is not None: + revision = revision.text + + subject = node.find(collada.tag('subject')) + if subject is not None: + subject = subject.text + + title = node.find(collada.tag('title')) + if title is not None: + title = title.text + + unitnode = node.find(collada.tag('unit')) + if unitnode is not None: + unitname = unitnode.get('name') + try: + unitmeter = float(unitnode.get('meter')) + except BaseException: + unitname = None + unitmeter = None + else: + unitname = None + unitmeter = None + + upaxis = node.find(collada.tag('up_axis')) + if upaxis is not None: + upaxis = upaxis.text + if not (upaxis == UP_AXIS.X_UP or + upaxis == UP_AXIS.Y_UP or + upaxis == UP_AXIS.Z_UP): + upaxis = None + + return Asset(created=created, modified=modified, title=title, + subject=subject, revision=revision, keywords=keywords, + unitname=unitname, unitmeter=unitmeter, upaxis=upaxis, + contributors=contributors, xmlnode=node) + + def __str__(self): + return '' % (str(self.title),) + + def __repr__(self): + return str(self) diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/camera.py b/data/miniconda3/lib/python3.13/site-packages/collada/camera.py new file mode 100644 index 0000000000000000000000000000000000000000..b4380783aeeb75924cc36bfd0250a0d6f1045cd2 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/collada/camera.py @@ -0,0 +1,403 @@ +#################################################################### +# # +# THIS FILE IS PART OF THE pycollada LIBRARY SOURCE CODE. # +# USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS # +# GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE # +# IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. # +# # +# THE pycollada SOURCE CODE IS (C) COPYRIGHT 2011 # +# by Jeff Terrace and contributors # +# # +#################################################################### + +"""Contains objects for representing cameras""" + +from collada.common import DaeIncompleteError +from collada.common import DaeMalformedError +from collada.common import DaeObject +from collada.common import DaeUnsupportedError +from collada.common import E + + +class Camera(DaeObject): + """Base camera class holding data from tags.""" + + @staticmethod + def load(collada, localscope, node): + tecnode = node.find(f"{collada.tag('optics')}/{collada.tag('technique_common')}") + if tecnode is None or len(tecnode) == 0: + raise DaeIncompleteError('Missing common technique in camera') + camnode = tecnode[0] + if camnode.tag == collada.tag('perspective'): + return PerspectiveCamera.load(collada, localscope, node) + elif camnode.tag == collada.tag('orthographic'): + return OrthographicCamera.load(collada, localscope, node) + else: + raise DaeUnsupportedError('Unrecognized camera type: %s' % camnode.tag) + + +class PerspectiveCamera(Camera): + """Perspective camera as defined in COLLADA tag .""" + + def __init__(self, id, znear, zfar, xfov=None, yfov=None, + aspect_ratio=None, xmlnode=None): + """Create a new perspective camera. + + Note: ``aspect_ratio = tan(0.5*xfov) / tan(0.5*yfov)`` + + You can specify one of: + * :attr:`xfov` alone + * :attr:`yfov` alone + * :attr:`xfov` and :attr:`yfov` + * :attr:`xfov` and :attr:`aspect_ratio` + * :attr:`yfov` and :attr:`aspect_ratio` + + Any other combination will raise :class:`collada.common.DaeMalformedError` + + :param str id: + Identifier for the camera + :param float znear: + Distance to the near clipping plane + :param float zfar: + Distance to the far clipping plane + :param float xfov: + Horizontal field of view, in degrees + :param float yfov: + Vertical field of view, in degrees + :param float aspect_ratio: + Aspect ratio of the field of view + :param xmlnode: + If loaded from xml, the xml node + + """ + + self.id = id + """Identifier for the camera""" + self.xfov = xfov + """Horizontal field of view, in degrees""" + self.yfov = yfov + """Vertical field of view, in degrees""" + self.aspect_ratio = aspect_ratio + """Aspect ratio of the field of view""" + self.znear = znear + """Distance to the near clipping plane""" + self.zfar = zfar + """Distance to the far clipping plane""" + + self._checkValidParams() + + if xmlnode is not None: + self.xmlnode = xmlnode + """ElementTree representation of the data.""" + else: + self._recreateXmlNode() + + def _recreateXmlNode(self): + perspective_node = E.perspective() + if self.xfov is not None: + perspective_node.append(E.xfov(str(self.xfov))) + if self.yfov is not None: + perspective_node.append(E.yfov(str(self.yfov))) + if self.aspect_ratio is not None: + perspective_node.append(E.aspect_ratio(str(self.aspect_ratio))) + perspective_node.append(E.znear(str(self.znear))) + perspective_node.append(E.zfar(str(self.zfar))) + self.xmlnode = E.camera( + E.optics( + E.technique_common(perspective_node) + ), id=self.id, name=self.id) + + def _checkValidParams(self): + if self.xfov is not None and self.yfov is None \ + and self.aspect_ratio is None: + pass + elif self.xfov is None and self.yfov is not None \ + and self.aspect_ratio is None: + pass + elif self.xfov is not None and self.yfov is None \ + and self.aspect_ratio is not None: + pass + elif self.xfov is None and self.yfov is not None \ + and self.aspect_ratio is not None: + pass + elif self.xfov is not None and self.yfov is not None \ + and self.aspect_ratio is None: + pass + else: + raise DaeMalformedError("Received invalid combination of xfov (%s), yfov (%s), and aspect_ratio (%s)" % + (str(self.xfov), str(self.yfov), str(self.aspect_ratio))) + + def save(self): + """Saves the perspective camera's properties back to xmlnode""" + self._checkValidParams() + self._recreateXmlNode() + + @staticmethod + def load(collada, localscope, node): + persnode = node.find(f"{collada.tag('optics')}/{collada.tag('technique_common')}/{collada.tag('perspective')}") + + if persnode is None: + raise DaeIncompleteError('Missing perspective for camera definition') + + xfov = persnode.find(collada.tag('xfov')) + yfov = persnode.find(collada.tag('yfov')) + aspect_ratio = persnode.find(collada.tag('aspect_ratio')) + znearnode = persnode.find(collada.tag('znear')) + zfarnode = persnode.find(collada.tag('zfar')) + id = node.get('id', '') + + try: + if xfov is not None: + xfov = float(xfov.text) + if yfov is not None: + yfov = float(yfov.text) + if aspect_ratio is not None: + aspect_ratio = float(aspect_ratio.text) + znear = float(znearnode.text) + zfar = float(zfarnode.text) + except (TypeError, ValueError): + raise DaeMalformedError('Corrupted float values in camera definition') + + # There are some exporters that incorrectly output all three of these. + # Worse, they actually got the calculation of aspect_ratio wrong! + # So instead of failing to load, let's just add one more hack because of terrible exporters + if xfov is not None and yfov is not None and aspect_ratio is not None: + aspect_ratio = None + + return PerspectiveCamera(id, znear, zfar, xfov=xfov, yfov=yfov, + aspect_ratio=aspect_ratio, xmlnode=node) + + def bind(self, matrix): + """Create a bound camera of itself based on a transform matrix. + + :param numpy.array matrix: + A numpy transformation matrix of size 4x4 + + :rtype: :class:`collada.camera.BoundPerspectiveCamera` + + """ + return BoundPerspectiveCamera(self, matrix) + + def __str__(self): + return '' % self.id + + def __repr__(self): + return str(self) + + +class OrthographicCamera(Camera): + """Orthographic camera as defined in COLLADA tag .""" + + def __init__(self, id, znear, zfar, xmag=None, ymag=None, aspect_ratio=None, xmlnode=None): + """Create a new orthographic camera. + + Note: ``aspect_ratio = xmag / ymag`` + + You can specify one of: + * :attr:`xmag` alone + * :attr:`ymag` alone + * :attr:`xmag` and :attr:`ymag` + * :attr:`xmag` and :attr:`aspect_ratio` + * :attr:`ymag` and :attr:`aspect_ratio` + + Any other combination will raise :class:`collada.common.DaeMalformedError` + + :param str id: + Identifier for the camera + :param float znear: + Distance to the near clipping plane + :param float zfar: + Distance to the far clipping plane + :param float xmag: + Horizontal magnification of the view + :param float ymag: + Vertical magnification of the view + :param float aspect_ratio: + Aspect ratio of the field of view + :param xmlnode: + If loaded from xml, the xml node + + """ + + self.id = id + """Identifier for the camera""" + self.xmag = xmag + """Horizontal magnification of the view""" + self.ymag = ymag + """Vertical magnification of the view""" + self.aspect_ratio = aspect_ratio + """Aspect ratio of the field of view""" + self.znear = znear + """Distance to the near clipping plane""" + self.zfar = zfar + """Distance to the far clipping plane""" + + self._checkValidParams() + + if xmlnode is not None: + self.xmlnode = xmlnode + """ElementTree representation of the data.""" + else: + self._recreateXmlNode() + + def _recreateXmlNode(self): + orthographic_node = E.orthographic() + if self.xmag is not None: + orthographic_node.append(E.xmag(str(self.xmag))) + if self.ymag is not None: + orthographic_node.append(E.ymag(str(self.ymag))) + if self.aspect_ratio is not None: + orthographic_node.append(E.aspect_ratio(str(self.aspect_ratio))) + orthographic_node.append(E.znear(str(self.znear))) + orthographic_node.append(E.zfar(str(self.zfar))) + self.xmlnode = E.camera( + E.optics( + E.technique_common(orthographic_node) + ), id=self.id, name=self.id) + + def _checkValidParams(self): + if self.xmag is not None and self.ymag is None \ + and self.aspect_ratio is None: + pass + elif self.xmag is None and self.ymag is not None \ + and self.aspect_ratio is None: + pass + elif self.xmag is not None and self.ymag is None \ + and self.aspect_ratio is not None: + pass + elif self.xmag is None and self.ymag is not None \ + and self.aspect_ratio is not None: + pass + elif self.xmag is not None and self.ymag is not None \ + and self.aspect_ratio is None: + pass + else: + raise DaeMalformedError("Received invalid combination of xmag (%s), ymag (%s), and aspect_ratio (%s)" % + (str(self.xmag), str(self.ymag), str(self.aspect_ratio))) + + def save(self): + """Saves the orthographic camera's properties back to xmlnode""" + self._checkValidParams() + self._recreateXmlNode() + + @staticmethod + def load(collada, localscope, node): + orthonode = node.find(f"{collada.tag('optics')}/{collada.tag('technique_common')}/{collada.tag('orthographic')}") + + if orthonode is None: + raise DaeIncompleteError('Missing orthographic for camera definition') + + xmag = orthonode.find(collada.tag('xmag')) + ymag = orthonode.find(collada.tag('ymag')) + aspect_ratio = orthonode.find(collada.tag('aspect_ratio')) + znearnode = orthonode.find(collada.tag('znear')) + zfarnode = orthonode.find(collada.tag('zfar')) + id = node.get('id', '') + + try: + if xmag is not None: + xmag = float(xmag.text) + if ymag is not None: + ymag = float(ymag.text) + if aspect_ratio is not None: + aspect_ratio = float(aspect_ratio.text) + znear = float(znearnode.text) + zfar = float(zfarnode.text) + except (TypeError, ValueError): + raise DaeMalformedError('Corrupted float values in camera definition') + + # There are some exporters that incorrectly output all three of these. + # Worse, they actually got the calculation of aspect_ratio wrong! + # So instead of failing to load, let's just add one more hack because of terrible exporters + if xmag is not None and ymag is not None and aspect_ratio is not None: + aspect_ratio = None + + return OrthographicCamera(id, znear, zfar, xmag=xmag, ymag=ymag, + aspect_ratio=aspect_ratio, xmlnode=node) + + def bind(self, matrix): + """Create a bound camera of itself based on a transform matrix. + + :param numpy.array matrix: + A numpy transformation matrix of size 4x4 + + :rtype: :class:`collada.camera.BoundOrthographicCamera` + + """ + return BoundOrthographicCamera(self, matrix) + + def __str__(self): + return '' % self.id + + def __repr__(self): + return str(self) + + +class BoundCamera(object): + """Base class for bound cameras""" + + +class BoundPerspectiveCamera(BoundCamera): + """Perspective camera bound to a scene with a transform. This gets created when a + camera is instantiated in a scene. Do not create this manually.""" + + def __init__(self, cam, matrix): + self.xfov = cam.xfov + """Horizontal field of view, in degrees""" + self.yfov = cam.yfov + """Vertical field of view, in degrees""" + self.aspect_ratio = cam.aspect_ratio + """Aspect ratio of the field of view""" + self.znear = cam.znear + """Distance to the near clipping plane""" + self.zfar = cam.zfar + """Distance to the far clipping plane""" + self.matrix = matrix + """The matrix bound to""" + self.position = matrix[:3, 3] + """The position of the camera""" + self.direction = -matrix[:3, 2] + """The direction the camera is facing""" + self.up = matrix[:3, 1] + """The up vector of the camera""" + self.original = cam + """Original :class:`collada.camera.PerspectiveCamera` object this is bound to.""" + + def __str__(self): + return '' % self.original.id + + def __repr__(self): + return str(self) + + +class BoundOrthographicCamera(BoundCamera): + """Orthographic camera bound to a scene with a transform. This gets created when a + camera is instantiated in a scene. Do not create this manually.""" + + def __init__(self, cam, matrix): + self.xmag = cam.xmag + """Horizontal magnification of the view""" + self.ymag = cam.ymag + """Vertical magnification of the view""" + self.aspect_ratio = cam.aspect_ratio + """Aspect ratio of the field of view""" + self.znear = cam.znear + """Distance to the near clipping plane""" + self.zfar = cam.zfar + """Distance to the far clipping plane""" + self.matrix = matrix + """The matrix bound to""" + self.position = matrix[:3, 3] + """The position of the camera""" + self.direction = -matrix[:3, 2] + """The direction the camera is facing""" + self.up = matrix[:3, 1] + """The up vector of the camera""" + self.original = cam + """Original :class:`collada.camera.OrthographicCamera` object this is bound to.""" + + def __str__(self): + return '' % self.original.id + + def __repr__(self): + return str(self) diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/common.py b/data/miniconda3/lib/python3.13/site-packages/collada/common.py new file mode 100644 index 0000000000000000000000000000000000000000..030a4183a900022e4979fad81e52ac3b00f95fa8 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/collada/common.py @@ -0,0 +1,112 @@ +from functools import cache + +from collada.xmlutil import ElementMaker, COLLADA_NS + +E = ElementMaker(namespace=COLLADA_NS, nsmap={None: COLLADA_NS}) + + +@cache +def tag(text, namespace=None): + """ + Tag a text key with the collada namespace, by default: + '{http://www.collada.org/2005/11/COLLADASchema}' + + :param string text: + The text to be tagged, i.e. 'geometry' + :param string namespace: + The namespace to tag with (not including brackets) + Will use default namespace if None is passed + """ + if namespace is None: + namespace = COLLADA_NS + return '{%s}%s' % (namespace, text) + + +def tagger(namespace=None): + """ + A closure, or function that returns a function. + Returned function tags using a specified namespace. + + :param string namespace: + The XML namespace to use to tag elements + + :return: + tag() function + """ + @cache + def tag(text): + return '{%s}%s' % (namespace, text) + + return tag + + +class DaeObject(object): + """This class is the abstract interface to all collada objects. + + Every in a COLLADA that we recognize and load has mirror + class deriving from this one. All instances will have at least + a :meth:`load` method which creates the object from an xml node and + an attribute called :attr:`xmlnode` with the ElementTree representation + of the data. Even if it was created on the fly. If the object is + not read-only, it will also have a :meth:`save` method which saves the + object's information back to the :attr:`xmlnode` attribute. + + """ + + xmlnode = None + """ElementTree representation of the data.""" + + @staticmethod + def load(collada, localscope, node): + """Load and return a class instance from an XML node. + + Inspect the data inside node, which must match + this class tag and create an instance out of it. + + :param collada.Collada collada: + The collada file object where this object lives + :param dict localscope: + If there is a local scope where we should look for local ids + (sid) this is the dictionary. Otherwise empty dict ({}) + :param node: + An Element from python's ElementTree API + + """ + raise Exception('Not implemented') + + def save(self): + """Put all the data to the internal xml node (xmlnode) so it can be serialized.""" + + +class DaeError(Exception): + """General DAE exception.""" + + def __init__(self, msg): + super(DaeError, self).__init__() + self.msg = msg + + def __str__(self): + return type(self).__name__ + ': ' + self.msg + + def __repr__(self): + return type(self).__name__ + '("' + self.msg + '")' + + +class DaeIncompleteError(DaeError): + """Raised when needed data for an object isn't there.""" + + +class DaeBrokenRefError(DaeError): + """Raised when a referenced object is not found in the scope.""" + + +class DaeMalformedError(DaeError): + """Raised when data is found to be corrupted in some way.""" + + +class DaeUnsupportedError(DaeError): + """Raised when some unexpectedly unsupported feature is found.""" + + +class DaeSaveValidationError(DaeError): + """Raised when XML validation fails when saving.""" diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/controller.py b/data/miniconda3/lib/python3.13/site-packages/collada/controller.py new file mode 100644 index 0000000000000000000000000000000000000000..82b3146975eae96705f1636bc3c6ce395b663836 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/collada/controller.py @@ -0,0 +1,408 @@ +#################################################################### +# # +# THIS FILE IS PART OF THE pycollada LIBRARY SOURCE CODE. # +# USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS # +# GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE # +# IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. # +# # +# THE pycollada SOURCE CODE IS (C) COPYRIGHT 2011 # +# by Jeff Terrace and contributors # +# # +#################################################################### + +"""Contains objects representing controllers. Currently has partial + support for loading Skin and Morph. **This module is highly + experimental. More support will be added in version 0.4.**""" + +import numpy + +from collada import source +from collada.common import DaeObject +from collada.common import DaeIncompleteError, DaeBrokenRefError, \ + DaeMalformedError, DaeUnsupportedError +from collada.geometry import Geometry +from collada.util import checkSource + + +class Controller(DaeObject): + """Base controller class holding data from tags.""" + + def bind(self, matrix, materialnodebysymbol): + pass + + @staticmethod + def load(collada, localscope, node): + controller = node.find(collada.tag('skin')) + if controller is None: + controller = node.find(collada.tag('morph')) + if controller is None: + raise DaeUnsupportedError('Unknown controller node') + + sourcebyid = {} + sourcenodes = node.findall(f"{controller.tag}/{collada.tag('source')}") + for sourcenode in sourcenodes: + ch = source.Source.load(collada, {}, sourcenode) + sourcebyid[ch.id] = ch + + if controller.tag == collada.tag('skin'): + return Skin.load(collada, sourcebyid, controller, node) + else: + return Morph.load(collada, sourcebyid, controller, node) + + +class BoundController(object): + """Base class for a controller bound to a transform matrix and materials mapping.""" + + +class Skin(Controller): + """Class containing data collada holds in the tag""" + + def __init__(self, sourcebyid, bind_shape_matrix, joint_source, joint_matrix_source, + weight_source, weight_joint_source, vcounts, vertex_weight_index, + offsets, geometry, controller_node=None, skin_node=None): + """Create a skin. + + :Parameters: + sourceById + A dict mapping id's to a collada source + bind_shape_matrix + A numpy array of floats (pre-shape) + joint_source + The string id for the joint source + joint_matrix_source + The string id for the joint matrix source + weight_source + The string id for the weight source + weight_joint_source + The string id for the joint source of weights + vcounts + A list with the number of influences on each vertex + vertex_weight_index + An array with the indexes as they come from array + offsets + A list with the offsets in the weight index array for each source + in (joint, weight) + geometry + The source geometry this should be applied to (geometry.Geometry) + controller_node + XML node of the tag which is the parent of this + skin_node + XML node of the tag if this is from there + + """ + self.sourcebyid = sourcebyid + self.bind_shape_matrix = bind_shape_matrix + self.joint_source = joint_source + self.joint_matrix_source = joint_matrix_source + self.weight_source = weight_source + self.weight_joint_source = weight_joint_source + self.vcounts = vcounts + self.vertex_weight_index = vertex_weight_index + self.offsets = offsets + self.geometry = geometry + self.controller_node = controller_node + self.skin_node = skin_node + self.xmlnode = controller_node + + if not isinstance(self.geometry, Geometry): + raise DaeMalformedError('Invalid reference geometry in skin') + + self.id = controller_node.get('id') + if self.id is None: + raise DaeMalformedError('Controller node requires an ID') + + self.nindices = max(self.offsets) + 1 + + if len(bind_shape_matrix) != 16: + raise DaeMalformedError('Corrupted bind shape matrix in skin') + self.bind_shape_matrix.shape = (4, 4) + + if not (joint_source in sourcebyid and joint_matrix_source in sourcebyid): + raise DaeBrokenRefError("Input in joints not found") + if not (isinstance(sourcebyid[joint_source], source.NameSource) or isinstance(sourcebyid[joint_source], source.IDRefSource)): + raise DaeIncompleteError("Could not find joint name input for skin") + if not isinstance(sourcebyid[joint_matrix_source], source.FloatSource): + raise DaeIncompleteError("Could not find joint matrix source for skin") + joint_names = [j for j in sourcebyid[joint_source]] + joint_matrices = sourcebyid[joint_matrix_source].data + joint_matrices.shape = (-1, 4, 4) + if len(joint_names) != len(joint_matrices): + raise DaeMalformedError("Skin joint and matrix inputs must be same length") + self.joint_matrices = dict(zip(joint_names, joint_matrices)) + + if not (weight_source in sourcebyid and weight_joint_source in sourcebyid): + raise DaeBrokenRefError("Weights input in joints not found") + if not isinstance(sourcebyid[weight_source], source.FloatSource): + raise DaeIncompleteError("Could not find weight inputs for skin") + if not (isinstance(sourcebyid[weight_joint_source], source.NameSource) or isinstance(sourcebyid[weight_joint_source], source.IDRefSource)): + raise DaeIncompleteError("Could not find weight joint source input for skin") + self.weights = sourcebyid[weight_source] + self.weight_joints = sourcebyid[weight_joint_source] + + try: + newshape = [] + at = 0 + for ct in self.vcounts: + this_set = self.vertex_weight_index[self.nindices * at:self.nindices * (at + ct)] + this_set.shape = (ct, self.nindices) + newshape.append(numpy.array(this_set)) + at += ct + self.index = newshape + except BaseException: + raise DaeMalformedError('Corrupted vcounts or index in skin weights') + + try: + self.joint_index = [influence[:, self.offsets[0]] for influence in self.index] + self.weight_index = [influence[:, self.offsets[1]] for influence in self.index] + except BaseException: + raise DaeMalformedError('Corrupted joint or weight index in skin') + + self.max_joint_index = numpy.max([numpy.max(joint) if len(joint) > 0 else 0 for joint in self.joint_index]) + self.max_weight_index = numpy.max([numpy.max(weight) if len(weight) > 0 else 0 for weight in self.weight_index]) + checkSource(self.weight_joints, ('JOINT',), self.max_joint_index) + checkSource(self.weights, ('WEIGHT',), self.max_weight_index) + + def __len__(self): + return len(self.index) + + def __getitem__(self, i): + return self.index[i] + + def bind(self, matrix, materialnodebysymbol): + """Create a bound morph from this one, transform and material mapping""" + return BoundSkin(self, matrix, materialnodebysymbol) + + @staticmethod + def load(collada, localscope, skinnode, controllernode): + if len(localscope) < 3: + raise DaeMalformedError('Not enough sources in skin') + + geometry_source = skinnode.get('source') + if geometry_source is None or len(geometry_source) < 2 \ + or geometry_source[0] != '#': + raise DaeBrokenRefError('Invalid source attribute of skin node') + if not geometry_source[1:] in collada.geometries: + raise DaeBrokenRefError('Source geometry for skin node not found') + geometry = collada.geometries[geometry_source[1:]] + + bind_shape_mat = skinnode.find(collada.tag('bind_shape_matrix')) + if bind_shape_mat is None: + bind_shape_mat = numpy.identity(4, dtype=numpy.float32) + bind_shape_mat.shape = (-1,) + else: + try: + values = [float(v) for v in bind_shape_mat.text.split()] + except ValueError: + raise DaeMalformedError('Corrupted bind shape matrix in skin') + bind_shape_mat = numpy.array(values, dtype=numpy.float32) + + inputnodes = skinnode.findall(f"{collada.tag('joints')}/{collada.tag('input')}") + if inputnodes is None or len(inputnodes) < 2: + raise DaeIncompleteError("Not enough inputs in skin joints") + + try: + inputs = [(i.get('semantic'), i.get('source')) for i in inputnodes] + except ValueError: + raise DaeMalformedError('Corrupted inputs in skin') + + joint_source = None + matrix_source = None + for i in inputs: + if len(i[1]) < 2 or i[1][0] != '#': + raise DaeBrokenRefError('Input in skin node %s not found' % i[1]) + if i[0] == 'JOINT': + joint_source = i[1][1:] + elif i[0] == 'INV_BIND_MATRIX': + matrix_source = i[1][1:] + + weightsnode = skinnode.find(collada.tag('vertex_weights')) + if weightsnode is None: + raise DaeIncompleteError("No vertex_weights found in skin") + indexnode = weightsnode.find(collada.tag('v')) + if indexnode is None: + raise DaeIncompleteError('Missing indices in skin vertex weights') + vcountnode = weightsnode.find(collada.tag('vcount')) + if vcountnode is None: + raise DaeIncompleteError('Missing vcount in skin vertex weights') + inputnodes = weightsnode.findall(collada.tag('input')) + + try: + index = numpy.array([float(v) + for v in indexnode.text.split()], dtype=numpy.int32) + vcounts = numpy.array([int(v) + for v in vcountnode.text.split()], dtype=numpy.int32) + inputs = [(i.get('semantic'), i.get('source'), int(i.get('offset'))) + for i in inputnodes] + except ValueError: + raise DaeMalformedError('Corrupted index or offsets in skin vertex weights') + + weight_joint_source = None + weight_source = None + offsets = [0, 0] + for i in inputs: + if len(i[1]) < 2 or i[1][0] != '#': + raise DaeBrokenRefError('Input in skin node %s not found' % i[1]) + if i[0] == 'JOINT': + weight_joint_source = i[1][1:] + offsets[0] = i[2] + elif i[0] == 'WEIGHT': + weight_source = i[1][1:] + offsets[1] = i[2] + + if joint_source is None or weight_source is None: + raise DaeMalformedError('Not enough inputs for vertex weights in skin') + + return Skin(localscope, bind_shape_mat, joint_source, matrix_source, + weight_source, weight_joint_source, vcounts, index, offsets, + geometry, controllernode, skinnode) + + +class BoundSkin(BoundController): + """A skin bound to a transform matrix and materials mapping.""" + + def __init__(self, skin, matrix, materialnodebysymbol): + self.matrix = matrix + self.materialnodebysymbol = materialnodebysymbol + self.skin = skin + self.id = skin.id + self.index = skin.index + self.joint_matrices = skin.joint_matrices + self.geometry = skin.geometry.bind(numpy.dot(matrix, skin.bind_shape_matrix), materialnodebysymbol) + + def __len__(self): + return len(self.index) + + def __getitem__(self, i): + return self.index[i] + + def getJoint(self, i): + return self.skin.weight_joints[i] + + def getWeight(self, i): + return self.skin.weights[i] + + def primitives(self): + for prim in self.geometry.primitives(): + bsp = BoundSkinPrimitive(prim, self) + yield bsp + + +class BoundSkinPrimitive(object): + """A bound skin bound to a primitive.""" + + def __init__(self, primitive, boundskin): + self.primitive = primitive + self.boundskin = boundskin + + def __len__(self): + return len(self.primitive) + + def shapes(self): + for shape in self.primitive.shapes(): + yield shape + + +class Morph(Controller): + """Class containing data collada holds in the tag""" + + def __init__(self, source_geometry, target_list, xmlnode=None): + """Create a morph instance + + :Parameters: + source_geometry + The source geometry (Geometry) + targets + A list of tuples where each tuple (g,w) contains + a Geometry (g) and a float weight value (w) + xmlnode + When loaded, the xmlnode it comes from + + """ + self.id = xmlnode.get('id') + if self.id is None: + raise DaeMalformedError('Controller node requires an ID') + self.source_geometry = source_geometry + """The source geometry (Geometry)""" + self.target_list = target_list + """A list of tuples where each tuple (g,w) contains + a Geometry (g) and a float weight value (w)""" + + self.xmlnode = xmlnode + # TODO + + def __len__(self): + return len(self.target_list) + + def __getitem__(self, i): + return self.target_list[i] + + def bind(self, matrix, materialnodebysymbol): + """Create a bound morph from this one, transform and material mapping""" + return BoundMorph(self, matrix, materialnodebysymbol) + + @staticmethod + def load(collada, localscope, morphnode, controllernode): + baseid = morphnode.get('source') + if len(baseid) < 2 or baseid[0] != '#' or \ + not baseid[1:] in collada.geometries: + raise DaeBrokenRefError('Base source of morph %s not found' % baseid) + basegeom = collada.geometries[baseid[1:]] + + method = morphnode.get('method') + if method is None: + method = 'NORMALIZED' + if not (method == 'NORMALIZED' or method == 'RELATIVE'): + raise DaeMalformedError("Morph method must be either NORMALIZED or RELATIVE. Found '%s'" % method) + + inputnodes = morphnode.findall(f"{collada.tag('targets')}/{collada.tag('input')}") + if inputnodes is None or len(inputnodes) < 2: + raise DaeIncompleteError("Not enough inputs in a morph") + + try: + inputs = [(i.get('semantic'), i.get('source')) for i in inputnodes] + except ValueError: + raise DaeMalformedError('Corrupted inputs in morph') + + target_source = None + weight_source = None + for i in inputs: + if len(i[1]) < 2 or i[1][0] != '#' or not i[1][1:] in localscope: + raise DaeBrokenRefError('Input in morph node %s not found' % i[1]) + if i[0] == 'MORPH_TARGET': + target_source = localscope[i[1][1:]] + elif i[0] == 'MORPH_WEIGHT': + weight_source = localscope[i[1][1:]] + + if not isinstance(target_source, source.IDRefSource) or \ + not isinstance(weight_source, source.FloatSource): + raise DaeIncompleteError("Not enough inputs in targets of morph") + + if len(target_source) != len(weight_source): + raise DaeMalformedError("Morph inputs must be of same length") + + target_list = [] + for target, weight in zip(target_source, weight_source): + if len(target) < 1 or not (target in collada.geometries): + raise DaeBrokenRefError("Targeted geometry %s in morph not found" % target) + target_list.append((collada.geometries[target], weight[0])) + + return Morph(basegeom, target_list, controllernode) + + def save(self): + # TODO + pass + + +class BoundMorph(BoundController): + """A morph bound to a transform matrix and materials mapping.""" + + def __init__(self, morph, matrix, materialnodebysymbol): + self.matrix = matrix + self.materialnodebysymbol = materialnodebysymbol + self.original = morph + + def __len__(self): + return len(self.original) + + def __getitem__(self, i): + return self.original[i] diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/geometry.py b/data/miniconda3/lib/python3.13/site-packages/collada/geometry.py new file mode 100644 index 0000000000000000000000000000000000000000..b2fbed2d9a49c2be2d3a02a7b65a8d425de95096 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/collada/geometry.py @@ -0,0 +1,390 @@ +#################################################################### +# # +# THIS FILE IS PART OF THE pycollada LIBRARY SOURCE CODE. # +# USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS # +# GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE # +# IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. # +# # +# THE pycollada SOURCE CODE IS (C) COPYRIGHT 2011 # +# by Jeff Terrace and contributors # +# # +#################################################################### + +"""Contains objects for representing a geometry.""" + + +from collada import source +from collada import triangleset +from collada import lineset +from collada import polylist +from collada import polygons +from collada import primitive +from collada.common import DaeObject, E, tag +from collada.common import DaeIncompleteError, DaeUnsupportedError + + +class Geometry(DaeObject): + """A class containing the data coming from a COLLADA tag""" + + def __init__(self, collada, id, name, sourcebyid, primitives=None, + xmlnode=None, double_sided=False): + """Create a geometry instance + + :param collada.Collada collada: + The collada object this geometry belongs to + :param str id: + A unique string identifier for the geometry + :param str name: + A text string naming the geometry + :param sourcebyid: + A list of :class:`collada.source.Source` objects or + a dictionary mapping source ids to the actual objects + :param list primitives: + List of primitive objects contained within the geometry. + Do not set this argument manually. Instead, create a + :class:`collada.geometry.Geometry` first and then append + to :attr:`primitives` with the `create*` functions. + :param xmlnode: + When loaded, the xmlnode it comes from. + :param bool double_sided: + Whether or not the geometry should be rendered double sided + + """ + self.collada = collada + """The :class:`collada.Collada` object this geometry belongs to""" + + self.id = id + """The unique string identifier for the geometry""" + + self.name = name + """The text string naming the geometry""" + + self.double_sided = double_sided + """A boolean indicating whether or not the geometry should be rendered double sided""" + + self.sourceById = sourcebyid + """A dictionary containing :class:`collada.source.Source` objects indexed by their id.""" + + if isinstance(sourcebyid, list): + self.sourceById = {} + for src in sourcebyid: + self.sourceById[src.id] = src + + self.primitives = [] + """List of primitives (base type :class:`collada.primitive.Primitive`) inside this geometry.""" + if primitives is not None: + self.primitives = primitives + + if xmlnode is not None: + self.xmlnode = xmlnode + """ElementTree representation of the geometry.""" + else: + sourcenodes = [] + verticesnode = None + for srcid, src in self.sourceById.items(): + sourcenodes.append(src.xmlnode) + if verticesnode is None: + # pick first source to be in the useless tag + verticesnode = E.vertices(E.input(semantic='POSITION', source="#%s" % srcid), + id=srcid + '-vertices') + meshnode = E.mesh(*sourcenodes) + meshnode.append(verticesnode) + self.xmlnode = E.geometry(meshnode) + if len(self.id) > 0: + self.xmlnode.set("id", self.id) + if len(self.name) > 0: + self.xmlnode.set("name", self.name) + + def createLineSet(self, indices, inputlist, materialid=None): + """Create a set of lines for use in this geometry instance. + + :param numpy.array indices: + unshaped numpy array that contains the indices for + the inputs referenced in inputlist + :param collada.source.InputList inputlist: + The inputs for this primitive + :param str materialid: + A string containing a symbol that will get used to bind this lineset + to a material when instantiating into a scene + + :rtype: :class:`collada.lineset.LineSet` + """ + inputdict = primitive.Primitive._getInputsFromList(self.collada, self.sourceById, inputlist.getList()) + return lineset.LineSet(inputdict, materialid, indices) + + def createTriangleSet(self, indices, inputlist, materialid=None): + """Create a set of triangles for use in this geometry instance. + + :param numpy.array indices: + unshaped numpy array that contains the indices for + the inputs referenced in inputlist + :param collada.source.InputList inputlist: + The inputs for this primitive + :param str materialid: + A string containing a symbol that will get used to bind this triangleset + to a material when instantiating into a scene + + :rtype: :class:`collada.triangleset.TriangleSet` + """ + inputdict = primitive.Primitive._getInputsFromList(self.collada, self.sourceById, inputlist.getList()) + return triangleset.TriangleSet(inputdict, materialid, indices) + + def createPolylist(self, indices, vcounts, inputlist, materialid=None): + """Create a polylist for use with this geometry instance. + + :param numpy.array indices: + unshaped numpy array that contains the indices for + the inputs referenced in inputlist + :param numpy.array vcounts: + unshaped numpy array that contains the vertex count + for each polygon in this polylist + :param collada.source.InputList inputlist: + The inputs for this primitive + :param str materialid: + A string containing a symbol that will get used to bind this polylist + to a material when instantiating into a scene + + :rtype: :class:`collada.polylist.Polylist` + """ + inputdict = primitive.Primitive._getInputsFromList(self.collada, self.sourceById, inputlist.getList()) + return polylist.Polylist(inputdict, materialid, indices, vcounts) + + def createPolygons(self, indices, inputlist, materialid=None): + """Create a polygons for use with this geometry instance. + + :param numpy.array indices: + list of unshaped numpy arrays that each contain the indices for + a single polygon + :param collada.source.InputList inputlist: + The inputs for this primitive + :param str materialid: + A string containing a symbol that will get used to bind this polygons + to a material when instantiating into a scene + + :rtype: :class:`collada.polygons.Polygons` + """ + inputdict = primitive.Primitive._getInputsFromList(self.collada, self.sourceById, inputlist.getList()) + return polygons.Polygons(inputdict, materialid, indices) + + @staticmethod + def load(collada, localscope, node): + id = node.get("id") or "" + name = node.get("name") or "" + tag_mesh = collada.tag('mesh') + tag_source = collada.tag('source') + tag_vertices = collada.tag('vertices') + tag_input = collada.tag('input') + tag_extra = collada.tag('extra') + tag_double_sided = collada.tag('double_sided') + tag_polylist = collada.tag('polylist') + tag_triangles = collada.tag('triangles') + tag_tristrips = collada.tag('tristrips') + tag_trifans = collada.tag('trifans') + tag_lines = collada.tag('lines') + tag_polygons = collada.tag('polygons') + + meshnode = node.find(tag_mesh) + if meshnode is None: + raise DaeUnsupportedError('Unknown geometry node') + + # Single pass over meshnode: collect sources, vertices, and primitive nodes + sourcebyid = {} + verticesnode = None + primitive_nodes = [] + tri_tags = {tag_triangles, tag_tristrips, tag_trifans} + + for subnode in meshnode: + tag = subnode.tag + if tag == tag_source: + ch = source.Source.load(collada, {}, subnode) + sourcebyid[ch.id] = ch + elif tag == tag_vertices: + verticesnode = subnode + elif tag == tag_polylist: + primitive_nodes.append(('polylist', subnode)) + elif tag in tri_tags: + primitive_nodes.append(('triangles', subnode)) + elif tag == tag_lines: + primitive_nodes.append(('lines', subnode)) + elif tag == tag_polygons: + primitive_nodes.append(('polygons', subnode)) + elif tag != tag_extra: + raise DaeUnsupportedError('Unknown geometry tag %s' % tag) + + # Process vertices node (needs sourcebyid populated) + if verticesnode is not None: + inputnodes = {} + for inputnode in verticesnode.iterfind(tag_input): + semantic = inputnode.get('semantic') + inputsource = inputnode.get('source') + if not semantic or not inputsource or not inputsource.startswith('#'): + raise DaeIncompleteError('Bad input definition inside vertices') + inputnodes[semantic] = sourcebyid.get(inputsource[1:]) + vertices_id = verticesnode.get('id') + if not vertices_id or len(inputnodes) == 0 or 'POSITION' not in inputnodes: + raise DaeIncompleteError('Bad vertices definition in mesh') + sourcebyid[vertices_id] = inputnodes + + # Check for double_sided in extra nodes (on parent node, not meshnode) + double_sided = False + for extra in node.iterfind(tag_extra): + double_sided_node = extra.find(f".//{tag_double_sided}") + if double_sided_node is not None and double_sided_node.text is not None: + try: + if int(double_sided_node.text) == 1: + double_sided = True + break + except ValueError: + pass + + # Load primitives (needs complete sourcebyid with vertices) + _primitives = [] + for ptype, pnode in primitive_nodes: + if ptype == 'polylist': + _primitives.append(polylist.Polylist.load(collada, sourcebyid, pnode)) + elif ptype == 'triangles': + _primitives.append(triangleset.TriangleSet.load(collada, sourcebyid, pnode)) + elif ptype == 'lines': + _primitives.append(lineset.LineSet.load(collada, sourcebyid, pnode)) + else: # polygons + _primitives.append(polygons.Polygons.load(collada, sourcebyid, pnode)) + + return Geometry(collada, id, name, sourcebyid, _primitives, xmlnode=node, double_sided=double_sided) + + def save(self): + """Saves the geometry back to :attr:`xmlnode`""" + meshnode = self.xmlnode.find(tag('mesh')) + for src in self.sourceById.values(): + if isinstance(src, source.Source): + src.save() + if src.xmlnode not in meshnode: + meshnode.insert(0, src.xmlnode) + + deletenodes = [] + for oldsrcnode in meshnode.findall(tag('source')): + if oldsrcnode not in [src.xmlnode + for src in self.sourceById.values() + if isinstance(src, source.Source)]: + deletenodes.append(oldsrcnode) + for d in deletenodes: + meshnode.remove(d) + + # Look through primitives to find a vertex source + vnode = self.xmlnode.find(tag('mesh')).find(tag('vertices')) + + # delete any inputs in vertices tag that no longer exist and find the vertex input + delete_inputs = [] + for input_node in vnode.findall(tag('input')): + if input_node.get('semantic') == 'POSITION': + input_vnode = input_node + else: + srcid = input_node.get('source')[1:] + if srcid not in self.sourceById: + delete_inputs.append(input_node) + + for node in delete_inputs: + vnode.remove(node) + + vert_sources = [] + for prim in self.primitives: + for src in prim.sources['VERTEX']: + vert_sources.append(src[2][1:]) + + vert_src = vnode.get('id') + vert_ref = input_vnode.get('source')[1:] + + if not (vert_src in vert_sources or vert_ref in vert_sources) and len(vert_sources) > 0: + if vert_ref in self.sourceById and vert_ref in vert_sources: + new_source = vert_ref + else: + new_source = vert_sources[0] + self.sourceById[new_source + '-vertices'] = self.sourceById[new_source] + input_vnode.set('source', '#' + new_source) + vnode.set('id', new_source + '-vertices') + + # any source references in primitives that are pointing to the + # same source that the vertices tag is pointing to to instead + # point to the vertices id + vert_src = vnode.get('id') + vert_ref = input_vnode.get('source')[1:] + for prim in self.primitives: + for node in prim.xmlnode.findall(tag('input')): + src = node.get('source')[1:] + if src == vert_ref: + node.set('source', '#%s' % vert_src) + + self.xmlnode.set('id', self.id) + self.xmlnode.set('name', self.name) + + for prim in self.primitives: + if isinstance(prim, triangleset.TriangleSet) and prim.xmlnode.tag != tag('triangles'): + prim._recreateXmlNode() + if prim.xmlnode not in meshnode: + meshnode.append(prim.xmlnode) + + deletenodes = [] + primnodes = [prim.xmlnode for prim in self.primitives] + for child in meshnode: + if child.tag != tag('vertices') and child.tag != tag('source') and child not in primnodes: + deletenodes.append(child) + for d in deletenodes: + meshnode.remove(d) + + def bind(self, matrix, materialnodebysymbol): + """Binds this geometry to a transform matrix and material mapping. + The geometry's points get transformed by the given matrix and its + inputs get mapped to the given materials. + + :param numpy.array matrix: + A 4x4 numpy float matrix + :param dict materialnodebysymbol: + A dictionary with the material symbols inside the primitive + assigned to :class:`collada.scene.MaterialNode` defined in the + scene + + :rtype: :class:`collada.geometry.BoundGeometry` + + """ + return BoundGeometry(self, matrix, materialnodebysymbol) + + def __str__(self): + return '' % (self.id, len(self.primitives)) + + def __repr__(self): + return str(self) + + +class BoundGeometry(object): + """A geometry bound to a transform matrix and material mapping. + This gets created when a geometry is instantiated in a scene. + Do not create this manually.""" + + def __init__(self, geom, matrix, materialnodebysymbol): + self.matrix = matrix + """The matrix bound to""" + self.materialnodebysymbol = materialnodebysymbol + """Dictionary with the material symbols inside the primitive + assigned to :class:`collada.scene.MaterialNode` defined in the + scene""" + self._primitives = geom.primitives + self.original = geom + """The original :class:`collada.geometry.Geometry` object this + is bound to""" + + def __len__(self): + """Returns the number of primitives in the bound geometry""" + return len(self._primitives) + + def primitives(self): + """Returns an iterator that iterates through the primitives in + the bound geometry. Each value returned will be of base type + :class:`collada.primitive.BoundPrimitive`""" + for p in self._primitives: + boundp = p.bind(self.matrix, self.materialnodebysymbol) + yield boundp + + def __str__(self): + return '' % (self.original.id, len(self)) + + def __repr__(self): + return str(self) diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/light.py b/data/miniconda3/lib/python3.13/site-packages/collada/light.py new file mode 100644 index 0000000000000000000000000000000000000000..2b73352628e3ffe46ea6b6a1cc8c2bf5b6e579f5 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/collada/light.py @@ -0,0 +1,557 @@ +#################################################################### +# # +# THIS FILE IS PART OF THE pycollada LIBRARY SOURCE CODE. # +# USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS # +# GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE # +# IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. # +# # +# THE pycollada SOURCE CODE IS (C) COPYRIGHT 2011 # +# by Jeff Terrace and contributors # +# # +#################################################################### + +"""Contains objects for representing lights.""" + +import numpy + +from collada.common import DaeObject, E, tag +from collada.common import DaeIncompleteError, DaeMalformedError, \ + DaeUnsupportedError +from collada.util import _correctValInNode + + +class Light(DaeObject): + """Base light class holding data from tags.""" + + @staticmethod + def load(collada, localscope, node): + tecnode = node.find(collada.tag('technique_common')) + if tecnode is None or len(tecnode) == 0: + raise DaeIncompleteError('Missing common technique in light') + lightnode = tecnode[0] + if lightnode.tag == collada.tag('directional'): + return DirectionalLight.load(collada, localscope, node) + elif lightnode.tag == collada.tag('point'): + return PointLight.load(collada, localscope, node) + elif lightnode.tag == collada.tag('ambient'): + return AmbientLight.load(collada, localscope, node) + elif lightnode.tag == collada.tag('spot'): + return SpotLight.load(collada, localscope, node) + else: + raise DaeUnsupportedError('Unrecognized light type: %s' % lightnode.tag) + + +class DirectionalLight(Light): + """Directional light as defined in COLLADA tag tag.""" + + def __init__(self, id, color, xmlnode=None): + """Create a new directional light. + + :param str id: + A unique string identifier for the light + :param tuple color: + Either a tuple of size 3 containing the RGB color value + of the light or a tuple of size 4 containing the RGBA + color value of the light + :param xmlnode: + If loaded from xml, the xml node + + """ + self.id = id + """The unique string identifier for the light""" + self.direction = numpy.array([0, 0, -1], dtype=numpy.float32) + # Not documenting this because it doesn't make sense to set the direction + # of an unbound light. The direction isn't set until binding in a scene. + self.color = color + """Either a tuple of size 3 containing the RGB color value + of the light or a tuple of size 4 containing the RGBA + color value of the light""" + if xmlnode is not None: + self.xmlnode = xmlnode + """ElementTree representation of the light.""" + else: + self.xmlnode = E.light( + E.technique_common( + E.directional( + E.color(' '.join(map(str, self.color))) + ) + ), id=self.id, name=self.id) + + def save(self): + """Saves the light's properties back to :attr:`xmlnode`""" + self.xmlnode.set('id', self.id) + self.xmlnode.set('name', self.id) + colornode = self.xmlnode.find(f"{tag('technique_common')}/{tag('directional')}/{tag('color')}") + colornode.text = ' '.join(map(str, self.color)) + + @staticmethod + def load(collada, localscope, node): + colornode = node.find(f"{collada.tag('technique_common')}/{collada.tag('directional')}/{collada.tag('color')}") + if colornode is None: + raise DaeIncompleteError('Missing color for directional light') + try: + color = tuple(float(v) for v in colornode.text.split()) + except ValueError: + raise DaeMalformedError('Corrupted color values in light definition') + return DirectionalLight(node.get('id'), color, xmlnode=node) + + def bind(self, matrix): + """Binds this light to a transform matrix. + + :param numpy.array matrix: + A 4x4 numpy float matrix + + :rtype: :class:`collada.light.BoundDirectionalLight` + + """ + return BoundDirectionalLight(self, matrix) + + def __str__(self): + return '' % (self.id,) + + def __repr__(self): + return str(self) + + +class AmbientLight(Light): + """Ambient light as defined in COLLADA tag .""" + + def __init__(self, id, color, xmlnode=None): + """Create a new ambient light. + + :param str id: + A unique string identifier for the light + :param tuple color: + Either a tuple of size 3 containing the RGB color value + of the light or a tuple of size 4 containing the RGBA + color value of the light + :param xmlnode: + If loaded from xml, the xml node + + """ + self.id = id + """The unique string identifier for the light""" + self.color = color + """Either a tuple of size 3 containing the RGB color value + of the light or a tuple of size 4 containing the RGBA + color value of the light""" + if xmlnode is not None: + self.xmlnode = xmlnode + """ElementTree representation of the light.""" + else: + self.xmlnode = E.light( + E.technique_common( + E.ambient( + E.color(' '.join(map(str, self.color))) + ) + ), id=self.id, name=self.id) + + def save(self): + """Saves the light's properties back to :attr:`xmlnode`""" + self.xmlnode.set('id', self.id) + self.xmlnode.set('name', self.id) + colornode = self.xmlnode.find(f"{tag('technique_common')}/{tag('ambient')}/{tag('color')}") + colornode.text = ' '.join(map(str, self.color)) + + @staticmethod + def load(collada, localscope, node): + colornode = node.find(f"{collada.tag('technique_common')}/{collada.tag('ambient')}/{collada.tag('color')}") + if colornode is None: + raise DaeIncompleteError('Missing color for ambient light') + try: + color = tuple(float(v) for v in colornode.text.split()) + except ValueError: + raise DaeMalformedError('Corrupted color values in light definition') + return AmbientLight(node.get('id'), color, xmlnode=node) + + def bind(self, matrix): + """Binds this light to a transform matrix. + + :param numpy.array matrix: + A 4x4 numpy float matrix + + :rtype: :class:`collada.light.BoundAmbientLight` + + """ + return BoundAmbientLight(self, matrix) + + def __str__(self): + return '' % (self.id,) + + def __repr__(self): + return str(self) + + +class PointLight(Light): + """Point light as defined in COLLADA tag .""" + + def __init__(self, id, color, constant_att=None, linear_att=None, + quad_att=None, zfar=None, xmlnode=None): + """Create a new sun light. + + :param str id: + A unique string identifier for the light + :param tuple color: + Either a tuple of size 3 containing the RGB color value + of the light or a tuple of size 4 containing the RGBA + color value of the light + :param float constant_att: + Constant attenuation factor + :param float linear_att: + Linear attenuation factor + :param float quad_att: + Quadratic attenuation factor + :param float zfar: + Distance to the far clipping plane + :param xmlnode: + If loaded from xml, the xml node + + """ + self.id = id + """The unique string identifier for the light""" + self.position = numpy.array([0, 0, 0], dtype=numpy.float32) + # Not documenting this because it doesn't make sense to set the position + # of an unbound light. The position isn't set until binding in a scene. + self.color = color + """Either a tuple of size 3 containing the RGB color value + of the light or a tuple of size 4 containing the RGBA + color value of the light""" + self.constant_att = constant_att + """Constant attenuation factor.""" + self.linear_att = linear_att + """Linear attenuation factor.""" + self.quad_att = quad_att + """Quadratic attenuation factor.""" + self.zfar = zfar + """Distance to the far clipping plane""" + + if xmlnode is not None: + self.xmlnode = xmlnode + """ElementTree representation of the light.""" + else: + pnode = E.point( + E.color(' '.join(map(str, self.color))) + ) + if self.constant_att is not None: + pnode.append(E.constant_attenuation(str(self.constant_att))) + if self.linear_att is not None: + pnode.append(E.linear_attenuation(str(self.linear_att))) + if self.quad_att is not None: + pnode.append(E.quadratic_attenuation(str(self.quad_att))) + if self.zfar is not None: + pnode.append(E.zfar(str(self.zvar))) + + self.xmlnode = E.light( + E.technique_common(pnode), id=self.id, name=self.id) + + def save(self): + """Saves the light's properties back to :attr:`xmlnode`""" + self.xmlnode.set('id', self.id) + self.xmlnode.set('name', self.id) + pnode = self.xmlnode.find(f"{tag('technique_common')}/{tag('point')}") + colornode = pnode.find(tag('color')) + colornode.text = ' '.join(map(str, self.color)) + _correctValInNode(pnode, 'constant_attenuation', self.constant_att) + _correctValInNode(pnode, 'linear_attenuation', self.linear_att) + _correctValInNode(pnode, 'quadratic_attenuation', self.quad_att) + _correctValInNode(pnode, 'zfar', self.zfar) + + @staticmethod + def load(collada, localscope, node): + pnode = node.find(f"{collada.tag('technique_common')}/{collada.tag('point')}") + colornode = pnode.find(collada.tag('color')) + if colornode is None: + raise DaeIncompleteError('Missing color for point light') + try: + color = tuple(float(v) for v in colornode.text.split()) + except ValueError: + raise DaeMalformedError('Corrupted color values in light definition') + constant_att = linear_att = quad_att = zfar = None + qattnode = pnode.find(collada.tag('quadratic_attenuation')) + cattnode = pnode.find(collada.tag('constant_attenuation')) + lattnode = pnode.find(collada.tag('linear_attenuation')) + zfarnode = pnode.find(collada.tag('zfar')) + try: + if cattnode is not None: + constant_att = float(cattnode.text) + if lattnode is not None: + linear_att = float(lattnode.text) + if qattnode is not None: + quad_att = float(qattnode.text) + if zfarnode is not None: + zfar = float(zfarnode.text) + except ValueError: + raise DaeMalformedError('Corrupted values in light definition') + return PointLight(node.get('id'), color, constant_att, linear_att, + quad_att, zfar, xmlnode=node) + + def bind(self, matrix): + """Binds this light to a transform matrix. + + :param numpy.array matrix: + A 4x4 numpy float matrix + + :rtype: :class:`collada.light.BoundPointLight` + + """ + return BoundPointLight(self, matrix) + + def __str__(self): + return '' % (self.id,) + + def __repr__(self): + return str(self) + + +class SpotLight(Light): + """Spot light as defined in COLLADA tag .""" + + def __init__(self, id, color, constant_att=None, linear_att=None, + quad_att=None, falloff_ang=None, falloff_exp=None, xmlnode=None): + """Create a new spot light. + + :param str id: + A unique string identifier for the light + :param tuple color: + Either a tuple of size 3 containing the RGB color value + of the light or a tuple of size 4 containing the RGBA + color value of the light + :param float constant_att: + Constant attenuation factor + :param float linear_att: + Linear attenuation factor + :param float quad_att: + Quadratic attenuation factor + :param float falloff_ang: + Falloff angle + :param float falloff_exp: + Falloff exponent + :param xmlnode: + If loaded from xml, the xml node + + """ + self.id = id + """The unique string identifier for the light""" + self.color = color + """Either a tuple of size 3 containing the RGB color value + of the light or a tuple of size 4 containing the RGBA + color value of the light""" + self.constant_att = constant_att + """Constant attenuation factor.""" + self.linear_att = linear_att + """Linear attenuation factor.""" + self.quad_att = quad_att + """Quadratic attenuation factor.""" + self.falloff_ang = falloff_ang + """Falloff angle""" + self.falloff_exp = falloff_exp + """Falloff exponent""" + + if xmlnode is not None: + self.xmlnode = xmlnode + """ElementTree representation of the light.""" + else: + pnode = E.spot( + E.color(' '.join(map(str, self.color))), + ) + if self.constant_att is not None: + pnode.append(E.constant_attenuation(str(self.constant_att))) + if self.linear_att is not None: + pnode.append(E.linear_attenuation(str(self.linear_att))) + if self.quad_att is not None: + pnode.append(E.quadratic_attenuation(str(self.quad_att))) + if self.falloff_ang is not None: + pnode.append(E.falloff_angle(str(self.falloff_ang))) + if self.falloff_exp is not None: + pnode.append(E.falloff_exponent(str(self.falloff_exp))) + + self.xmlnode = E.light( + E.technique_common(pnode), id=self.id, name=self.id) + + def save(self): + """Saves the light's properties back to :attr:`xmlnode`""" + self.xmlnode.set('id', self.id) + self.xmlnode.set('name', self.id) + pnode = self.xmlnode.find(f"{tag('technique_common')}/{tag('spot')}") + colornode = pnode.find(tag('color')) + colornode.text = ' '.join(map(str, self.color)) + _correctValInNode(pnode, 'constant_attenuation', self.constant_att) + _correctValInNode(pnode, 'linear_attenuation', self.linear_att) + _correctValInNode(pnode, 'quadratic_attenuation', self.quad_att) + _correctValInNode(pnode, 'falloff_angle', self.falloff_ang) + _correctValInNode(pnode, 'falloff_exponent', self.falloff_exp) + + @staticmethod + def load(collada, localscope, node): + pnode = node.find(f"{collada.tag('technique_common')}/{collada.tag('spot')}") + colornode = pnode.find(collada.tag('color')) + if colornode is None: + raise DaeIncompleteError('Missing color for spot light') + try: + color = tuple(float(v) for v in colornode.text.split()) + except ValueError: + raise DaeMalformedError('Corrupted color values in spot light definition') + constant_att = linear_att = quad_att = falloff_ang = falloff_exp = None + cattnode = pnode.find(collada.tag('constant_attenuation')) + lattnode = pnode.find(collada.tag('linear_attenuation')) + qattnode = pnode.find(collada.tag('quadratic_attenuation')) + fangnode = pnode.find(collada.tag('falloff_angle')) + fexpnode = pnode.find(collada.tag('falloff_exponent')) + try: + if cattnode is not None: + constant_att = float(cattnode.text) + if lattnode is not None: + linear_att = float(lattnode.text) + if qattnode is not None: + quad_att = float(qattnode.text) + if fangnode is not None: + falloff_ang = float(fangnode.text) + if fexpnode is not None: + falloff_exp = float(fexpnode.text) + except ValueError: + raise DaeMalformedError('Corrupted values in spot light definition') + return SpotLight(node.get('id'), color, constant_att, linear_att, + quad_att, falloff_ang, falloff_exp, xmlnode=node) + + def bind(self, matrix): + """Binds this light to a transform matrix. + + :param numpy.array matrix: + A 4x4 numpy float matrix + + :rtype: :class:`collada.light.BoundSpotLight` + + """ + return BoundSpotLight(self, matrix) + + def __str__(self): + return '' % (self.id,) + + def __repr__(self): + return str(self) + + +class BoundLight(object): + """Base class for bound lights""" + + +class BoundPointLight(BoundLight): + """Point light bound to a scene with transformation. This gets created when a + light is instantiated in a scene. Do not create this manually.""" + + def __init__(self, plight, matrix): + self.position = numpy.dot(matrix[:3, :3], plight.position) + matrix[:3, 3] + """Numpy array of length 3 representing the position of the light in the scene""" + self.color = plight.color + """Either a tuple of size 3 containing the RGB color value + of the light or a tuple of size 4 containing the RGBA + color value of the light""" + self.constant_att = plight.constant_att + if self.constant_att is None: + self.constant_att = 1.0 + """Constant attenuation factor.""" + self.linear_att = plight.linear_att + if self.linear_att is None: + self.linear_att = 0.0 + """Linear attenuation factor.""" + self.quad_att = plight.quad_att + if self.quad_att is None: + self.quad_att = 0.0 + """Quadratic attenuation factor.""" + self.zfar = plight.zfar + """Distance to the far clipping plane""" + self.original = plight + """The original :class:`collada.light.PointLight` this is bound to""" + + def __str__(self): + return '' % str(self.original.id) + + def __repr__(self): + return str(self) + + +class BoundSpotLight(BoundLight): + """Spot light bound to a scene with transformation. This gets created when a + light is instantiated in a scene. Do not create this manually.""" + + def __init__(self, slight, matrix): + self.position = matrix[:3, 3] + """Numpy array of length 3 representing the position of the light in the scene""" + self.direction = -matrix[:3, 2] + """Direction of the spot light""" + self.up = matrix[:3, 1] + """Up vector of the spot light""" + self.matrix = matrix + """Transform matrix for the bound light""" + self.color = slight.color + """Either a tuple of size 3 containing the RGB color value + of the light or a tuple of size 4 containing the RGBA + color value of the light""" + self.constant_att = slight.constant_att + if self.constant_att is None: + self.constant_att = 1.0 + """Constant attenuation factor.""" + self.linear_att = slight.linear_att + if self.linear_att is None: + self.linear_att = 0.0 + """Linear attenuation factor.""" + self.quad_att = slight.quad_att + if self.quad_att is None: + self.quad_att = 0.0 + """Quadratic attenuation factor.""" + self.falloff_ang = slight.falloff_ang + if self.falloff_ang is None: + self.falloff_ang = 180.0 + """Falloff angle""" + self.falloff_exp = slight.falloff_exp + if self.falloff_exp is None: + self.falloff_exp = 0.0 + """Falloff exponent""" + self.original = slight + """The original :class:`collada.light.SpotLight` this is bound to""" + + def __str__(self): + return '' % str(self.original.id) + + def __repr__(self): + return str(self) + + +class BoundDirectionalLight(BoundLight): + """Directional light bound to a scene with transformation. This gets created when a + light is instantiated in a scene. Do not create this manually.""" + + def __init__(self, dlight, matrix): + self.direction = numpy.dot(matrix[:3, :3], dlight.direction) + """Numpy array of length 3 representing the direction of the light in the scene""" + self.color = dlight.color + """Either a tuple of size 3 containing the RGB color value + of the light or a tuple of size 4 containing the RGBA + color value of the light""" + self.original = dlight + """The original :class:`collada.light.DirectionalLight` this is bound to""" + + def __str__(self): + return '' % str(self.original.id) + + def __repr__(self): + return str(self) + + +class BoundAmbientLight(BoundLight): + """Ambient light bound to a scene with transformation. This gets created when a + light is instantiated in a scene. Do not create this manually.""" + + def __init__(self, alight, matrix): + self.color = alight.color + """Either a tuple of size 3 containing the RGB color value + of the light or a tuple of size 4 containing the RGBA + color value of the light""" + self.original = alight + """The original :class:`collada.light.AmbientLight` this is bound to""" + + def __str__(self): + return '' % str(self.original.id) + + def __repr__(self): + return str(self) diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/lineset.py b/data/miniconda3/lib/python3.13/site-packages/collada/lineset.py new file mode 100644 index 0000000000000000000000000000000000000000..8405bd7e9360c9508e26fa0e8d65756daf174bb6 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/collada/lineset.py @@ -0,0 +1,266 @@ +#################################################################### +# # +# THIS FILE IS PART OF THE pycollada LIBRARY SOURCE CODE. # +# USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS # +# GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE # +# IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. # +# # +# THE pycollada SOURCE CODE IS (C) COPYRIGHT 2011 # +# by Jeff Terrace and contributors # +# # +#################################################################### + +"""Module containing classes and functions for the primitive.""" + +import numpy + +from collada import primitive +from collada.util import checkSource +from collada.common import E +from collada.common import DaeIncompleteError, DaeMalformedError + + +class Line(object): + """Single line representation. Represents the line between two points + ``(x0,y0,z0)`` and ``(x1,y1,z1)``. A Line is read-only.""" + + def __init__(self, indices, vertices, normals, texcoords, material): + """A Line should not be created manually.""" + + self.vertices = vertices + """A (2, 3) numpy float array containing the endpoints of the line""" + self.normals = normals + """A (2, 3) numpy float array with the normals for the endpoints of the line. Can be None.""" + self.texcoords = texcoords + """A tuple where entries are numpy float arrays of size (2, 2) containing + the texture coordinates for the endpoints of the line for each texture + coordinate set. Can be length 0 if there are no texture coordinates.""" + self.material = material + """If coming from an unbound :class:`collada.lineset.LineSet`, contains a + string with the material symbol. If coming from a bound + :class:`collada.lineset.BoundLineSet`, contains the actual + :class:`collada.material.Effect` the line is bound to.""" + self.indices = indices + + # Note: we can't generate normals for lines if there are none + + def __repr__(self): + return '' % (str(self.vertices[0]), str(self.vertices[1]), str(self.material)) + + def __str__(self): + return repr(self) + + +class LineSet(primitive.Primitive): + """Class containing the data COLLADA puts in a tag, a collection of + lines. The LineSet object is read-only. To modify a LineSet, create a new + instance using :meth:`collada.geometry.Geometry.createLineSet`. + + * If ``L`` is an instance of :class:`collada.lineset.LineSet`, then ``len(L)`` + returns the number of lines in the set. ``L[i]`` returns the i\\ :sup:`th` + line in the set.""" + + def __init__(self, sources, material, index, xmlnode=None): + """A LineSet should not be created manually. Instead, call the + :meth:`collada.geometry.Geometry.createLineSet` method after + creating a geometry instance. + """ + + if len(sources) == 0: + raise DaeIncompleteError('A line set needs at least one input for vertex positions') + if not sources.get('VERTEX'): + raise DaeIncompleteError('Line set requires vertex input') + + # find max offset + max_offset = max([max([input[0] for input in input_type_array]) + for input_type_array in sources.values() if len(input_type_array) > 0]) + + self.sources = sources + self.material = material + self.index = index + self.indices = self.index + self.nindices = max_offset + 1 + self.index.shape = (-1, 2, self.nindices) + self.nlines = len(self.index) + + if len(self.index) > 0: + self._vertex = sources['VERTEX'][0][4].data + self._vertex_index = self.index[:, :, sources['VERTEX'][0][0]] + self.maxvertexindex = numpy.max(self._vertex_index) + checkSource(sources['VERTEX'][0][4], ('X', 'Y', 'Z'), + self.maxvertexindex) + else: + self._vertex = None + self._vertex_index = None + self.maxvertexindex = -1 + + if 'NORMAL' in sources and len(sources['NORMAL']) > 0 \ + and len(self.index) > 0: + self._normal = sources['NORMAL'][0][4].data + self._normal_index = self.index[:, :, sources['NORMAL'][0][0]] + self.maxnormalindex = numpy.max(self._normal_index) + checkSource(sources['NORMAL'][0][4], ('X', 'Y', 'Z'), + self.maxnormalindex) + else: + self._normal = None + self._normal_index = None + self.maxnormalindex = -1 + + if 'TEXCOORD' in sources and len(sources['TEXCOORD']) > 0 \ + and len(self.index) > 0: + self._texcoordset = tuple([texinput[4].data + for texinput in sources['TEXCOORD']]) + self._texcoord_indexset = tuple([self.index[:, :, sources['TEXCOORD'][i][0]] + for i in range(len(sources['TEXCOORD']))]) + self.maxtexcoordsetindex = [numpy.max(tex_index) + for tex_index in self._texcoord_indexset] + for i, texinput in enumerate(sources['TEXCOORD']): + checkSource(texinput[4], ('S', 'T'), self.maxtexcoordsetindex[i]) + else: + self._texcoordset = tuple() + self._texcoord_indexset = tuple() + self.maxtexcoordsetindex = -1 + + if xmlnode is not None: + self.xmlnode = xmlnode + """ElementTree representation of the line set.""" + else: + self.index.shape = (-1) + txtindices = ' '.join(map(str, self.index.tolist())) + self.index.shape = (-1, 2, self.nindices) + + self.xmlnode = E.lines(count=str(self.nlines)) + if self.material is not None: + self.xmlnode.set('material', self.material) + + all_inputs = [] + for semantic_list in self.sources.values(): + all_inputs.extend(semantic_list) + for offset, semantic, sourceid, set, src in all_inputs: + inpnode = E.input(offset=str(offset), semantic=semantic, + source=sourceid) + if set is not None: + inpnode.set('set', str(set)) + self.xmlnode.append(inpnode) + + self.xmlnode.append(E.p(txtindices)) + + def __len__(self): + """The number of lines in this line set.""" + return len(self.index) + + def __getitem__(self, i): + v = self._vertex[self._vertex_index[i]] + if self._normal is None: + n = None + else: + n = self._normal[self._normal_index[i]] + uv = [] + for j, uvindex in enumerate(self._texcoord_indexset): + uv.append(self._texcoordset[j][uvindex[i]]) + return Line(self._vertex_index[i], v, n, uv, self.material) + + @staticmethod + def load(collada, localscope, node): + indexnode = node.find(collada.tag('p')) + input_tag = collada.tag('input') + if indexnode is None: + raise DaeIncompleteError('Missing index in line set') + + source_array = primitive.Primitive._getInputs(collada, localscope, node.findall(input_tag)) + + try: + if indexnode.text is None or indexnode.text.isspace(): + index = numpy.array([], dtype=numpy.int32) + else: + try: + index = numpy.fromstring(indexnode.text, dtype=numpy.int32, sep=' ') + except ValueError: + raise DaeMalformedError("Failed to parse lineset index integers") + index[numpy.isnan(index)] = 0 + except BaseException: + raise DaeMalformedError('Corrupted index in line set') + + lineset = LineSet(source_array, node.get('material'), index, node) + lineset.xmlnode = node + return lineset + + def bind(self, matrix, materialnodebysymbol): + """Create a bound line set from this line set, transform and material mapping""" + return BoundLineSet(self, matrix, materialnodebysymbol) + + def __str__(self): + return '' % len(self) + + def __repr__(self): + return str(self) + + +class BoundLineSet(primitive.BoundPrimitive): + """A line set bound to a transform matrix and materials mapping. + + * If ``bs`` is an instance of :class:`collada.lineset.BoundLineSet`, ``len(bs)`` + returns the number of lines in the set and ``bs[i]`` returns the i\\ :superscript:`th` + line in the set. + + """ + + def __init__(self, ls, matrix, materialnodebysymbol): + """Create a bound line set from a line set, transform and material mapping. This gets created when a + line set is instantiated in a scene. Do not create this manually.""" + M = numpy.asmatrix(matrix).transpose() + self._vertex = None + if ls._vertex is not None: + self._vertex = numpy.asarray(ls._vertex * M[:3, :3]) + matrix[:3, 3] + self._normal = None + if ls._normal is not None: + self._normal = numpy.asarray(ls._normal * M[:3, :3]) + self._texcoordset = ls._texcoordset + matnode = materialnodebysymbol.get(ls.material) + if matnode: + self.material = matnode.target + self.inputmap = dict([(sem, (input_sem, set)) + for sem, input_sem, set in matnode.inputs]) + else: + self.inputmap = self.material = None + self.index = ls.index + self._vertex_index = ls._vertex_index + self._normal_index = ls._normal_index + self._texcoord_indexset = ls._texcoord_indexset + self.nlines = ls.nlines + self.original = ls + + def __len__(self): + return len(self.index) + + def __getitem__(self, i): + v = self._vertex[self._vertex_index[i]] + if self._normal is None: + n = None + else: + n = self._normal[self._normal_index[i]] + uv = [] + for j, uvindex in enumerate(self._texcoord_indexset): + uv.append(self._texcoordset[j][uvindex[i]]) + return Line(self._vertex_index[i], v, n, uv, self.material) + + def lines(self): + """Iterate through all the lines contained in the set. + + :rtype: generator of :class:`collada.lineset.Line` + """ + for i in range(self.nlines): + yield self[i] + + def shapes(self): + """Iterate through all the lines contained in the set. + + :rtype: generator of :class:`collada.lineset.Line` + """ + return self.lines() + + def __str__(self): + return '' % len(self) + + def __repr__(self): + return str(self) diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/material.py b/data/miniconda3/lib/python3.13/site-packages/collada/material.py new file mode 100644 index 0000000000000000000000000000000000000000..8bb53e043866bdfb560f0ad71af654dbccd973d6 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/collada/material.py @@ -0,0 +1,913 @@ +#################################################################### +# # +# THIS FILE IS PART OF THE pycollada LIBRARY SOURCE CODE. # +# USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS # +# GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE # +# IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. # +# # +# THE pycollada SOURCE CODE IS (C) COPYRIGHT 2011 # +# by Jeff Terrace and contributors # +# # +#################################################################### + +"""Module for material, effect and image loading + +This module contains all the functionality to load and manage: +- Images in the image library +- Surfaces and samplers2D in effects +- Effects (that are now used as materials) + +""" + +import copy +import io +import numpy + +from collada.common import DaeObject, E, tag +from collada.common import DaeIncompleteError, DaeBrokenRefError, \ + DaeMalformedError, DaeUnsupportedError +from collada.util import falmostEqual + +try: + from PIL import Image as pil +except BaseException: + pil = None + +# internally used constant +_FAILED = 'failed' + + +class DaeMissingSampler2D(Exception): + """Raised when a tag references a texture without a sampler.""" + + +class CImage(DaeObject): + """Class containing data coming from a tag. + + Basically is just the path to the file, but we give an extended + functionality if PIL is available. You can in that case get the + image object or numpy arrays in both int and float format. We + named it CImage to avoid confusion with PIL's Image class. + + """ + + def __init__(self, id, path, collada=None, xmlnode=None): + """Create an image object. + + :param str id: + A unique string identifier for the image + :param str path: + Path relative to the collada document where the image is located + :param collada.Collada collada: + The collada object this image belongs to + :param xmlnode: + If loaded from xml, the node this data comes from + + """ + self.id = id + """The unique string identifier for the image""" + self.path = path + """Path relative to the collada document where the image is located""" + + self.collada = collada + self._data = None + self._pilimage = None + self._uintarray = None + self._floatarray = None + if xmlnode is not None: + self.xmlnode = xmlnode + """ElementTree representation of the image.""" + else: + self.xmlnode = E.image( + E.init_from(path), id=self.id, name=self.id) + + def getData(self): + if self._data is None: + try: + self._data = self.collada.getFileData(self.path) + except DaeBrokenRefError as ex: + self._data = '' + self.collada.handleError(ex) + return self._data + + def getImage(self): + if pil is None or self._pilimage is _FAILED: + return None + if self._pilimage: + return self._pilimage + else: + data = self.getData() + if not data: + self._pilimage = _FAILED + return None + try: + self._pilimage = pil.open(io.BytesIO(data)) + self._pilimage.load() + except IOError: + self._pilimage = _FAILED + return None + return self._pilimage + + def getUintArray(self): + if self._uintarray is _FAILED: + return None + if self._uintarray is not None: + return self._uintarray + img = self.getImage() + if not img: + self._uintarray = _FAILED + return None + nchan = len(img.mode) + self._uintarray = numpy.frombuffer(img.tobytes(), dtype=numpy.uint8) + self._uintarray.shape = (img.size[1], img.size[0], nchan) + return self._uintarray + + def getFloatArray(self): + if self._floatarray is _FAILED: + return None + if self._floatarray is not None: + return self._floatarray + array = self.getUintArray() + if array is None: + self._floatarray = _FAILED + return None + self._floatarray = numpy.asarray(array, dtype=numpy.float32) + self._floatarray *= 1.0 / 255.0 + return self._floatarray + + def setData(self, data): + self._data = data + self._floatarray = None + self._uintarray = None + self._pilimage = None + + data = property(getData, setData) + """Raw binary image file data if the file is readable. If `aux_file_loader` was passed to + :func:`collada.Collada.__init__`, this function will be called to retrieve the data. + Otherwise, if the file came from the local disk, the path will be interpreted from + the local file system. If the file was a zip archive, the archive will be searched.""" + pilimage = property(getImage) + """PIL Image object if PIL is available and the file is readable.""" + uintarray = property(getUintArray) + """Numpy array (height, width, nchannels) in integer format.""" + floatarray = property(getFloatArray) + """Numpy float array (height, width, nchannels) with the image data normalized to 1.0.""" + + @staticmethod + def load(collada, localspace, node): + id = node.get('id') + initnode = node.find(collada.tag('init_from')) + if initnode is None: + raise DaeIncompleteError('Image has no file path') + path = initnode.text + return CImage(id, path, collada, xmlnode=node) + + def save(self): + """Saves the image back to :attr:`xmlnode`. Only the :attr:`id` attribute is saved. + The image itself will have to be saved to its original source to make modifications.""" + self.xmlnode.set('id', self.id) + self.xmlnode.set('name', self.id) + initnode = self.xmlnode.find(tag('init_from')) + initnode.text = self.path + + def __str__(self): + return '' % (self.id, self.path) + + def __repr__(self): + return str(self) + + +class Surface(DaeObject): + """Class containing data coming from a tag. + + Collada materials use this to access to the tag. + The only extra information we store right now is the + image format. In theory, this enables many more features + according to the collada spec, but no one seems to actually + use them in the wild, so for now, it's unimplemented. + + """ + + def __init__(self, id, img, format=None, xmlnode=None): + """Creates a surface. + + :param str id: + A string identifier for the surface within the local scope of the material + :param collada.material.CImage img: + The image object + :param str format: + The format of the image + :param xmlnode: + If loaded from xml, the xml node + + """ + self.id = id + """The string identifier for the surface within the local scope of the material""" + self.image = img + """:class:`collada.material.CImage` object from the image library.""" + self.format = format if format is not None else "A8R8G8B8" + if xmlnode is not None: + self.xmlnode = xmlnode + """ElementTree representation of the surface.""" + else: + self.xmlnode = E.newparam( + E.surface( + E.init_from(self.image.id), + E.format(self.format), type="2D"), sid=self.id) + + @staticmethod + def load(collada, localscope, node): + surfacenode = node.find(collada.tag('surface')) + if surfacenode is None: + raise DaeIncompleteError('No surface found in newparam') + if surfacenode.get('type') != '2D': + raise DaeMalformedError('Hard to imagine a non-2D surface, isn\'t it?') + initnode = surfacenode.find(collada.tag('init_from')) + if initnode is None: + raise DaeIncompleteError('No init image found in surface') + formatnode = surfacenode.find(collada.tag('format')) + if formatnode is None: + format = None + else: + format = formatnode.text + imgid = initnode.text + id = node.get('sid') + if imgid in localscope: + img = localscope[imgid] + else: + img = collada.images.get(imgid) + if img is None: + raise DaeBrokenRefError("Missing image '%s' in surface '%s'" % (imgid, id)) + return Surface(id, img, format, xmlnode=node) + + def save(self): + """Saves the surface data back to :attr:`xmlnode`""" + surfacenode = self.xmlnode.find(tag('surface')) + initnode = surfacenode.find(tag('init_from')) + if self.format: + formatnode = surfacenode.find(tag('format')) + if formatnode is None: + surfacenode.append(E.format(self.format)) + else: + formatnode.text = self.format + initnode.text = self.image.id + self.xmlnode.set('sid', self.id) + + def __str__(self): + return '' % (self.id,) + + def __repr__(self): + return str(self) + + +class Sampler2D(DaeObject): + """Class containing data coming from tag in material. + + Collada uses the tag to map to a . The only + information we store about the sampler right now is minfilter and + magfilter. Theoretically, the collada spec has many more parameters + here, but no one seems to be using them in the wild, so they are + currently unimplemented. + + """ + + def __init__(self, id, surface, minfilter=None, magfilter=None, xmlnode=None): + """Create a Sampler2D object. + + :param str id: + A string identifier for the sampler within the local scope of the material + :param collada.material.Surface surface: + Surface instance that this object samples from + :param str minfilter: + Minification filter string id, see collada spec for details + :param str magfilter: + Maximization filter string id, see collada spec for details + :param xmlnode: + If loaded from xml, the xml node + + """ + self.id = id + """The string identifier for the sampler within the local scope of the material""" + self.surface = surface + """Surface instance that this object samples from""" + self.minfilter = minfilter + """Minification filter string id, see collada spec for details""" + self.magfilter = magfilter + """Maximization filter string id, see collada spec for details""" + if xmlnode is not None: + self.xmlnode = xmlnode + """ElementTree representation of the sampler.""" + else: + sampler_node = E.sampler2D(E.source(self.surface.id)) + if minfilter: + sampler_node.append(E.minfilter(self.minfilter)) + if magfilter: + sampler_node.append(E.magfilter(self.magfilter)) + + self.xmlnode = E.newparam(sampler_node, sid=self.id) + + @staticmethod + def load(collada, localscope, node): + samplernode = node.find(collada.tag('sampler2D')) + if samplernode is None: + raise DaeIncompleteError('No sampler found in newparam') + sourcenode = samplernode.find(collada.tag('source')) + if sourcenode is None: + raise DaeIncompleteError('No source found in sampler') + minnode = samplernode.find(collada.tag('minfilter')) + if minnode is None: + minfilter = None + else: + minfilter = minnode.text + magnode = samplernode.find(collada.tag('magfilter')) + if magnode is None: + magfilter = None + else: + magfilter = magnode.text + + surfaceid = sourcenode.text + id = node.get('sid') + surface = localscope.get(surfaceid) + if surface is None or not isinstance(surface, Surface): + raise DaeBrokenRefError('Missing surface ' + surfaceid) + return Sampler2D(id, surface, minfilter, magfilter, xmlnode=node) + + def save(self): + """Saves the sampler data back to :attr:`xmlnode`""" + samplernode = self.xmlnode.find(tag('sampler2D')) + sourcenode = samplernode.find(tag('source')) + if self.minfilter: + minnode = samplernode.find(tag('minfilter')) + minnode.text = self.minfilter + if self.magfilter: + maxnode = samplernode.find(tag('magfilter')) + maxnode.text = self.magfilter + sourcenode.text = self.surface.id + self.xmlnode.set('sid', self.id) + + def __str__(self): + return '' % (self.id,) + + def __repr__(self): + return str(self) + + +class Map(DaeObject): + """Class containing data coming from tag inside material. + + When a material defines its properties like `diffuse`, it can give you + a color or a texture. In the latter, the texture is mapped with a + sampler and a texture coordinate channel. If a material defined a texture + for one of its properties, you'll find an object of this class in the + corresponding attribute. + + """ + + def __init__(self, sampler, texcoord, xmlnode=None): + """Create a map instance to a sampler using a texcoord channel. + + :param collada.material.Sampler2D sampler: + A sampler object to map + :param str texcoord: + Texture coordinate channel symbol to use + :param xmlnode: + If loaded from xml, the xml node + + """ + self.sampler = sampler + """:class:`collada.material.Sampler2D` object to map""" + self.texcoord = texcoord + """Texture coordinate channel symbol to use""" + if xmlnode is not None: + self.xmlnode = xmlnode + """ElementTree representation of the map""" + else: + self.xmlnode = E.texture(texture=self.sampler.id, texcoord=self.texcoord) + + @staticmethod + def load(collada, localscope, node): + samplerid = node.get('texture') + texcoord = node.get('texcoord') + sampler = localscope.get(samplerid) + # Check for the sampler ID as the texture ID because some exporters suck + if sampler is None: + for s2d in localscope.values(): + if isinstance(s2d, Sampler2D): + if s2d.surface.image.id == samplerid: + sampler = s2d + if sampler is None or not isinstance(sampler, Sampler2D): + err = DaeMissingSampler2D('Missing sampler ' + samplerid + ' in node ' + node.tag) + err.samplerid = samplerid + raise err + return Map(sampler, texcoord, xmlnode=node) + + def save(self): + """Saves the map back to :attr:`xmlnode`""" + self.xmlnode.set('texture', self.sampler.id) + self.xmlnode.set('texcoord', self.texcoord) + + def __str__(self): + return '' % (self.sampler.id, self.texcoord) + + def __repr__(self): + return str(self) + + +class OPAQUE_MODE: + """The opaque mode of an effect.""" + A_ONE = 'A_ONE' + """Takes the transparency information from the color's alpha channel, where the value 1.0 is opaque (default).""" + RGB_ZERO = 'RGB_ZERO' + """Takes the transparency information from the color's red, green, and blue + channels, where the value 0.0 is opaque, with each channel modulated + independently.""" + + +class Effect(DaeObject): + """Class containing data coming from an tag. + """ + supported = ['emission', 'ambient', 'diffuse', 'specular', + 'shininess', 'reflective', 'reflectivity', + 'transparent', 'transparency', 'index_of_refraction'] + """Supported material properties list.""" + shaders = ['phong', 'lambert', 'blinn', 'constant'] + """Supported shader list.""" + + def __init__(self, id, params, shadingtype, bumpmap=None, double_sided=False, + emission=(0.0, 0.0, 0.0, 1.0), + ambient=(0.0, 0.0, 0.0, 1.0), + diffuse=(0.0, 0.0, 0.0, 1.0), + specular=(0.0, 0.0, 0.0, 1.0), + shininess=0.0, + reflective=(0.0, 0.0, 0.0, 1.0), + reflectivity=0.0, + transparent=(0.0, 0.0, 0.0, 1.0), + transparency=None, + index_of_refraction=None, + opaque_mode=None, + xmlnode=None): + """Create an effect instance out of properties. + + :param str id: + A string identifier for the effect + :param list params: + A list containing elements of type :class:`collada.material.Sampler2D` + and :class:`collada.material.Surface` + :param str shadingtype: + The type of shader to be used for this effect. Right now, we + only supper the shaders listed in :attr:`shaders` + :param `collada.material.Map` bumpmap: + The bump map for this effect, or None if there isn't one + :param bool double_sided: + Whether or not the material should be rendered double sided + :param emission: + Either an RGBA-format tuple of four floats or an instance + of :class:`collada.material.Map` + :param ambient: + Either an RGBA-format tuple of four floats or an instance + of :class:`collada.material.Map` + :param diffuse: + Either an RGBA-format tuple of four floats or an instance + of :class:`collada.material.Map` + :param specular: + Either an RGBA-format tuple of four floats or an instance + of :class:`collada.material.Map` + :param shininess: + Either a single float or an instance of :class:`collada.material.Map` + :param reflective: + Either an RGBA-format tuple of four floats or an instance + of :class:`collada.material.Map` + :param reflectivity: + Either a single float or an instance of :class:`collada.material.Map` + :param tuple transparent: + Either an RGBA-format tuple of four floats or an instance + of :class:`collada.material.Map` + :param transparency: + Either a single float or an instance of :class:`collada.material.Map` + :param float index_of_refraction: + A single float indicating the index of refraction for perfectly + refracted light + :param `collada.material.OPAQUE_MODE` opaque_mode: + The opaque mode for the effect. If not specified, defaults to A_ONE. + :param xmlnode: + If loaded from xml, the xml node + + """ + self.id = id + """The string identifier for the effect""" + self.params = params + """A list containing elements of type :class:`collada.material.Sampler2D` + and :class:`collada.material.Surface`""" + self.shadingtype = shadingtype + """String with the type of the shading.""" + self.bumpmap = bumpmap + """Either the bump map of the effect of type :class:`collada.material.Map` + or None if there is none.""" + self.double_sided = double_sided + """A boolean indicating whether or not the material should be rendered double sided""" + self.emission = emission + """Either an RGB-format tuple of three floats or an instance + of :class:`collada.material.Map`""" + self.ambient = ambient + """Either an RGB-format tuple of three floats or an instance + of :class:`collada.material.Map`""" + self.diffuse = diffuse + """Either an RGB-format tuple of three floats or an instance + of :class:`collada.material.Map`""" + self.specular = specular + """Either an RGB-format tuple of three floats or an instance + of :class:`collada.material.Map`""" + self.shininess = shininess + """Either a single float or an instance of :class:`collada.material.Map`""" + self.reflective = reflective + """Either an RGB-format tuple of three floats or an instance + of :class:`collada.material.Map`""" + self.reflectivity = reflectivity + """Either a single float or an instance of :class:`collada.material.Map`""" + self.transparent = transparent + """Either an RGB-format tuple of three floats or an instance + of :class:`collada.material.Map`""" + self.transparency = transparency + """Either a single float or an instance of :class:`collada.material.Map`""" + self.index_of_refraction = index_of_refraction + """A single float indicating the index of refraction for perfectly + refracted light""" + self.opaque_mode = OPAQUE_MODE.A_ONE if opaque_mode is None else opaque_mode + """The opaque mode for the effect. An instance of :class:`collada.material.OPAQUE_MODE`.""" + + if self.transparency is None: + if self.opaque_mode == OPAQUE_MODE.A_ONE: + self.transparency = 1.0 + else: + self.transparency = 0.0 + + self._fixColorValues() + + if xmlnode is not None: + self.xmlnode = xmlnode + """ElementTree representation of the effect""" + else: + shadnode = E(self.shadingtype) + + for prop in self.supported: + value = getattr(self, prop) + if value is None: + continue + propnode = E(prop) + if prop == 'transparent' and self.opaque_mode == OPAQUE_MODE.RGB_ZERO: + propnode.set('opaque', OPAQUE_MODE.RGB_ZERO) + shadnode.append(propnode) + if isinstance(value, Map): + propnode.append(value.xmlnode) + elif isinstance(value, float): + propnode.append(E.float(str(value))) + else: + propnode.append(E.color(' '.join(map(str, value)))) + + effect_nodes = [param.xmlnode for param in self.params] + effect_nodes.append(E.technique(shadnode, sid='common')) + self.xmlnode = E.effect( + E.profile_COMMON(*effect_nodes), id=self.id, name=self.id) + + @staticmethod + def getEffectParameters(collada, parentnode, localscope, params): + + for paramnode in parentnode.findall(collada.tag('newparam')): + if paramnode.find(collada.tag('surface')) is not None: + param = Surface.load(collada, localscope, paramnode) + params.append(param) + localscope[param.id] = param + elif paramnode.find(collada.tag('sampler2D')) is not None: + param = Sampler2D.load(collada, localscope, paramnode) + params.append(param) + localscope[param.id] = param + else: + # Try float variants in order + floatnode = None + for float_type in ('float', 'float2', 'float3', 'float4'): + floatnode = paramnode.find(collada.tag(float_type)) + if floatnode is not None: + break + paramid = paramnode.get('sid') + if floatnode is not None and paramid and len(paramid) > 0 and floatnode.text is not None: + localscope[paramid] = [float(v) for v in floatnode.text.split()] + + @staticmethod + def load(collada, localscope, node): + localscope = {} # we have our own scope, shadow it + params = [] + id = node.get('id') + profilenode = node.find(collada.tag('profile_COMMON')) + if profilenode is None: + raise DaeUnsupportedError('Found effect with profile other than profile_COMMON') + + # can be local to a material instead of global in + for imgnode in profilenode.findall(collada.tag('image')): + local_image = CImage.load(collada, localscope, imgnode) + localscope[local_image.id] = local_image + + global_image_id = local_image.id + uniquenum = 2 + while global_image_id in collada.images: + global_image_id = local_image.id + "-" + uniquenum + uniquenum += 1 + collada.images.append(local_image) + + Effect.getEffectParameters(collada, profilenode, localscope, params) + + tecnode = profilenode.find(collada.tag('technique')) + + Effect.getEffectParameters(collada, tecnode, localscope, params) + + shadnode = None + for shad in Effect.shaders: + shadnode = tecnode.find(collada.tag(shad)) + shadingtype = shad + if shadnode is not None: + break + if shadnode is None: + raise DaeIncompleteError('No material properties found in effect') + props = {} + for key in Effect.supported: + pnode = shadnode.find(collada.tag(key)) + if pnode is None: + props[key] = None + else: + try: + props[key] = Effect._loadShadingParam(collada, localscope, pnode) + except DaeMissingSampler2D as ex: + if ex.samplerid in collada.images: + # Whoever exported this collada file didn't include the proper references so we will create them + surf = Surface(ex.samplerid + '-surface', collada.images[ex.samplerid], 'A8R8G8B8') + sampler = Sampler2D(ex.samplerid, surf, None, None) + params.append(surf) + params.append(sampler) + localscope[surf.id] = surf + localscope[sampler.id] = sampler + try: + props[key] = Effect._loadShadingParam( + collada, localscope, pnode) + except DaeUnsupportedError as ex: + props[key] = None + collada.handleError(ex) + except DaeUnsupportedError as ex: + props[key] = None + collada.handleError(ex) # Give the chance to ignore error and load the rest + + if key == 'transparent' and key in props and props[key] is not None: + opaque_mode = pnode.get('opaque') + if opaque_mode is not None and opaque_mode == OPAQUE_MODE.RGB_ZERO: + props['opaque_mode'] = OPAQUE_MODE.RGB_ZERO + props['xmlnode'] = node + + bumpnode = node.find(f".//{collada.tag('extra')}//{collada.tag('texture')}") + if bumpnode is not None: + bumpmap = Map.load(collada, localscope, bumpnode) + else: + bumpmap = None + + double_sided_node = node.find(f".//{collada.tag('extra')}//{collada.tag('double_sided')}") + double_sided = False + if double_sided_node is not None and double_sided_node.text is not None: + try: + val = int(double_sided_node.text) + if val == 1: + double_sided = True + except ValueError: + pass + return Effect(id, params, shadingtype, bumpmap, double_sided, **props) + + @staticmethod + def _loadShadingParam(collada, localscope, node): + """Load from the node a definition for a material property.""" + children = list(node) + if not children: + raise DaeIncompleteError('Incorrect effect shading parameter ' + node.tag) + vnode = children[0] + if vnode.tag == collada.tag('color'): + try: + value = tuple(float(v) for v in vnode.text.split()) + except ValueError: + raise DaeMalformedError('Corrupted color definition in effect `{}`'.format(id)) + except IndexError: + raise DaeMalformedError('Corrupted color definition in effect `{}`'.format(id)) + elif vnode.tag == collada.tag('float'): + try: + value = float(vnode.text) + except ValueError: + raise DaeMalformedError('Corrupted float definition in effect ' + id) + elif vnode.tag == collada.tag('texture'): + value = Map.load(collada, localscope, vnode) + elif vnode.tag == collada.tag('param'): + refid = vnode.get('ref') + if refid is not None and refid in localscope: + value = localscope[refid] + else: + return None + else: + raise DaeUnsupportedError('Unknown shading param definition ' + + str(vnode.tag)) + return value + + def _fixColorValues(self): + for prop in self.supported: + propval = getattr(self, prop) + if isinstance(propval, tuple): + if len(propval) < 4: + propval = list(propval) + while len(propval) < 3: + propval.append(0.0) + while len(propval) < 4: + propval.append(1.0) + setattr(self, prop, tuple(propval)) + + def save(self): + """Saves the effect back to :attr:`xmlnode`""" + self.xmlnode.set('id', self.id) + self.xmlnode.set('name', self.id) + profilenode = self.xmlnode.find(tag('profile_COMMON')) + tecnode = profilenode.find(tag('technique')) + tecnode.set('sid', 'common') + + self._fixColorValues() + + for param in self.params: + param.save() + if param.xmlnode not in profilenode: + profilenode.insert(list(profilenode).index(tecnode), + param.xmlnode) + + deletenodes = [] + for oldparam in profilenode.findall(tag('newparam')): + if oldparam not in [param.xmlnode for param in self.params]: + deletenodes.append(oldparam) + for d in deletenodes: + profilenode.remove(d) + + for shader in self.shaders: + shadnode = tecnode.find(tag(shader)) + if shadnode is not None and shader != self.shadingtype: + tecnode.remove(shadnode) + + def getPropNode(prop, value): + propnode = E(prop) + if prop == 'transparent' and self.opaque_mode == OPAQUE_MODE.RGB_ZERO: + propnode.set('opaque', OPAQUE_MODE.RGB_ZERO) + if isinstance(value, Map): + propnode.append(copy.deepcopy(value.xmlnode)) + elif isinstance(value, float): + propnode.append(E.float(str(value))) + else: + propnode.append(E.color(' '.join(map(str, value)))) + return propnode + + shadnode = tecnode.find(tag(self.shadingtype)) + if shadnode is None: + shadnode = E(self.shadingtype) + for prop in self.supported: + value = getattr(self, prop) + if value is None: + continue + shadnode.append(getPropNode(prop, value)) + tecnode.append(shadnode) + else: + for prop in self.supported: + value = getattr(self, prop) + propnode = shadnode.find(tag(prop)) + if propnode is not None: + shadnode.remove(propnode) + if value is not None: + shadnode.append(getPropNode(prop, value)) + + double_sided_node = profilenode.find(f".//{tag('extra')}//{tag('double_sided')}") + if double_sided_node is None or double_sided_node.text is None: + extranode = profilenode.find(tag('extra')) + if extranode is None: + extranode = E.extra() + profilenode.append(extranode) + + teqnodes = extranode.findall(tag('technique')) + goognode = None + for teqnode in teqnodes: + if teqnode.get('profile') == 'GOOGLEEARTH': + goognode = teqnode + break + if goognode is None: + goognode = E.technique(profile='GOOGLEEARTH') + extranode.append(goognode) + double_sided_node = goognode.find(tag('double_sided')) + if double_sided_node is None: + double_sided_node = E.double_sided() + goognode.append(double_sided_node) + + double_sided_node.text = "1" if self.double_sided else "0" + + def __str__(self): + return '' % (self.id, self.shadingtype) + + def __repr__(self): + return str(self) + + def almostEqual(self, other): + """Checks if this effect is almost equal (within float precision) + to the given effect. + + :param collada.material.Effect other: + Effect to compare to + + :rtype: bool + + """ + if self.shadingtype != other.shadingtype: + return False + if self.double_sided != other.double_sided: + return False + for prop in self.supported: + thisprop = getattr(self, prop) + otherprop = getattr(other, prop) + if not isinstance(thisprop, type(otherprop)): + return False + elif isinstance(thisprop, float): + if not falmostEqual(thisprop, otherprop): + return False + elif isinstance(thisprop, Map): + if thisprop.sampler.surface.image.id != otherprop.sampler.surface.image.id or thisprop.texcoord != otherprop.texcoord: + return False + elif isinstance(thisprop, tuple): + if len(thisprop) != len(otherprop): + return False + for valthis, valother in zip(thisprop, otherprop): + if not falmostEqual(valthis, valother): + return False + return True + + +class Material(DaeObject): + """Class containing data coming from a tag. + + Right now, this just stores a reference to the effect + which is instantiated in the material. The effect instance + can have parameters, but this is rarely used in the wild, + so it is not yet implemented. + + """ + + def __init__(self, id, name, effect, xmlnode=None): + """Creates a material. + + :param str id: + A unique string identifier for the material + :param str name: + A name for the material + :param collada.material.Effect effect: + The effect instantiated in this material + :param xmlnode: + If loaded from xml, the xml node + + """ + + self.id = id + """The unique string identifier for the material""" + self.name = name + """The name for the material""" + self.effect = effect + """The :class:`collada.material.Effect` instantiated in this material""" + + if xmlnode is not None: + self.xmlnode = xmlnode + """ElementTree representation of the surface.""" + else: + self.xmlnode = E.material( + E.instance_effect(url="#%s" % self.effect.id), id=str(self.id), name=str(self.name)) + + @staticmethod + def load(collada, localscope, node): + matid = node.get('id') + matname = node.get('name') + + effnode = node.find(collada.tag('instance_effect')) + if effnode is None: + raise DaeIncompleteError('No effect inside material') + effectid = effnode.get('url') + + if not effectid.startswith('#'): + raise DaeMalformedError('Corrupted effect reference in material %s' % effectid) + + effect = collada.effects.get(effectid[1:]) + if not effect: + raise DaeBrokenRefError('Effect not found: ' + effectid) + + return Material(matid, matname, effect, xmlnode=node) + + def save(self): + """Saves the material data back to :attr:`xmlnode`""" + self.xmlnode.set('id', str(self.id)) + self.xmlnode.set('name', str(self.name)) + effnode = self.xmlnode.find(tag('instance_effect')) + effnode.set('url', '#%s' % self.effect.id) + + def __str__(self): + return '' % (self.id, self.effect.id) + + def __repr__(self): + return str(self) diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/polygons.py b/data/miniconda3/lib/python3.13/site-packages/collada/polygons.py new file mode 100644 index 0000000000000000000000000000000000000000..f36fb41691b939d2d7619c2fa763f62e5c4fafda --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/collada/polygons.py @@ -0,0 +1,118 @@ +#################################################################### +# # +# THIS FILE IS PART OF THE pycollada LIBRARY SOURCE CODE. # +# USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS # +# GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE # +# IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. # +# # +# THE pycollada SOURCE CODE IS (C) COPYRIGHT 2011 # +# by Jeff Terrace and contributors # +# # +#################################################################### + +"""Module containing classes and functions for the primitive.""" + +import numpy + +from collada import primitive +from collada import polylist +from collada.common import E +from collada.common import DaeIncompleteError, DaeMalformedError + + +class Polygons(polylist.Polylist): + """Class containing the data COLLADA puts in a tag, a collection of + polygons that can have holes. + + * The Polygons object is read-only. To modify a + Polygons, create a new instance using :meth:`collada.geometry.Geometry.createPolygons`. + + * Polygons with holes are not currently supported, so for right now, this class is + essentially the same as a :class:`collada.polylist.Polylist`. Use a polylist instead + if your polygons don't have holes. + """ + + def __init__(self, sources, material, polygons, xmlnode=None): + """A Polygons should not be created manually. Instead, call the + :meth:`collada.geometry.Geometry.createPolygons` method after + creating a geometry instance. + """ + + # find max offset - flatten and find max in one pass + max_offset = max(inp[0] for arr in sources.values() for inp in arr) + + vcounts = numpy.zeros(len(polygons), dtype=numpy.int32) + for i, poly in enumerate(polygons): + vcounts[i] = len(poly) / (max_offset + 1) + + if len(polygons) > 0: + indices = numpy.concatenate(polygons) + else: + indices = numpy.array([], dtype=numpy.int32) + + super(Polygons, self).__init__(sources, material, indices, vcounts, xmlnode) + + if xmlnode is not None: + self.xmlnode = xmlnode + else: + acclen = len(polygons) + + self.xmlnode = E.polygons(count=str(acclen)) + if self.material is not None: + self.xmlnode.set('material', self.material) + + all_inputs = [] + for semantic_list in self.sources.values(): + all_inputs.extend(semantic_list) + for offset, semantic, sourceid, set, src in all_inputs: + inpnode = E.input(offset=str(offset), semantic=semantic, source=sourceid) + if set is not None: + inpnode.set('set', str(set)) + self.xmlnode.append(inpnode) + + for poly in polygons: + self.xmlnode.append(E.p(' '.join(map(str, poly.flatten().tolist())))) + + @staticmethod + def load(collada, localscope, node): + indexnodes = node.findall(collada.tag('p')) + if indexnodes is None: + raise DaeIncompleteError('Missing indices in polygons') + + polygon_indices = [] + for indexnode in indexnodes: + try: + index = numpy.fromstring(indexnode.text, dtype=numpy.int32, sep=' ') + except ValueError: + raise DaeMalformedError("Failed to parse polygons index integers") + index[numpy.isnan(index)] = 0 + polygon_indices.append(index) + + all_inputs = primitive.Primitive._getInputs(collada, localscope, node.findall(collada.tag('input'))) + + polygons = Polygons(all_inputs, node.get('material'), polygon_indices, node) + return polygons + + def bind(self, matrix, materialnodebysymbol): + """Create a bound polygons from this polygons, transform and material mapping""" + return BoundPolygons(self, matrix, materialnodebysymbol) + + def __str__(self): + return '' % len(self) + + def __repr__(self): + return str(self) + + +class BoundPolygons(polylist.BoundPolylist): + """Polygons bound to a transform matrix and materials mapping.""" + + def __init__(self, pl, matrix, materialnodebysymbol): + """Create a BoundPolygons from a Polygons, transform and material mapping""" + super(BoundPolygons, self).__init__(pl, matrix, materialnodebysymbol) + + def __str__(self): + return '' % len(self) + + def __repr__(self): + return str(self) diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/polylist.py b/data/miniconda3/lib/python3.13/site-packages/collada/polylist.py new file mode 100644 index 0000000000000000000000000000000000000000..d1bee531a72ab0522a304403c74877279905b556 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/collada/polylist.py @@ -0,0 +1,401 @@ +#################################################################### +# # +# THIS FILE IS PART OF THE pycollada LIBRARY SOURCE CODE. # +# USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS # +# GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE # +# IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. # +# # +# THE pycollada SOURCE CODE IS (C) COPYRIGHT 2011 # +# by Jeff Terrace and contributors # +# # +#################################################################### + +"""Module containing classes and functions for the primitive.""" + +import numpy + +from collada import primitive +from collada import triangleset +from collada.common import E +from collada.common import DaeIncompleteError, DaeMalformedError +from collada.util import checkSource + + +class Polygon(object): + """Single polygon representation. Represents a polygon of N points.""" + + def __init__(self, indices, vertices, normal_indices, normals, texcoord_indices, texcoords, material): + """A Polygon should not be created manually.""" + + self.vertices = vertices + """A (N, 3) float array containing the points in the polygon.""" + self.normals = normals + """A (N, 3) float array with the normals for points in the polygon. Can be None.""" + self.texcoords = texcoords + """A tuple where entries are numpy float arrays of size (N, 2) containing + the texture coordinates for the points in the polygon for each texture + coordinate set. Can be length 0 if there are no texture coordinates.""" + self.material = material + """If coming from an unbound :class:`collada.polylist.Polylist`, contains a + string with the material symbol. If coming from a bound + :class:`collada.polylist.BoundPolylist`, contains the actual + :class:`collada.material.Effect` the line is bound to.""" + self.indices = indices + """A (N,) int array containing the indices for the vertices + of the N points in the polygon.""" + self.normal_indices = normal_indices + """A (N,) int array containing the indices for the normals of + the N points in the polygon""" + self.texcoord_indices = texcoord_indices + """A (N,2) int array with texture coordinate indexes for the + texcoords of the N points in the polygon""" + + def triangles(self): + """This triangulates the polygon using a simple fanning method. + + :rtype: generator of :class:`collada.polylist.Polygon` + """ + + npts = len(self.vertices) + + for i in range(npts - 2): + + tri_indices = numpy.array([ + self.indices[0], self.indices[i + 1], self.indices[i + 2] + ], dtype=numpy.float32) + + tri_vertices = numpy.array([ + self.vertices[0], self.vertices[i + 1], self.vertices[i + 2] + ], dtype=numpy.float32) + + if self.normals is None: + tri_normals = None + normal_indices = None + else: + tri_normals = numpy.array([ + self.normals[0], self.normals[i + 1], self.normals[i + 2] + ], dtype=numpy.float32) + normal_indices = numpy.array([ + self.normal_indices[0], + self.normal_indices[i + 1], + self.normal_indices[i + 2] + ], dtype=numpy.float32) + + tri_texcoords = [] + tri_texcoord_indices = [] + for texcoord, texcoord_indices in zip( + self.texcoords, self.texcoord_indices): + tri_texcoords.append(numpy.array([ + texcoord[0], + texcoord[i + 1], + texcoord[i + 2] + ], dtype=numpy.float32)) + tri_texcoord_indices.append(numpy.array([ + texcoord_indices[0], + texcoord_indices[i + 1], + texcoord_indices[i + 2] + ], dtype=numpy.float32)) + + tri = triangleset.Triangle( + tri_indices, tri_vertices, + normal_indices, tri_normals, + tri_texcoord_indices, tri_texcoords, + self.material) + yield tri + + def __repr__(self): + return '' % len(self.vertices) + + def __str__(self): + return repr(self) + + +class Polylist(primitive.Primitive): + """Class containing the data COLLADA puts in a tag, a collection of + polygons. The Polylist object is read-only. To modify a Polylist, create a new + instance using :meth:`collada.geometry.Geometry.createPolylist`. + + * If ``P`` is an instance of :class:`collada.polylist.Polylist`, then ``len(P)`` + returns the number of polygons in the set. ``P[i]`` returns the i\\ :sup:`th` + polygon in the set. + """ + + def __init__(self, sources, material, index, vcounts, xmlnode=None): + """A Polylist should not be created manually. Instead, call the + :meth:`collada.geometry.Geometry.createPolylist` method after + creating a geometry instance. + """ + + if len(sources) == 0: + raise DaeIncompleteError('A polylist set needs at least one input for vertex positions') + if 'VERTEX' not in sources: + raise DaeIncompleteError('Polylist requires vertex input') + + # find max offset - flatten and find max in one pass + max_offset = max([max([input[0] for input in input_type_array]) + for input_type_array in sources.values() if len(input_type_array) > 0]) + + self.material = material + self.index = index + self.indices = self.index + self.nindices = max_offset + 1 + self.vcounts = vcounts + self.sources = sources + self.index.shape = (-1, self.nindices) + self.npolygons = len(self.vcounts) + self.nvertices = numpy.sum(self.vcounts) if len(self.index) > 0 else 0 + self.polyends = numpy.cumsum(self.vcounts) + self.polystarts = self.polyends - self.vcounts + self.polyindex = numpy.dstack((self.polystarts, self.polyends))[0] + + if len(self.index) > 0: + self._vertex = sources['VERTEX'][0][4].data + self._vertex_index = self.index[:, sources['VERTEX'][0][0]] + self.maxvertexindex = numpy.max(self._vertex_index) + checkSource(sources['VERTEX'][0][4], ('X', 'Y', 'Z'), self.maxvertexindex) + else: + self._vertex = None + self._vertex_index = None + self.maxvertexindex = -1 + + if 'NORMAL' in sources and len(sources['NORMAL']) > 0 and len(self.index) > 0: + self._normal = sources['NORMAL'][0][4].data + self._normal_index = self.index[:, sources['NORMAL'][0][0]] + self.maxnormalindex = numpy.max(self._normal_index) + checkSource(sources['NORMAL'][0][4], ('X', 'Y', 'Z'), self.maxnormalindex) + else: + self._normal = None + self._normal_index = None + self.maxnormalindex = -1 + + if 'TEXCOORD' in sources and len(sources['TEXCOORD']) > 0 \ + and len(self.index) > 0: + self._texcoordset = tuple([texinput[4].data + for texinput in sources['TEXCOORD']]) + self._texcoord_indexset = tuple([self.index[:, sources['TEXCOORD'][i][0]] + for i in range(len(sources['TEXCOORD']))]) + self.maxtexcoordsetindex = [numpy.max(each) + for each in self._texcoord_indexset] + for i, texinput in enumerate(sources['TEXCOORD']): + checkSource(texinput[4], ('S', 'T'), self.maxtexcoordsetindex[i]) + else: + self._texcoordset = tuple() + self._texcoord_indexset = tuple() + self.maxtexcoordsetindex = -1 + + if xmlnode is not None: + self.xmlnode = xmlnode + """ElementTree representation of the line set.""" + else: + txtindices = ' '.join(map(str, self.indices.flatten().tolist())) + + self.xmlnode = E.polylist(count=str(self.npolygons)) + if self.material is not None: + self.xmlnode.set('material', self.material) + + all_inputs = [] + for semantic_list in self.sources.values(): + all_inputs.extend(semantic_list) + for offset, semantic, sourceid, set, src in all_inputs: + inpnode = E.input(offset=str(offset), semantic=semantic, + source=sourceid) + if set is not None: + inpnode.set('set', str(set)) + self.xmlnode.append(inpnode) + + vcountnode = E.vcount(' '.join(map(str, self.vcounts))) + self.xmlnode.append(vcountnode) + self.xmlnode.append(E.p(txtindices)) + + def __len__(self): + return self.npolygons + + def __getitem__(self, i): + polyrange = self.polyindex[i] + vertindex = self._vertex_index[polyrange[0]:polyrange[1]] + v = self._vertex[vertindex] + + normalindex = None + if self.normal is None: + n = None + else: + normalindex = self._normal_index[polyrange[0]:polyrange[1]] + n = self._normal[normalindex] + + uvindices = [] + uv = [] + for j, uvindex in enumerate(self._texcoord_indexset): + uvindices.append(uvindex[polyrange[0]:polyrange[1]]) + uv.append(self._texcoordset[j][uvindex[polyrange[0]:polyrange[1]]]) + + return Polygon(vertindex, v, normalindex, n, uvindices, uv, self.material) + + _triangleset = None + + def triangleset(self): + """This performs a simple triangulation of the polylist using the fanning method. + + :rtype: :class:`collada.triangleset.TriangleSet` + """ + + if self._triangleset is None: + indexselector = numpy.zeros(self.nvertices) == 0 + indexselector[self.polyindex[:, 1] - 1] = False + indexselector[self.polyindex[:, 1] - 2] = False + indexselector = numpy.arange(self.nvertices)[indexselector] + + firstpolyindex = numpy.arange(self.nvertices) + firstpolyindex = firstpolyindex - numpy.repeat(self.polyends - self.vcounts, self.vcounts) + firstpolyindex = firstpolyindex[indexselector] + + if len(self.index) > 0: + triindex = numpy.dstack((self.index[indexselector - firstpolyindex], + self.index[indexselector + 1], + self.index[indexselector + 2])) + triindex = numpy.swapaxes(triindex, 1, 2).flatten() + else: + triindex = numpy.array([], dtype=self.index.dtype) + + triset = triangleset.TriangleSet(self.sources, self.material, triindex, self.xmlnode) + + self._triangleset = triset + return self._triangleset + + @staticmethod + def load(collada, localscope, node): + indexnode = node.find(collada.tag('p')) + vcountnode = node.find(collada.tag('vcount')) + input_tag = collada.tag('input') + if indexnode is None: + raise DaeIncompleteError('Missing index in polylist') + if vcountnode is None: + raise DaeIncompleteError('Missing vcount in polylist') + + try: + if vcountnode.text is None or vcountnode.text.isspace(): + vcounts = numpy.array([], dtype=numpy.int32) + else: + try: + vcounts = numpy.fromstring(vcountnode.text, dtype=numpy.int32, sep=' ') + except ValueError: + raise DaeMalformedError("Failed to parse polylist vcount integers") + vcounts[numpy.isnan(vcounts)] = 0 + except ValueError: + raise DaeMalformedError('Corrupted vcounts in polylist') + + all_inputs = primitive.Primitive._getInputs(collada, localscope, node.findall(input_tag)) + + try: + if indexnode.text is None or indexnode.text.isspace(): + index = numpy.array([], dtype=numpy.int32) + else: + try: + index = numpy.fromstring(indexnode.text, dtype=numpy.int32, sep=' ') + except ValueError: + raise DaeMalformedError("Failed to parse poylist index integers") + index[numpy.isnan(index)] = 0 + except BaseException: + raise DaeMalformedError('Corrupted index in polylist') + + polylist = Polylist(all_inputs, node.get('material'), index, vcounts, node) + return polylist + + def bind(self, matrix, materialnodebysymbol): + """Create a bound polylist from this polylist, transform and material mapping""" + return BoundPolylist(self, matrix, materialnodebysymbol) + + def __str__(self): + return '' % len(self) + + def __repr__(self): + return str(self) + + +class BoundPolylist(primitive.BoundPrimitive): + """A polylist bound to a transform matrix and materials mapping. + + * If ``P`` is an instance of :class:`collada.polylist.BoundPolylist`, then ``len(P)`` + returns the number of polygons in the set. ``P[i]`` returns the i\\ :sup:`th` + polygon in the set. + """ + + def __init__(self, pl, matrix, materialnodebysymbol): + """Create a bound polylist from a polylist, transform and material mapping. + This gets created when a polylist is instantiated in a scene. Do not create this manually.""" + M = numpy.asmatrix(matrix).transpose() + self._vertex = None if pl._vertex is None else numpy.asarray(pl._vertex * M[:3, :3]) + matrix[:3, 3] + self._normal = None if pl._normal is None else numpy.asarray(pl._normal * M[:3, :3]) + self._texcoordset = pl._texcoordset + matnode = materialnodebysymbol.get(pl.material) + if matnode: + self.material = matnode.target + self.inputmap = dict([(sem, (input_sem, set)) for sem, input_sem, set in matnode.inputs]) + else: + self.inputmap = self.material = None + self.index = pl.index + self.nvertices = pl.nvertices + self._vertex_index = pl._vertex_index + self._normal_index = pl._normal_index + self._texcoord_indexset = pl._texcoord_indexset + self.polyindex = pl.polyindex + self.npolygons = pl.npolygons + self.matrix = matrix + self.materialnodebysymbol = materialnodebysymbol + self.original = pl + + def __len__(self): + return self.npolygons + + def __getitem__(self, i): + polyrange = self.polyindex[i] + vertindex = self._vertex_index[polyrange[0]:polyrange[1]] + v = self._vertex[vertindex] + + normalindex = None + if self.normal is None: + n = None + else: + normalindex = self._normal_index[polyrange[0]:polyrange[1]] + n = self._normal[normalindex] + + uvindices = [] + uv = [] + for j, uvindex in enumerate(self._texcoord_indexset): + uvindices.append(uvindex[polyrange[0]:polyrange[1]]) + uv.append(self._texcoordset[j][uvindex[polyrange[0]:polyrange[1]]]) + + return Polygon(vertindex, v, normalindex, n, uvindices, uv, self.material) + + _triangleset = None + + def triangleset(self): + """This performs a simple triangulation of the polylist using the fanning method. + + :rtype: :class:`collada.triangleset.BoundTriangleSet` + """ + if self._triangleset is None: + triset = self.original.triangleset() + boundtriset = triset.bind(self.matrix, self.materialnodebysymbol) + self._triangleset = boundtriset + return self._triangleset + + def polygons(self): + """Iterate through all the polygons contained in the set. + + :rtype: generator of :class:`collada.polylist.Polygon` + """ + for i in range(self.npolygons): + yield self[i] + + def shapes(self): + """Iterate through all the polygons contained in the set. + + :rtype: generator of :class:`collada.polylist.Polygon` + """ + return self.polygons() + + def __str__(self): + return '' % len(self) + + def __repr__(self): + return str(self) diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/primitive.py b/data/miniconda3/lib/python3.13/site-packages/collada/primitive.py new file mode 100644 index 0000000000000000000000000000000000000000..ca3e0bee2b1b050aa0aa0f12f2552432cd086d3c --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/collada/primitive.py @@ -0,0 +1,168 @@ +#################################################################### +# # +# THIS FILE IS PART OF THE pycollada LIBRARY SOURCE CODE. # +# USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS # +# GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE # +# IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. # +# # +# THE pycollada SOURCE CODE IS (C) COPYRIGHT 2011 # +# by Jeff Terrace and contributors # +# # +#################################################################### + +"""Module containing the base class for primitives""" + +from collada.common import DaeObject +from collada.common import DaeBrokenRefError, DaeMalformedError, \ + DaeUnsupportedError +from collada.source import InputList + + +class Primitive(DaeObject): + """Base class for all primitive sets like TriangleSet, LineSet, Polylist, etc.""" + + vertex = property(lambda s: s._vertex, doc="""Read-only numpy.array of size Nx3 where N is the number of vertex points in the + primitive's vertex source array.""") + normal = property(lambda s: s._normal, doc="""Read-only numpy.array of size Nx3 where N is the number of normal values in the + primitive's normal source array.""") + texcoordset = property(lambda s: s._texcoordset, doc="""Read-only tuple of texture coordinate arrays. Each value is a numpy.array of size + Nx2 where N is the number of texture coordinates in the primitive's source array.""") + textangentset = property(lambda s: s._textangentset, doc="""Read-only tuple of texture tangent arrays. Each value is a numpy.array of size + Nx3 where N is the number of texture tangents in the primitive's source array.""") + texbinormalset = property(lambda s: s._texbinormalset, doc="""Read-only tuple of texture binormal arrays. Each value is a numpy.array of size + Nx3 where N is the number of texture binormals in the primitive's source array.""") + + vertex_index = property(lambda s: s._vertex_index, doc="""Read-only numpy.array of size Nx3 where N is the number of vertices in the primitive. + To get the actual vertex points, one can use this array to select into the vertex + array, e.g. ``vertex[vertex_index]``.""") + normal_index = property(lambda s: s._normal_index, doc="""Read-only numpy.array of size Nx3 where N is the number of vertices in the primitive. + To get the actual normal values, one can use this array to select into the normals + array, e.g. ``normal[normal_index]``.""") + texcoord_indexset = property(lambda s: s._texcoord_indexset, doc="""Read-only tuple of texture coordinate index arrays. Each value is a numpy.array of size + Nx2 where N is the number of vertices in the primitive. To get the actual texture + coordinates, one can use the array to select into the texcoordset array, e.g. + ``texcoordset[0][texcoord_indexset[0]]`` would select the first set of texture + coordinates.""") + textangent_indexset = property(lambda s: s._textangent_indexset, doc="""Read-only tuple of texture tangent index arrays. Each value is a numpy.array of size + Nx3 where N is the number of vertices in the primitive. To get the actual texture + tangents, one can use the array to select into the textangentset array, e.g. + ``textangentset[0][textangent_indexset[0]]`` would select the first set of texture + tangents.""") + texbinormal_indexset = property(lambda s: s._texbinormal_indexset, doc="""Read-only tuple of texture binormal index arrays. Each value is a numpy.array of size + Nx3 where N is the number of vertices in the primitive. To get the actual texture + binormals, one can use the array to select into the texbinormalset array, e.g. + ``texbinormalset[0][texbinormal_indexset[0]]`` would select the first set of texture + binormals.""") + + def bind(self, matrix, materialnodebysymbol): + """Binds this primitive to a transform matrix and material mapping. + The primitive's points get transformed by the given matrix and its + inputs get mapped to the given materials. + + :param numpy.array matrix: + A 4x4 numpy float matrix + :param dict materialnodebysymbol: + A dictionary with the material symbols inside the primitive + assigned to :class:`collada.scene.MaterialNode` defined in the + scene + + :rtype: :class:`collada.primitive.Primitive` + + """ + + # Known semantic types for fast lookup + _KNOWN_SEMANTICS = frozenset([ + 'VERTEX', 'NORMAL', 'TEXCOORD', 'TEXTANGENT', + 'TEXBINORMAL', 'COLOR', 'TANGENT', 'BINORMAL']) + + @staticmethod + def _getInputsFromList(collada, localscope, inputs): + # Build result dict - only create lists as needed + all_inputs = {} + known_semantics = Primitive._KNOWN_SEMANTICS + + for input in inputs: + offset, semantic, source, set = input + source_key = source[1:] + vertex_source = localscope.get(source_key) + + # Handle VERTEX semantic referencing a dict of sources + if semantic == 'VERTEX' and isinstance(vertex_source, dict): + for inputsemantic, inputsource in vertex_source.items(): + actual_semantic = 'VERTEX' if inputsemantic == 'POSITION' else inputsemantic + actual_source = '#' + inputsource.id + input_tuple = (offset, actual_semantic, actual_source, set, inputsource) + if actual_semantic not in all_inputs: + all_inputs[actual_semantic] = [] + all_inputs[actual_semantic].append(input_tuple) + elif not isinstance(vertex_source, dict): + if len(source) < 2 or source[0] != '#': + raise DaeMalformedError('Incorrect source id "%s" in input' % source) + if source_key not in localscope: + raise DaeBrokenRefError('Source input id "%s" not found' % source) + input_tuple = (offset, semantic, source, set, localscope[source_key]) + if semantic in known_semantics: + if semantic not in all_inputs: + all_inputs[semantic] = [] + all_inputs[semantic].append(input_tuple) + else: + collada.handleError(DaeUnsupportedError('Unknown input semantic: %s' % semantic)) + if semantic not in all_inputs: + all_inputs[semantic] = [] + all_inputs[semantic].append(input_tuple) + + return all_inputs + + @staticmethod + def _getInputs(collada, localscope, inputnodes): + try: + inputs = [(int(i.get('offset')), i.get('semantic'), + i.get('source'), i.get('set')) + for i in inputnodes] + except ValueError: + raise DaeMalformedError('Corrupted offsets in primitive') + + return Primitive._getInputsFromList(collada, localscope, inputs) + + def getInputList(self): + """Gets a :class:`collada.source.InputList` representing the inputs from a primitive""" + inpl = InputList() + for (key, tupes) in self.sources.items(): + for (offset, semantic, source, set, srcobj) in tupes: + inpl.addInput(offset, semantic, source, set) + return inpl + + def save(self): + return NotImplementedError("Primitives are read-only") + + +class BoundPrimitive(object): + """A :class:`collada.primitive.Primitive` bound to a transform matrix + and material mapping.""" + + def shapes(self): + """Iterate through the items in this primitive. The shape returned + depends on the primitive type. Examples: Triangle, Polygon.""" + + vertex = property(lambda s: s._vertex, doc="""Read-only numpy.array of size Nx3 where N is the number of vertex points in the + primitive's vertex source array. The values will be transformed according to the + bound transformation matrix.""") + normal = property(lambda s: s._normal, doc="""Read-only numpy.array of size Nx3 where N is the number of normal values in the + primitive's normal source array. The values will be transformed according to the + bound transformation matrix.""") + texcoordset = property(lambda s: s._texcoordset, doc="""Read-only tuple of texture coordinate arrays. Each value is a numpy.array of size + Nx2 where N is the number of texture coordinates in the primitive's source array. The + values will be transformed according to the bound transformation matrix.""") + vertex_index = property(lambda s: s._vertex_index, doc="""Read-only numpy.array of size Nx3 where N is the number of vertices in the primitive. + To get the actual vertex points, one can use this array to select into the vertex + array, e.g. ``vertex[vertex_index]``. The values will be transformed according to the + bound transformation matrix.""") + normal_index = property(lambda s: s._normal_index, doc="""Read-only numpy.array of size Nx3 where N is the number of vertices in the primitive. + To get the actual normal values, one can use this array to select into the normals + array, e.g. ``normal[normal_index]``. The values will be transformed according to the + bound transformation matrix.""") + texcoord_indexset = property(lambda s: s._texcoord_indexset, doc="""Read-only tuple of texture coordinate index arrays. Each value is a numpy.array of size + Nx2 where N is the number of vertices in the primitive. To get the actual texture + coordinates, one can use the array to select into the texcoordset array, e.g. + ``texcoordset[0][texcoord_indexset[0]]`` would select the first set of texture + coordinates. The values will be transformed according to the bound transformation matrix.""") diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/scene.py b/data/miniconda3/lib/python3.13/site-packages/collada/scene.py new file mode 100644 index 0000000000000000000000000000000000000000..6fce8e4da9cf7c6749c34b4e807ab0719a5230b8 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/collada/scene.py @@ -0,0 +1,1058 @@ +#################################################################### +# # +# THIS FILE IS PART OF THE pycollada LIBRARY SOURCE CODE. # +# USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS # +# GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE # +# IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. # +# # +# THE pycollada SOURCE CODE IS (C) COPYRIGHT 2011 # +# by Jeff Terrace and contributors # +# # +#################################################################### + +"""This module contains several classes related to the scene graph. + +Supported scene nodes are: + * which is loaded as a Node + * which is loaded as a CameraNode + * which is loaded as a LightNode + * which is loaded as a MaterialNode + * which is loaded as a GeometryNode + * which is loaded as a ControllerNode + * which is loaded as a Scene + +""" + +import collada +import numpy + +from collada.common import DaeBrokenRefError +from collada.common import DaeError +from collada.common import DaeMalformedError +from collada.common import DaeObject +from collada.common import DaeUnsupportedError +from collada.common import E +from collada.common import tag +from collada.util import toUnitVec +from collada.xmlutil import etree as ElementTree + +# Pre-allocated identity matrix for reuse (read-only, never modify directly) +_IDENTITY_MATRIX = numpy.identity(4, dtype=numpy.float32) +_IDENTITY_MATRIX.flags.writeable = False + + +class DaeInstanceNotLoadedError(Exception): + """Raised when an instance_node refers to a node that isn't loaded yet. Will always be caught""" + + def __init__(self, msg): + super(DaeInstanceNotLoadedError, self).__init__() + self.msg = msg + + +class SceneNode(DaeObject): + """Abstract base class for all nodes within a scene.""" + + def objects(self, tipo, matrix=None): + """Iterate through all objects under this node that match `tipo`. + The objects will be bound and transformed via the scene transformations. + + :param str tipo: + A string for the desired object type. This can be one of 'geometry', + 'camera', 'light', or 'controller'. + :param numpy.array matrix: + An optional transformation matrix + + :rtype: generator that yields the type specified + + """ + + +def makeRotationMatrix(x, y, z, angle): + """Build and return a transform 4x4 matrix to rotate `angle` radians + around (`x`,`y`,`z`) axis.""" + c = numpy.cos(angle) + s = numpy.sin(angle) + t = (1 - c) + return numpy.array([[t * x * x + c, t * x * y - s * z, t * x * z + s * y, 0], + [t * x * y + s * z, t * y * y + c, t * y * z - s * x, 0], + [t * x * z - s * y, t * y * z + s * x, t * z * z + c, 0], + [0, 0, 0, 1]], + dtype=numpy.float32) + + +class Transform(DaeObject): + """Base class for all transformation types""" + + def save(self): + pass + + +class TranslateTransform(Transform): + """Contains a translation transformation as defined in the collada tag.""" + + def __init__(self, x, y, z, xmlnode=None): + """Creates a translation transformation + + :param float x: + x coordinate + :param float y: + y coordinate + :param float z: + z coordinate + :param xmlnode: + When loaded, the xmlnode it comes from + + """ + self.x = x + """x coordinate""" + self.y = y + """y coordinate""" + self.z = z + """z coordinate""" + self.matrix = numpy.identity(4, dtype=numpy.float32) + """The resulting transformation matrix. This will be a numpy.array of size 4x4.""" + self.matrix[:3, 3] = [x, y, z] + self.xmlnode = xmlnode + """ElementTree representation of the transform.""" + if xmlnode is None: + self.xmlnode = E.translate(' '.join([str(x), str(y), str(z)])) + + @staticmethod + def load(collada, node): + try: + floats = numpy.fromstring(node.text, dtype=numpy.float32, sep=' ') + except ValueError: + raise DaeMalformedError("Failed to parse translate transform floats") + if len(floats) != 3: + raise DaeMalformedError("Translate node requires three float values") + return TranslateTransform(floats[0], floats[1], floats[2], node) + + def __str__(self): + return '' % (self.x, self.y, self.z) + + def __repr__(self): + return str(self) + + +class RotateTransform(Transform): + """Contains a rotation transformation as defined in the collada tag.""" + + def __init__(self, x, y, z, angle, xmlnode=None): + """Creates a rotation transformation + + :param float x: + x coordinate + :param float y: + y coordinate + :param float z: + z coordinate + :param float angle: + angle of rotation, in degrees + :param xmlnode: + When loaded, the xmlnode it comes from + + """ + self.x = x + """x coordinate""" + self.y = y + """y coordinate""" + self.z = z + """z coordinate""" + self.angle = angle + """angle of rotation, in degrees""" + self.matrix = makeRotationMatrix(x, y, z, angle * numpy.pi / 180.0) + """The resulting transformation matrix. This will be a numpy.array of size 4x4.""" + self.xmlnode = xmlnode + """ElementTree representation of the transform.""" + if xmlnode is None: + self.xmlnode = E.rotate(' '.join([str(x), str(y), str(z), str(angle)])) + + @staticmethod + def load(collada, node): + try: + floats = numpy.fromstring(node.text, dtype=numpy.float32, sep=' ') + except ValueError: + raise DaeMalformedError("Failed to parse rotate transform floats") + if len(floats) != 4: + raise DaeMalformedError("Rotate node requires four float values") + return RotateTransform(floats[0], floats[1], floats[2], floats[3], node) + + def __str__(self): + return '' % (self.x, self.y, self.z, self.angle) + + def __repr__(self): + return str(self) + + +class ScaleTransform(Transform): + """Contains a scale transformation as defined in the collada tag.""" + + def __init__(self, x, y, z, xmlnode=None): + """Creates a scale transformation + + :param float x: + x coordinate + :param float y: + y coordinate + :param float z: + z coordinate + :param xmlnode: + When loaded, the xmlnode it comes from + + """ + self.x = x + """x coordinate""" + self.y = y + """y coordinate""" + self.z = z + """z coordinate""" + self.matrix = numpy.identity(4, dtype=numpy.float32) + """The resulting transformation matrix. This will be a numpy.array of size 4x4.""" + self.matrix[0, 0] = x + self.matrix[1, 1] = y + self.matrix[2, 2] = z + self.xmlnode = xmlnode + """ElementTree representation of the transform.""" + if xmlnode is None: + self.xmlnode = E.scale(' '.join([str(x), str(y), str(z)])) + + @staticmethod + def load(collada, node): + try: + floats = numpy.fromstring(node.text, dtype=numpy.float32, sep=' ') + except ValueError: + raise DaeMalformedError("Failed to parse scale transform floats") + if len(floats) != 3: + raise DaeMalformedError("Scale node requires three float values") + return ScaleTransform(floats[0], floats[1], floats[2], node) + + def __str__(self): + return '' % (self.x, self.y, self.z) + + def __repr__(self): + return str(self) + + +class MatrixTransform(Transform): + """Contains a matrix transformation as defined in the collada tag.""" + + def __init__(self, matrix, xmlnode=None): + """Creates a matrix transformation + + :param numpy.array matrix: + This should be an unshaped numpy array of floats of length 16 + :param xmlnode: + When loaded, the xmlnode it comes from + + """ + self.matrix = matrix + """The resulting transformation matrix. This will be a numpy.array of size 4x4.""" + if len(self.matrix) != 16: + raise DaeMalformedError('Corrupted matrix transformation node') + self.matrix.shape = (4, 4) + self.xmlnode = xmlnode + """ElementTree representation of the transform.""" + if xmlnode is None: + self.xmlnode = E.matrix(' '.join(map(str, self.matrix.flat))) + + @staticmethod + def load(collada, node): + try: + floats = numpy.fromstring(node.text, dtype=numpy.float32, sep=' ') + except ValueError: + raise DaeMalformedError("Failed to parse matrix transform floats") + return MatrixTransform(floats, node) + + def __str__(self): + return '' + + def __repr__(self): + return str(self) + + +class LookAtTransform(Transform): + """Contains a transformation for aiming a camera as defined in the collada tag.""" + + def __init__(self, eye, interest, upvector, xmlnode=None): + """Creates a lookat transformation + + :param numpy.array eye: + An unshaped numpy array of floats of length 3 containing the position of the eye + :param numpy.array interest: + An unshaped numpy array of floats of length 3 containing the point of interest + :param numpy.array upvector: + An unshaped numpy array of floats of length 3 containing the up-axis direction + :param xmlnode: + When loaded, the xmlnode it comes from + + """ + self.eye = eye + """A numpy array of length 3 containing the position of the eye""" + self.interest = interest + """A numpy array of length 3 containing the point of interest""" + self.upvector = upvector + """A numpy array of length 3 containing the up-axis direction""" + + if len(eye) != 3 or len(interest) != 3 or len(upvector) != 3: + raise DaeMalformedError('Corrupted lookat transformation node') + + self.matrix = numpy.identity(4, dtype=numpy.float32) + """The resulting transformation matrix. This will be a numpy.array of size 4x4.""" + + front = toUnitVec(numpy.subtract(eye, interest)) + side = numpy.multiply(-1, toUnitVec(numpy.cross(front, upvector))) + self.matrix[0, 0:3] = side + self.matrix[1, 0:3] = upvector + self.matrix[2, 0:3] = front + self.matrix[3, 0:3] = eye + + self.xmlnode = xmlnode + """ElementTree representation of the transform.""" + if xmlnode is None: + self.xmlnode = E.lookat(' '.join(map(str, + numpy.concatenate((self.eye, self.interest, self.upvector))))) + + @staticmethod + def load(collada, node): + try: + floats = numpy.fromstring(node.text, dtype=numpy.float32, sep=' ') + except ValueError: + raise DaeMalformedError("Failed to parse lookat transform floats") + if len(floats) != 9: + raise DaeMalformedError("Lookat node requires 9 float values") + return LookAtTransform(floats[0:3], floats[3:6], floats[6:9], node) + + def __str__(self): + return '' + + def __repr__(self): + return str(self) + + +class Node(SceneNode): + """Represents a node object, which is a point on the scene graph, as defined in the collada tag. + + Contains the list of transformations effecting the node as well as any children. + """ + + def __init__(self, id, children=None, transforms=None, xmlnode=None, name=None): + """Create a node in the scene graph. + + :param str id: + A unique string identifier for the node + :param list children: + A list of child nodes of this node. This can contain any + object that inherits from :class:`collada.scene.SceneNode` + :param list transforms: + A list of transformations effecting the node. This can + contain any object that inherits from :class:`collada.scene.Transform` + :param xmlnode: + When loaded, the xmlnode it comes from + :param name: + If given, sets the node name property, if missing (None) then then + node name property is set from the id value (if not None) + + """ + self.id = id + """The unique string identifier for the node""" + self.name = id if name is None else name + """The optional string node name (not required to be unique)for the node, by default set to the id value""" + self.children = [] + """A list of child nodes of this node. This can contain any + object that inherits from :class:`collada.scene.SceneNode`""" + if children is not None: + self.children = children + self.transforms = [] + if transforms is not None: + self.transforms = transforms + """A list of transformations effecting the node. This can + contain any object that inherits from :class:`collada.scene.Transform`""" + + # Use cached identity matrix when no transforms, otherwise compute the combined matrix + if len(self.transforms) == 0: + self.matrix = _IDENTITY_MATRIX + elif len(self.transforms) == 1: + self.matrix = self.transforms[0].matrix.copy() + else: + self.matrix = numpy.identity(4, dtype=numpy.float32) + for t in self.transforms: + self.matrix = numpy.dot(self.matrix, t.matrix) + """A numpy.array of size 4x4 containing a transformation matrix that + combines all the transformations in :attr:`transforms`. This will only + be updated after calling :meth:`save`.""" + + if xmlnode is not None: + self.xmlnode = xmlnode + """ElementTree representation of the transform.""" + else: + self.xmlnode = E.node(id=self.id, name=self.name) + for t in self.transforms: + self.xmlnode.append(t.xmlnode) + for c in self.children: + self.xmlnode.append(c.xmlnode) + + def objects(self, tipo, matrix=None): + """Iterate through all objects under this node that match `tipo`. + The objects will be bound and transformed via the scene transformations. + + :param str tipo: + A string for the desired object type. This can be one of 'geometry', + 'camera', 'light', or 'controller'. + :param numpy.array matrix: + An optional transformation matrix + + :rtype: generator that yields the type specified + + """ + if matrix is not None: + M = numpy.dot(matrix, self.matrix) + else: + M = self.matrix + for node in self.children: + for obj in node.objects(tipo, M): + yield obj + + def save(self): + """Saves the geometry back to :attr:`xmlnode`. Also updates + :attr:`matrix` if :attr:`transforms` has been modified.""" + if len(self.transforms) == 0: + self.matrix = _IDENTITY_MATRIX + else: + self.matrix = numpy.identity(4, dtype=numpy.float32) + for t in self.transforms: + self.matrix = numpy.dot(self.matrix, t.matrix) + + for child in self.children: + child.save() + + if self.id is not None: + self.xmlnode.set('id', self.id) + if self.name is not None: + self.xmlnode.set('name', self.name) + + for t in self.transforms: + if t.xmlnode not in self.xmlnode: + self.xmlnode.append(t.xmlnode) + for c in self.children: + if c.xmlnode not in self.xmlnode: + self.xmlnode.append(c.xmlnode) + xmlnodes = [c.xmlnode for c in self.children] + xmlnodes.extend([t.xmlnode for t in self.transforms]) + for n in self.xmlnode: + if n not in xmlnodes: + self.xmlnode.remove(n) + + @staticmethod + def load(collada, node, localscope): + id = node.get('id') + name = node.get('name') + children = [] + transforms = [] + + dispatch = getattr(collada, '_node_dispatch', None) + if dispatch is None: + dispatch = _build_node_dispatch(collada) + + for subnode in node: + entry = dispatch.get(subnode.tag) + if entry is None: + collada.handleError(DaeUnsupportedError('Unknown scene node %s' % str(subnode.tag))) + continue + + load_type, loader_class, is_transform = entry + if load_type == 'none': + continue + + try: + if load_type == 'node': + n = loader_class.load(collada, subnode, localscope) + else: + n = loader_class.load(collada, subnode) + + if n is not None: + if is_transform: + transforms.append(n) + else: + children.append(n) + except DaeError as ex: + collada.handleError(ex) + + return Node(id, children, transforms, xmlnode=node, name=name) + + def __str__(self): + return '' % (len(self.transforms), len(self.children)) + + def __repr__(self): + return str(self) + + +class NodeNode(Node): + """Represents a node being instantiated in a scene, as defined in the collada tag.""" + + def __init__(self, node, xmlnode=None): + """Creates a node node + + :param collada.scene.Node node: + A node to instantiate in the scene + :param xmlnode: + When loaded, the xmlnode it comes from + + """ + self.node = node + """An object of type :class:`collada.scene.Node` representing the node to bind in the scene""" + + if xmlnode is not None: + self.xmlnode = xmlnode + """ElementTree representation of the node node.""" + else: + self.xmlnode = E.instance_node(url="#%s" % self.node.id) + + def objects(self, tipo, matrix=None): + for obj in self.node.objects(tipo, matrix): + yield obj + + id = property(lambda s: s.node.id) + children = property(lambda s: s.node.children) + matrix = property(lambda s: s.node.matrix) + + @staticmethod + def load(collada, node, localscope): + url = node.get('url') + if not url.startswith('#'): + raise DaeMalformedError('Invalid url in node instance %s' % url) + referred_node = localscope.get(url[1:]) + if not referred_node: + referred_node = collada.nodes.get(url[1:]) + if not referred_node: + raise DaeInstanceNotLoadedError('Node %s not found in library' % url) + return NodeNode(referred_node, xmlnode=node) + + def save(self): + """Saves the node node back to :attr:`xmlnode`""" + self.xmlnode.set('url', "#%s" % self.node.id) + + def __str__(self): + return '' % (self.node.id,) + + def __repr__(self): + return str(self) + + +class GeometryNode(SceneNode): + """Represents a geometry instance in a scene, as defined in the collada tag.""" + + def __init__(self, geometry, materials=None, xmlnode=None): + """Creates a geometry node + + :param collada.geometry.Geometry geometry: + A geometry to instantiate in the scene + :param list materials: + A list containing items of type :class:`collada.scene.MaterialNode`. + Each of these represents a material that the geometry should be + bound to. + :param xmlnode: + When loaded, the xmlnode it comes from + + """ + self.geometry = geometry + """An object of type :class:`collada.geometry.Geometry` representing the + geometry to bind in the scene""" + self.materials = [] + """A list containing items of type :class:`collada.scene.MaterialNode`. + Each of these represents a material that the geometry is bound to.""" + if materials is not None: + self.materials = materials + if xmlnode is not None: + self.xmlnode = xmlnode + """ElementTree representation of the geometry node.""" + else: + self.xmlnode = E.instance_geometry(url="#%s" % self.geometry.id) + if len(self.materials) > 0: + self.xmlnode.append(E.bind_material( + E.technique_common( + *[mat.xmlnode for mat in self.materials] + ) + )) + + def objects(self, tipo, matrix=None): + """Yields a :class:`collada.geometry.BoundGeometry` if ``tipo=='geometry'``""" + if tipo == 'geometry': + if matrix is None: + matrix = _IDENTITY_MATRIX + materialnodesbysymbol = {mat.symbol: mat for mat in self.materials} + yield self.geometry.bind(matrix, materialnodesbysymbol) + + @staticmethod + def load(collada, node): + url = node.get('url') + if not url.startswith('#'): + raise DaeMalformedError('Invalid url in geometry instance %s' % url) + geometry = collada.geometries.get(url[1:]) + if not geometry: + raise DaeBrokenRefError('Geometry %s not found in library' % url) + # Use cached xpath or build and cache it + mat_xpath = getattr(collada, '_geomnode_mat_xpath', None) + if mat_xpath is None: + mat_xpath = f"{collada.tag('bind_material')}/{collada.tag('technique_common')}/{collada.tag('instance_material')}" + collada._geomnode_mat_xpath = mat_xpath + matnodes = node.findall(mat_xpath) + materials = [MaterialNode.load(collada, matnode) for matnode in matnodes] + return GeometryNode(geometry, materials, xmlnode=node) + + def save(self): + """Saves the geometry node back to :attr:`xmlnode`""" + self.xmlnode.set('url', "#%s" % self.geometry.id) + + for m in self.materials: + m.save() + + matparent = self.xmlnode.find(f"{tag('bind_material')}/{tag('technique_common')}") + if matparent is None and len(self.materials) == 0: + return + elif matparent is None: + matparent = E.technique_common() + self.xmlnode.append(E.bind_material(matparent)) + elif len(self.materials) == 0 and matparent is not None: + bindnode = self.xmlnode.find('%s' % tag('bind_material')) + self.xmlnode.remove(bindnode) + return + + for m in self.materials: + if m.xmlnode not in matparent: + matparent.append(m.xmlnode) + xmlnodes = [m.xmlnode for m in self.materials] + for n in matparent: + if n not in xmlnodes: + matparent.remove(n) + + def __str__(self): + return '' % (self.geometry.id,) + + def __repr__(self): + return str(self) + + +class ControllerNode(SceneNode): + """Represents a controller instance in a scene, as defined in the collada tag. **This class is highly + experimental. More support will be added in version 0.4.**""" + + def __init__(self, controller, materials, xmlnode=None): + """Creates a controller node + + :param collada.controller.Controller controller: + A controller to instantiate in the scene + :param list materials: + A list containing items of type :class:`collada.scene.MaterialNode`. + Each of these represents a material that the controller should be + bound to. + :param xmlnode: + When loaded, the xmlnode it comes from + + """ + self.controller = controller + """ An object of type :class:`collada.controller.Controller` representing + the controller being instantiated in the scene""" + self.materials = materials + """A list containing items of type :class:`collada.scene.MaterialNode`. + Each of these represents a material that the controller is bound to.""" + if xmlnode is not None: + self.xmlnode = xmlnode + """ElementTree representation of the controller node.""" + else: + self.xmlnode = ElementTree.Element(collada.tag('instance_controller')) + bindnode = ElementTree.Element(collada.tag('bind_material')) + technode = ElementTree.Element(collada.tag('technique_common')) + bindnode.append(technode) + self.xmlnode.append(bindnode) + for mat in materials: + technode.append(mat.xmlnode) + + def objects(self, tipo, matrix=None): + """Yields a :class:`collada.controller.BoundController` if ``tipo=='controller'``""" + if tipo == 'controller': + if matrix is None: + matrix = _IDENTITY_MATRIX + materialnodesbysymbol = {mat.symbol: mat for mat in self.materials} + yield self.controller.bind(matrix, materialnodesbysymbol) + + @staticmethod + def load(collada, node): + url = node.get('url') + if not url.startswith('#'): + raise DaeMalformedError('Invalid url in controller instance %s' % url) + controller = collada.controllers.get(url[1:]) + if not controller: + raise DaeBrokenRefError('Controller %s not found in library' % url) + # Use cached xpath (same as GeometryNode) or build and cache it + mat_xpath = getattr(collada, '_geomnode_mat_xpath', None) + if mat_xpath is None: + mat_xpath = f"{collada.tag('bind_material')}/{collada.tag('technique_common')}/{collada.tag('instance_material')}" + collada._geomnode_mat_xpath = mat_xpath + matnodes = node.findall(mat_xpath) + materials = [MaterialNode.load(collada, matnode) for matnode in matnodes] + return ControllerNode(controller, materials, xmlnode=node) + + def save(self): + """Saves the controller node back to :attr:`xmlnode`""" + self.xmlnode.set('url', '#' + self.controller.id) + for mat in self.materials: + mat.save() + + def __str__(self): + return '' % (self.controller.id,) + + def __repr__(self): + return str(self) + + +class MaterialNode(SceneNode): + """Represents a material being instantiated in a scene, as defined in the collada tag.""" + + def __init__(self, symbol, target, inputs, xmlnode=None): + """Creates a material node + + :param str symbol: + The symbol within a geometry this material should be bound to + :param collada.material.Material target: + The material object being bound to + :param list inputs: + A list of tuples of the form ``(semantic, input_semantic, set)`` mapping + texcoords or other inputs to material input channels, e.g. + ``('TEX0', 'TEXCOORD', '0')`` would map the effect parameter ``'TEX0'`` + to the ``'TEXCOORD'`` semantic of the geometry, using texture coordinate + set ``0``. + :param xmlnode: + When loaded, the xmlnode it comes from + + """ + self.symbol = symbol + """The symbol within a geometry this material should be bound to""" + self.target = target + """An object of type :class:`collada.material.Material` representing the material object being bound to""" + self.inputs = inputs + """A list of tuples of the form ``(semantic, input_semantic, set)`` mapping + texcoords or other inputs to material input channels, e.g. + ``('TEX0', 'TEXCOORD', '0')`` would map the effect parameter ``'TEX0'`` + to the ``'TEXCOORD'`` semantic of the geometry, using texture coordinate + set ``0``.""" + if xmlnode is not None: + self.xmlnode = xmlnode + """ElementTree representation of the material node.""" + else: + self.xmlnode = E.instance_material( + *[E.bind_vertex_input(semantic=sem, input_semantic=input_sem, input_set=set) + for sem, input_sem, set in self.inputs], **{'symbol': self.symbol, 'target': "#%s" % self.target.id}) + + @staticmethod + def load(collada, node): + inputs = [] + for inputnode in node.findall(collada.tag('bind_vertex_input')): + inputs.append((inputnode.get('semantic'), inputnode.get('input_semantic'), inputnode.get('input_set'))) + targetid = node.get('target') + if not targetid.startswith('#'): + raise DaeMalformedError('Incorrect target id in material ' + targetid) + target = collada.materials.get(targetid[1:]) + if not target: + raise DaeBrokenRefError('Material %s not found' % targetid) + return MaterialNode(node.get('symbol'), target, inputs, xmlnode=node) + + def objects(self): + pass + + def save(self): + """Saves the material node back to :attr:`xmlnode`""" + self.xmlnode.set('symbol', self.symbol) + self.xmlnode.set('target', "#%s" % self.target.id) + + inputs_in = [] + for i in self.xmlnode.findall(tag('bind_vertex_input')): + input_tuple = (i.get('semantic'), i.get('input_semantic'), i.get('input_set')) + if input_tuple not in self.inputs: + self.xmlnode.remove(i) + else: + inputs_in.append(input_tuple) + for i in self.inputs: + if i not in inputs_in: + self.xmlnode.append(E.bind_vertex_input(semantic=i[0], input_semantic=i[1], input_set=i[2])) + + def __str__(self): + return '' % (self.symbol, self.target.id) + + def __repr__(self): + return str(self) + + +class CameraNode(SceneNode): + """Represents a camera being instantiated in a scene, as defined in the collada tag.""" + + def __init__(self, camera, xmlnode=None): + """Create a camera instance + + :param collada.camera.Camera camera: + The camera being instantiated + :param xmlnode: + When loaded, the xmlnode it comes from + + """ + self.camera = camera + """An object of type :class:`collada.camera.Camera` representing the instantiated camera""" + if xmlnode is not None: + self.xmlnode = xmlnode + """ElementTree representation of the camera node.""" + else: + self.xmlnode = E.instance_camera(url="#%s" % camera.id) + + def objects(self, tipo, matrix=None): + """Yields a :class:`collada.camera.BoundCamera` if ``tipo=='camera'``""" + if tipo == 'camera': + if matrix is None: + matrix = _IDENTITY_MATRIX + yield self.camera.bind(matrix) + + @staticmethod + def load(collada, node): + url = node.get('url') + if not url.startswith('#'): + raise DaeMalformedError('Invalid url in camera instance %s' % url) + camera = collada.cameras.get(url[1:]) + if not camera: + raise DaeBrokenRefError('Camera %s not found in library' % url) + return CameraNode(camera, xmlnode=node) + + def save(self): + """Saves the camera node back to :attr:`xmlnode`""" + self.xmlnode.set('url', '#' + self.camera.id) + + def __str__(self): + return '' % (self.camera.id,) + + def __repr__(self): + return str(self) + + +class LightNode(SceneNode): + """Represents a light being instantiated in a scene, as defined in the collada tag.""" + + def __init__(self, light, xmlnode=None): + """Create a light instance + + :param collada.light.Light light: + The light being instantiated + :param xmlnode: + When loaded, the xmlnode it comes from + + """ + self.light = light + """An object of type :class:`collada.light.Light` representing the instantiated light""" + if xmlnode is not None: + self.xmlnode = xmlnode + """ElementTree representation of the light node.""" + else: + self.xmlnode = E.instance_light(url="#%s" % light.id) + + def objects(self, tipo, matrix=None): + """Yields a :class:`collada.light.BoundLight` if ``tipo=='light'``""" + if tipo == 'light': + if matrix is None: + matrix = _IDENTITY_MATRIX + yield self.light.bind(matrix) + + @staticmethod + def load(collada, node): + url = node.get('url') + if not url.startswith('#'): + raise DaeMalformedError('Invalid url in light instance %s' % url) + light = collada.lights.get(url[1:]) + if not light: + raise DaeBrokenRefError('Light %s not found in library' % url) + return LightNode(light, xmlnode=node) + + def save(self): + """Saves the light node back to :attr:`xmlnode`""" + self.xmlnode.set('url', '#' + self.light.id) + + def __str__(self): + return '' % (self.light.id,) + + def __repr__(self): + return str(self) + + +class ExtraNode(SceneNode): + """Represents extra information in a scene, as defined in a collada tag.""" + + def __init__(self, xmlnode): + """Create an extra node which stores arbitrary xml + + :param xmlnode: + Should be an ElementTree instance of tag type + + """ + if xmlnode is not None: + self.xmlnode = xmlnode + """ElementTree representation of the extra node.""" + else: + self.xmlnode = E.extra() + + def objects(self, tipo, matrix=None): + if tipo == 'extra': + for e in self.xmlnode.findall(tag(tipo)): + yield e + + @staticmethod + def load(collada, node): + return ExtraNode(node) + + def save(self): + pass + + +def _build_node_dispatch(collada): + """Build the node dispatch table and cache it on the collada object.""" + dispatch = { + collada.tag('node'): ('node', Node, False), + collada.tag('translate'): ('simple', TranslateTransform, True), + collada.tag('rotate'): ('simple', RotateTransform, True), + collada.tag('scale'): ('simple', ScaleTransform, True), + collada.tag('matrix'): ('simple', MatrixTransform, True), + collada.tag('lookat'): ('simple', LookAtTransform, True), + collada.tag('instance_geometry'): ('simple', GeometryNode, False), + collada.tag('instance_camera'): ('simple', CameraNode, False), + collada.tag('instance_light'): ('simple', LightNode, False), + collada.tag('instance_controller'): ('simple', ControllerNode, False), + collada.tag('instance_node'): ('node', NodeNode, False), + collada.tag('extra'): ('simple', ExtraNode, False), + collada.tag('asset'): ('none', None, False), + } + collada._node_dispatch = dispatch + return dispatch + + +def loadNode(collada, node, localscope): + """Generic scene node loading from an xml `node` and a `collada` object. + + Knowing the supported nodes, create the appropriate class for the given node + and return it. + + """ + # Inline check, call builder only if needed + dispatch = getattr(collada, '_node_dispatch', None) + if dispatch is None: + dispatch = _build_node_dispatch(collada) + + entry = dispatch.get(node.tag) + if entry is None: + raise DaeUnsupportedError('Unknown scene node %s' % str(node.tag)) + load_type, loader_class, _ = entry + if load_type == 'node': + return loader_class.load(collada, node, localscope) + elif load_type == 'simple': + return loader_class.load(collada, node) + else: # 'none' + return None + + +class Scene(DaeObject): + """The root object for a scene, as defined in a collada tag""" + + def __init__(self, id, nodes, xmlnode=None, collada=None): + """Create a scene + + :param str id: + A unique string identifier for the scene + :param list nodes: + A list of type :class:`collada.scene.Node` representing the nodes in the scene + :param xmlnode: + When loaded, the xmlnode it comes from + :param collada: + The collada instance this is part of + + """ + self.id = id + """The unique string identifier for the scene""" + self.nodes = nodes + """A list of type :class:`collada.scene.Node` representing the nodes in the scene""" + self.collada = collada + """The collada instance this is part of""" + if xmlnode is not None: + self.xmlnode = xmlnode + """ElementTree representation of the scene node.""" + else: + self.xmlnode = E.visual_scene(id=self.id) + for node in nodes: + self.xmlnode.append(node.xmlnode) + + def objects(self, tipo): + """Iterate through all objects in the scene that match `tipo`. + The objects will be bound and transformed via the scene transformations. + + :param str tipo: + A string for the desired object type. This can be one of 'geometry', + 'camera', 'light', or 'controller'. + + :rtype: generator that yields the type specified + + """ + matrix = None + for node in self.nodes: + for obj in node.objects(tipo, matrix): + yield obj + + @staticmethod + def load(collada, node): + id = node.get('id') + nodes = [] + tried_loading = [] + succeeded = False + localscope = {} + for nodenode in node.findall(collada.tag('node')): + try: + N = loadNode(collada, nodenode, localscope) + except DaeInstanceNotLoadedError as ex: + tried_loading.append((nodenode, ex)) + except DaeError as ex: + collada.handleError(ex) + else: + if N is not None: + nodes.append(N) + if N.id and N.id not in localscope: + localscope[N.id] = N + succeeded = True + while len(tried_loading) > 0 and succeeded: + succeeded = False + next_tried = [] + for nodenode, ex in tried_loading: + try: + N = loadNode(collada, nodenode, localscope) + except DaeInstanceNotLoadedError as ex: + next_tried.append((nodenode, ex)) + except DaeError as ex: + collada.handleError(ex) + else: + if N is not None: + nodes.append(N) + succeeded = True + tried_loading = next_tried + if len(tried_loading) > 0: + for nodenode, ex in tried_loading: + raise DaeBrokenRefError(ex.msg) + + return Scene(id, nodes, xmlnode=node, collada=collada) + + def save(self): + """Saves the scene back to :attr:`xmlnode`""" + self.xmlnode.set('id', self.id) + for node in self.nodes: + node.save() + if node.xmlnode not in self.xmlnode: + self.xmlnode.append(node.xmlnode) + xmlnodes = [n.xmlnode for n in self.nodes] + for node in self.xmlnode: + if node not in xmlnodes: + self.xmlnode.remove(node) + + def __str__(self): + return '' % (self.id, len(self.nodes)) + + def __repr__(self): + return str(self) diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/schema.py b/data/miniconda3/lib/python3.13/site-packages/collada/schema.py new file mode 100644 index 0000000000000000000000000000000000000000..7ca10fcda8d416dfe8af6fb545d8c45890ffc508 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/collada/schema.py @@ -0,0 +1,68 @@ +# encoding:UTF-8 +#################################################################### +# # +# THIS FILE IS PART OF THE pycollada LIBRARY SOURCE CODE. # +# USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS # +# GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE # +# IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. # +# # +# THE pycollada SOURCE CODE IS (C) COPYRIGHT 2011 # +# by Jeff Terrace and contributors # +# # +#################################################################### + +"""This module contains helper classes and functions for working +with the COLLADA 1.4.1 schema.""" + +import io +import lxml +import lxml.etree + +from .resources import resource_string + +# get a copy of the XML schema +COLLADA_SCHEMA_1_4_1 = resource_string("schema-1.4.1.xml") +XML_XSD = resource_string("xsd.xml") + + +class ColladaResolver(lxml.etree.Resolver): + """COLLADA XML Resolver. If a known URL referenced + from the COLLADA spec is resolved, a cached local + copy is returned instead of initiating a network + request""" + + def resolve(self, url, id, context): + """Currently Resolves: + * http://www.w3.org/2001/03/xml.xsd + """ + if url == 'http://www.w3.org/2001/03/xml.xsd': + return self.resolve_string(XML_XSD, context) + else: + return None + + +class ColladaValidator(object): + """Validates a collada lxml document""" + + def __init__(self): + """Initializes the validator""" + self.COLLADA_SCHEMA_1_4_1_DOC = None + self._COLLADA_SCHEMA_1_4_1_INSTANCE = None + + def _getColladaSchemaInstance(self): + if self._COLLADA_SCHEMA_1_4_1_INSTANCE is None: + self._parser = lxml.etree.XMLParser() + self._parser.resolvers.add(ColladaResolver()) + self.COLLADA_SCHEMA_1_4_1_DOC = lxml.etree.parse( + io.BytesIO(bytes(COLLADA_SCHEMA_1_4_1, encoding='utf-8')), + self._parser) + self._COLLADA_SCHEMA_1_4_1_INSTANCE = lxml.etree.XMLSchema( + self.COLLADA_SCHEMA_1_4_1_DOC) + return self._COLLADA_SCHEMA_1_4_1_INSTANCE + + COLLADA_SCHEMA_1_4_1_INSTANCE = property(_getColladaSchemaInstance) + """An instance of lxml.XMLSchema that can be used to validate""" + + def validate(self, *args, **kwargs): + """A wrapper for lxml.XMLSchema.validate""" + return self.COLLADA_SCHEMA_1_4_1_INSTANCE.validate(*args, **kwargs) diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/source.py b/data/miniconda3/lib/python3.13/site-packages/collada/source.py new file mode 100644 index 0000000000000000000000000000000000000000..26170b1b4185953a103e9034113088b76c693177 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/collada/source.py @@ -0,0 +1,454 @@ +#################################################################### +# # +# THIS FILE IS PART OF THE pycollada LIBRARY SOURCE CODE. # +# USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS # +# GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE # +# IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. # +# # +# THE pycollada SOURCE CODE IS (C) COPYRIGHT 2011 # +# by Jeff Terrace and contributors # +# # +#################################################################### + +"""Module for managing data sources defined in geometry tags.""" + +import numpy + +from collada.common import DaeObject, E, tag +from collada.common import DaeIncompleteError, DaeMalformedError, DaeUnsupportedError + + +class InputList(object): + """Used for defining input sources to a geometry.""" + + class Input: + def __init__(self, offset, semantic, src, set=None): + self.offset = offset + self.semantic = semantic + self.source = src + self.set = set + + semantics = ["VERTEX", "NORMAL", "TEXCOORD", "TEXBINORMAL", "TEXTANGENT", "COLOR", "TANGENT", "BINORMAL"] + + def __init__(self): + """Create an input list""" + self.inputs = {s: [] for s in self.semantics} + + def addInput(self, offset, semantic, src, set=None): + """Add an input source to this input list. + + :param int offset: + Offset for this source within the geometry's indices + :param str semantic: + The semantic for the input source. Currently supported options are: + * VERTEX + * NORMAL + * TEXCOORD + * TEXBINORMAL + * TEXTANGENT + * COLOR + * TANGENT + * BINORMAL + :param str src: + A string identifier of the form `#srcid` where `srcid` is a source + within the geometry's :attr:`~collada.geometry.Geometry.sourceById` array. + :param str set: + Indicates a set number for the source. This is used, for example, + when there are multiple texture coordinate sets. + + """ + if semantic not in self.semantics: + raise DaeUnsupportedError("Unsupported semantic %s" % semantic) + self.inputs[semantic].append(self.Input(offset, semantic, src, set)) + + def getList(self): + """Returns a list of tuples of the source in the form (offset, semantic, source, set)""" + retlist = [] + for inplist in self.inputs.values(): + for inp in inplist: + retlist.append((inp.offset, inp.semantic, inp.source, inp.set)) + return retlist + + def __str__(self): + return '' + + def __repr__(self): + return str(self) + + +class Source(DaeObject): + """Abstract class for loading source arrays""" + + @staticmethod + def load(collada, localscope, node): + sourceid = node.get('id') + # Try float_array first (most common), pass found node to avoid re-lookup + arraynode = node.find(collada.tag('float_array')) + if arraynode is not None: + return FloatSource.load(collada, localscope, node, arraynode) + arraynode = node.find(collada.tag('IDREF_array')) + if arraynode is not None: + return IDRefSource.load(collada, localscope, node, arraynode) + arraynode = node.find(collada.tag('Name_array')) + if arraynode is not None: + return NameSource.load(collada, localscope, node, arraynode) + + raise DaeIncompleteError('No array found in source %s' % sourceid) + + +class FloatSource(Source): + """Contains a source array of floats, as defined in the collada + inside a . + + If ``f`` is an instance of :class:`collada.source.FloatSource`, then + ``len(f)`` is the length of the shaped source. ``len(f)*len(f.components)`` + would give you the number of values in the source. ``f[i]`` is the i\\ :sup:`th` + item in the source array. + """ + + def __init__(self, id, data, components, xmlnode=None): + """Create a float source instance. + + :param str id: + A unique string identifier for the source + :param numpy.array data: + Numpy array (unshaped) with the source values + :param tuple components: + Tuple of strings describing the semantic of the data, + e.g. ``('X','Y','Z')`` would cause :attr:`data` to be + reshaped as ``(-1, 3)`` + :param xmlnode: + When loaded, the xmlnode it comes from. + + """ + + self.id = id + """The unique string identifier for the source""" + + # check that the passed data is reshapable + if (data.size % len(components)) != 0: + raise DaeMalformedError( + 'data.size `{}` isn\'t reshapable into `(-1, {})`!'.format( + data.size, + len(components))) + + """Numpy array with the source values. This will be shaped as ``(-1,N)`` where ``N = len(self.components)``""" + self.data = data.reshape((-1, len(components))) + + self.components = components + """Tuple of strings describing the semantic of the data, e.g. ``('X','Y','Z')``""" + if xmlnode is not None: + self.xmlnode = xmlnode + """ElementTree representation of the source.""" + else: + self.data.shape = (-1,) + txtdata = ' '.join(map(str, self.data.tolist())) + rawlen = len(self.data) + self.data.shape = (-1, len(self.components)) + acclen = len(self.data) + stridelen = len(self.components) + sourcename = "%s-array" % self.id + + self.xmlnode = E.source( + E.float_array(txtdata, count=str(rawlen), id=sourcename), + E.technique_common( + E.accessor( + *[E.param(type='float', name=c) for c in self.components], **{'count': str(acclen), 'stride': str(stridelen), 'source': "#%s" % sourcename}) + ), id=self.id) + + def __len__(self): + return len(self.data) + + def __getitem__(self, i): + return self.data[i] + + def save(self): + """Saves the source back to :attr:`xmlnode`""" + self.data.shape = (-1,) + + txtdata = ' '.join(map(lambda x: '%.7g' % x, self.data.tolist())) + + rawlen = len(self.data) + self.data.shape = (-1, len(self.components)) + acclen = len(self.data) + node = self.xmlnode.find(tag('float_array')) + node.text = txtdata + node.set('count', str(rawlen)) + node.set('id', self.id + '-array') + node = self.xmlnode.find(f"{tag('technique_common')}/{tag('accessor')}") + node.clear() + node.set('count', str(acclen)) + node.set('source', '#' + self.id + '-array') + node.set('stride', str(len(self.components))) + for c in self.components: + node.append(E.param(type='float', name=c)) + self.xmlnode.set('id', self.id) + + @staticmethod + def load(collada, localscope, node, arraynode=None): + sourceid = node.get('id') + if arraynode is None: + arraynode = node.find(collada.tag('float_array')) + if arraynode is None: + raise DaeIncompleteError('No float_array in source node') + if arraynode.text is None or arraynode.text.isspace(): + data = numpy.array([], dtype=numpy.float32) + else: + try: + data = numpy.fromstring(arraynode.text, dtype=numpy.float32, sep=' ') + except ValueError: + raise DaeMalformedError('Corrupted float array') + # Replace NaN values with 0 + data[numpy.isnan(data)] = 0 + + # Use cached xpath or build and cache it + accessor_path = getattr(collada, '_floatsource_accessor_xpath', None) + if accessor_path is None: + accessor_path = f"{collada.tag('technique_common')}/{collada.tag('accessor')}/{collada.tag('param')}" + collada._floatsource_accessor_xpath = accessor_path + paramnodes = node.findall(accessor_path) + if not paramnodes: + raise DaeIncompleteError('No accessor info in source node') + components = [param.get('name') for param in paramnodes] + if len(components) == 2 and components[0] == 'U' and components[1] == 'V': + # U,V is used for "generic" arguments - convert to S,T + components = ['S', 'T'] + if len(components) == 3 and components[0] == 'S' and components[1] == 'T' and components[2] == 'P': + components = ['S', 'T'] + data.shape = (-1, 3) + # remove 3d texcoord dimension because we don't support it + data = numpy.delete(data, -1, 1) + data.shape = (-1) + return FloatSource(sourceid, data, tuple(components), xmlnode=node) + + def __str__(self): + return '' % (len(self),) + + def __repr__(self): + return str(self) + + +class IDRefSource(Source): + """Contains a source array of ID references, as defined in the collada + inside a . + + If ``r`` is an instance of :class:`collada.source.IDRefSource`, then + ``len(r)`` is the length of the shaped source. ``len(r)*len(r.components)`` + would give you the number of values in the source. ``r[i]`` is the i\\ :sup:`th` + item in the source array. + + """ + + def __init__(self, id, data, components, xmlnode=None): + """Create an id ref source instance. + + :param str id: + A unique string identifier for the source + :param numpy.array data: + Numpy array (unshaped) with the source values + :param tuple components: + Tuple of strings describing the semantic of the data, + e.g. ``('MORPH_TARGET')`` would cause :attr:`data` to be + reshaped as ``(-1, 1)`` + :param xmlnode: + When loaded, the xmlnode it comes from. + + """ + + self.id = id + """The unique string identifier for the source""" + self.data = data + """Numpy array with the source values. This will be shaped as ``(-1,N)`` where ``N = len(self.components)``""" + self.data.shape = (-1, len(components)) + self.components = components + """Tuple of strings describing the semantic of the data, e.g. ``('MORPH_TARGET')``""" + if xmlnode is not None: + self.xmlnode = xmlnode + """ElementTree representation of the source.""" + else: + self.data.shape = (-1,) + txtdata = ' '.join(map(str, self.data.tolist())) + rawlen = len(self.data) + self.data.shape = (-1, len(self.components)) + acclen = len(self.data) + stridelen = len(self.components) + sourcename = "%s-array" % self.id + + self.xmlnode = E.source( + E.IDREF_array(txtdata, count=str(rawlen), id=sourcename), + E.technique_common( + E.accessor( + *[E.param(type='IDREF', name=c) for c in self.components], **{'count': str(acclen), 'stride': str(stridelen), 'source': sourcename}) + ), id=self.id) + + def __len__(self): + return len(self.data) + + def __getitem__(self, i): + return self.data[i][0] if len(self.data[i]) == 1 else self.data[i] + + def save(self): + """Saves the source back to :attr:`xmlnode`""" + self.data.shape = (-1,) + txtdata = ' '.join(map(str, self.data.tolist())) + rawlen = len(self.data) + self.data.shape = (-1, len(self.components)) + acclen = len(self.data) + + node = self.xmlnode.find(tag('IDREF_array')) + node.text = txtdata + node.set('count', str(rawlen)) + node.set('id', self.id + '-array') + node = self.xmlnode.find(f"{tag('technique_common')}/{tag('accessor')}") + node.clear() + node.set('count', str(acclen)) + node.set('source', '#' + self.id + '-array') + node.set('stride', str(len(self.components))) + for c in self.components: + node.append(E.param(type='IDREF', name=c)) + self.xmlnode.set('id', self.id) + + @staticmethod + def load(collada, localscope, node, arraynode=None): + sourceid = node.get('id') + if arraynode is None: + arraynode = node.find(collada.tag('IDREF_array')) + if arraynode is None: + raise DaeIncompleteError('No IDREF_array in source node') + if arraynode.text is None or arraynode.text.isspace(): + values = [] + else: + try: + values = arraynode.text.split() + except ValueError: + raise DaeMalformedError('Corrupted IDREF array') + data = numpy.array(values, dtype=numpy.str_) + # Use cached xpath (same as FloatSource) or build and cache it + accessor_path = getattr(collada, '_floatsource_accessor_xpath', None) + if accessor_path is None: + accessor_path = f"{collada.tag('technique_common')}/{collada.tag('accessor')}/{collada.tag('param')}" + collada._floatsource_accessor_xpath = accessor_path + paramnodes = node.findall(accessor_path) + if not paramnodes: + raise DaeIncompleteError('No accessor info in source node') + components = [param.get('name') for param in paramnodes] + return IDRefSource(sourceid, data, tuple(components), xmlnode=node) + + def __str__(self): + return '' % (len(self),) + + def __repr__(self): + return str(self) + + +class NameSource(Source): + """Contains a source array of strings, as defined in the collada + inside a . + + If ``n`` is an instance of :class:`collada.source.NameSource`, then + ``len(n)`` is the length of the shaped source. ``len(n)*len(n.components)`` + would give you the number of values in the source. ``n[i]`` is the i\\ :sup:`th` + item in the source array. + + """ + + def __init__(self, id, data, components, xmlnode=None): + """Create a name source instance. + + :param str id: + A unique string identifier for the source + :param numpy.array data: + Numpy array (unshaped) with the source values + :param tuple components: + Tuple of strings describing the semantic of the data, + e.g. ``('JOINT')`` would cause :attr:`data` to be + reshaped as ``(-1, 1)`` + :param xmlnode: + When loaded, the xmlnode it comes from. + + """ + + self.id = id + """The unique string identifier for the source""" + self.data = data + """Numpy array with the source values. This will be shaped as ``(-1,N)`` where ``N = len(self.components)``""" + self.data.shape = (-1, len(components)) + self.components = components + """Tuple of strings describing the semantic of the data, e.g. ``('JOINT')``""" + if xmlnode is not None: + self.xmlnode = xmlnode + """ElementTree representation of the source.""" + else: + self.data.shape = (-1,) + txtdata = ' '.join(map(str, self.data.tolist())) + rawlen = len(self.data) + self.data.shape = (-1, len(self.components)) + acclen = len(self.data) + stridelen = len(self.components) + sourcename = "%s-array" % self.id + + self.xmlnode = E.source( + E.Name_array(txtdata, count=str(rawlen), id=sourcename), + E.technique_common( + E.accessor( + *[E.param(type='Name', name=c) for c in self.components], **{'count': str(acclen), 'stride': str(stridelen), 'source': sourcename}) + ), id=self.id) + + def __len__(self): + return len(self.data) + + def __getitem__(self, i): + return self.data[i][0] if len(self.data[i]) == 1 else self.data[i] + + def save(self): + """Saves the source back to :attr:`xmlnode`""" + self.data.shape = (-1,) + txtdata = ' '.join(map(str, self.data.tolist())) + rawlen = len(self.data) + self.data.shape = (-1, len(self.components)) + acclen = len(self.data) + + node = self.xmlnode.find(tag('Name_array')) + node.text = txtdata + node.set('count', str(rawlen)) + node.set('id', self.id + '-array') + node = self.xmlnode.find(f"{tag('technique_common')}/{tag('accessor')}") + node.clear() + node.set('count', str(acclen)) + node.set('source', '#' + self.id + '-array') + node.set('stride', str(len(self.components))) + for c in self.components: + node.append(E.param(type='IDREF', name=c)) + self.xmlnode.set('id', self.id) + + @staticmethod + def load(collada, localscope, node, arraynode=None): + sourceid = node.get('id') + if arraynode is None: + arraynode = node.find(collada.tag('Name_array')) + if arraynode is None: + raise DaeIncompleteError('No Name_array in source node') + if arraynode.text is None or arraynode.text.isspace(): + values = [] + else: + try: + values = arraynode.text.split() + except ValueError: + raise DaeMalformedError('Corrupted Name array') + data = numpy.array(values, dtype=numpy.str_) + # Use cached xpath (same as FloatSource) or build and cache it + accessor_path = getattr(collada, '_floatsource_accessor_xpath', None) + if accessor_path is None: + accessor_path = f"{collada.tag('technique_common')}/{collada.tag('accessor')}/{collada.tag('param')}" + collada._floatsource_accessor_xpath = accessor_path + paramnodes = node.findall(accessor_path) + if not paramnodes: + raise DaeIncompleteError('No accessor info in source node') + components = [param.get('name') for param in paramnodes] + return NameSource(sourceid, data, tuple(components), xmlnode=node) + + def __str__(self): + return '' % (len(self),) + + def __repr__(self): + return str(self) diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/triangleset.py b/data/miniconda3/lib/python3.13/site-packages/collada/triangleset.py new file mode 100644 index 0000000000000000000000000000000000000000..d83718fc13a75f718c85290b9f788f928be96ad0 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/collada/triangleset.py @@ -0,0 +1,458 @@ +#################################################################### +# # +# THIS FILE IS PART OF THE pycollada LIBRARY SOURCE CODE. # +# USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS # +# GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE # +# IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. # +# # +# THE pycollada SOURCE CODE IS (C) COPYRIGHT 2011 # +# by Jeff Terrace and contributors # +# # +#################################################################### + +"""Module containing classes and functions for the primitive.""" + +import numpy + +from collada import primitive +from collada.common import E +from collada.common import DaeIncompleteError, DaeMalformedError +from collada.util import toUnitVec, checkSource, normalize_v3, dot_v3 + + +class Triangle(object): + """Single triangle representation.""" + + def __init__(self, indices, vertices, normal_indices, normals, + texcoord_indices, texcoords, material): + """A triangle should not be created manually.""" + + self.vertices = vertices + """A (3, 3) float array for points in the triangle""" + self.normals = normals + """A (3, 3) float array with the normals for points in the triangle. + If the triangle didn't have normals, they will be computed.""" + self.texcoords = texcoords + """A tuple with (3, 2) float arrays with the texture coordinates + for the points in the triangle""" + self.material = material + """If coming from an unbound :class:`collada.triangleset.TriangleSet`, contains a + string with the material symbol. If coming from a bound + :class:`collada.triangleset.BoundTriangleSet`, contains the actual + :class:`collada.material.Effect` the triangle is bound to.""" + self.indices = indices + """A (3,) int array with vertex indexes of the 3 vertices in + the vertex array""" + self.normal_indices = normal_indices + """A (3,) int array with normal indexes of the 3 vertices in + the normal array""" + self.texcoord_indices = texcoord_indices + """A (3,2) int array with texture coordinate indexes of the 3 + vertices in the texcoord array.""" + + if self.normals is None: + # generate normals + vec1 = numpy.subtract(vertices[0], vertices[1]) + vec2 = numpy.subtract(vertices[2], vertices[0]) + vec3 = toUnitVec(numpy.cross(toUnitVec(vec2), toUnitVec(vec1))) + self.normals = numpy.array([vec3, vec3, vec3]) + + def __repr__(self): + return '' % (str(self.vertices[0]), + str(self.vertices[1]), str(self.vertices[2]), + str(self.material)) + + def __str__(self): + return repr(self) + + +class TriangleSet(primitive.Primitive): + """Class containing the data COLLADA puts in a tag, a collection of + triangles. + + * The TriangleSet object is read-only. To modify a TriangleSet, create a new + instance using :meth:`collada.geometry.Geometry.createTriangleSet`. + * If ``T`` is an instance of :class:`collada.triangleset.TriangleSet`, then ``len(T)`` + returns the number of triangles in the set. ``T[i]`` returns the i\\ :sup:`th` + triangle in the set. + """ + + def __init__(self, sources, material, index, xmlnode=None): + """A TriangleSet should not be created manually. Instead, call the + :meth:`collada.geometry.Geometry.createTriangleSet` method after + creating a geometry instance. + """ + + if len(sources) == 0: + raise DaeIncompleteError('A triangle set needs at least one input for vertex positions') + if 'VERTEX' not in sources: + raise DaeIncompleteError('Triangle set requires vertex input') + + max_offset = max([max([input[0] for input in input_type_array]) + for input_type_array in sources.values() + if len(input_type_array) > 0]) + + self.material = material + self.index = index + self.indices = self.index + self.nindices = max_offset + 1 + self.index.shape = (-1, 3, self.nindices) + self.ntriangles = len(self.index) + self.sources = sources + + if len(self.index) > 0: + self._vertex = sources['VERTEX'][0][4].data + self._vertex_index = self.index[:, :, sources['VERTEX'][0][0]] + self.maxvertexindex = numpy.max(self._vertex_index) + checkSource(sources['VERTEX'][0][4], ('X', 'Y', 'Z'), self.maxvertexindex) + else: + self._vertex = None + self._vertex_index = None + self.maxvertexindex = -1 + + if 'NORMAL' in sources and len(sources['NORMAL']) > 0 and len(self.index) > 0: + self._normal = sources['NORMAL'][0][4].data + self._normal_index = self.index[:, :, sources['NORMAL'][0][0]] + self.maxnormalindex = numpy.max(self._normal_index) + checkSource(sources['NORMAL'][0][4], ('X', 'Y', 'Z'), self.maxnormalindex) + else: + self._normal = None + self._normal_index = None + self.maxnormalindex = -1 + + if 'TEXCOORD' in sources and len(sources['TEXCOORD']) > 0 and len(self.index) > 0: + self._texcoordset = tuple([texinput[4].data for texinput in sources['TEXCOORD']]) + self._texcoord_indexset = tuple([self.index[:, :, sources['TEXCOORD'][i][0]] + for i in range(len(sources['TEXCOORD']))]) + self.maxtexcoordsetindex = [numpy.max(tex_index) for tex_index in self._texcoord_indexset] + for i, texinput in enumerate(sources['TEXCOORD']): + checkSource(texinput[4], ('S', 'T'), self.maxtexcoordsetindex[i]) + else: + self._texcoordset = tuple() + self._texcoord_indexset = tuple() + self.maxtexcoordsetindex = -1 + + if 'TEXTANGENT' in sources and len(sources['TEXTANGENT']) > 0 and len(self.index) > 0: + self._textangentset = tuple([texinput[4].data for texinput in sources['TEXTANGENT']]) + self._textangent_indexset = tuple([self.index[:, :, sources['TEXTANGENT'][i][0]] + for i in range(len(sources['TEXTANGENT']))]) + self.maxtextangentsetindex = [numpy.max(tex_index) for tex_index in self._textangent_indexset] + for i, texinput in enumerate(sources['TEXTANGENT']): + checkSource(texinput[4], ('X', 'Y', 'Z'), self.maxtextangentsetindex[i]) + else: + self._textangentset = tuple() + self._textangent_indexset = tuple() + self.maxtextangentsetindex = -1 + + if 'TEXBINORMAL' in sources and len(sources['TEXBINORMAL']) > 0 and len(self.index) > 0: + self._texbinormalset = tuple([texinput[4].data for texinput in sources['TEXBINORMAL']]) + self._texbinormal_indexset = tuple([self.index[:, :, sources['TEXBINORMAL'][i][0]] + for i in range(len(sources['TEXBINORMAL']))]) + self.maxtexbinormalsetindex = [numpy.max(tex_index) for tex_index in self._texbinormal_indexset] + for i, texinput in enumerate(sources['TEXBINORMAL']): + checkSource(texinput[4], ('X', 'Y', 'Z'), self.maxtexbinormalsetindex[i]) + else: + self._texbinormalset = tuple() + self._texbinormal_indexset = tuple() + self.maxtexbinormalsetindex = -1 + + if xmlnode is not None: + self.xmlnode = xmlnode + else: + self._recreateXmlNode() + + def __len__(self): + return len(self.index) + + def _recreateXmlNode(self): + self.index.shape = (-1) + len(self.index) + txtindices = ' '.join(map(str, self.index.tolist())) + self.index.shape = (-1, 3, self.nindices) + + self.xmlnode = E.triangles(count=str(self.ntriangles)) + if self.material is not None: + self.xmlnode.set('material', self.material) + + all_inputs = [] + for semantic_list in self.sources.values(): + all_inputs.extend(semantic_list) + for offset, semantic, sourceid, set, src in all_inputs: + inpnode = E.input(offset=str(offset), semantic=semantic, source=sourceid) + if set is not None: + inpnode.set('set', str(set)) + self.xmlnode.append(inpnode) + + self.xmlnode.append(E.p(txtindices)) + + def __getitem__(self, i): + v = self._vertex[self._vertex_index[i]] + n = self._normal[self._normal_index[i]] if self._normal is not None else None + uvindices = [] + uv = [] + for j, uvindex in enumerate(self._texcoord_indexset): + uvindices.append(uvindex[i]) + uv.append(self._texcoordset[j][uvindex[i]]) + return Triangle(self._vertex_index[i], v, self._normal_index[i] if self._normal_index is not None else 0, n, uvindices, uv, self.material) + + @staticmethod + def load(collada, localscope, node): + indexnodes = node.findall(collada.tag('p')) + input_tag = collada.tag('input') + if not indexnodes: + raise DaeIncompleteError('Missing index in triangle set') + + source_array = primitive.Primitive._getInputs(collada, localscope, node.findall(input_tag)) + + def parse_p(indexnode): + if indexnode.text is None or indexnode.text.isspace(): + index = numpy.array([], dtype=numpy.int32) + else: + try: + index = numpy.fromstring(indexnode.text, dtype=numpy.int32, sep=' ') + except ValueError: + raise DaeMalformedError("Failed to parse triangleset index ints") + index[numpy.isnan(index)] = 0 + return index + + indexlist = [] + tag_bare = node.tag.split('}')[-1] + + extendfunc = _indexExtendFunctions[tag_bare] + + max_offset = max(input[0] for input_type_array in source_array.values() + for input in input_type_array) + + try: + for indexnode in indexnodes: + index = parse_p(indexnode) + if extendfunc is None: + break + + extendfunc(indexlist, index.reshape((-1, max_offset + 1))) + else: + index = numpy.concatenate(indexlist) + except BaseException: + raise DaeMalformedError('Corrupted index in triangleset') + + triset = TriangleSet(source_array, node.get('material'), index, node) + triset.xmlnode = node + return triset + + def bind(self, matrix, materialnodebysymbol): + """Create a bound triangle set from this triangle set, transform and material mapping""" + return BoundTriangleSet(self, matrix, materialnodebysymbol) + + def generateNormals(self): + """If :attr:`normals` is `None` or you wish for normals to be + recomputed, call this method to recompute them.""" + norms = numpy.zeros(self._vertex.shape, dtype=self._vertex.dtype) + tris = self._vertex[self._vertex_index] + n = numpy.cross(tris[::, 1] - tris[::, 0], tris[::, 2] - tris[::, 0]) + normalize_v3(n) + norms[self._vertex_index[:, 0]] += n + norms[self._vertex_index[:, 1]] += n + norms[self._vertex_index[:, 2]] += n + normalize_v3(norms) + + self._normal = norms + self._normal_index = self._vertex_index + + def generateTexTangentsAndBinormals(self): + """If there are no texture tangents, this method will compute them. + Texture coordinates must exist and it uses the first texture coordinate set.""" + + # The following is taken from: + # http://www.terathon.com/code/tangent.html + # It's pretty much a direct translation, using numpy arrays + + tris = self._vertex[self._vertex_index] + uvs = self._texcoordset[0][self._texcoord_indexset[0]] + + x1 = tris[:, 1, 0] - tris[:, 0, 0] + x2 = tris[:, 2, 0] - tris[:, 1, 0] + y1 = tris[:, 1, 1] - tris[:, 0, 1] + y2 = tris[:, 2, 1] - tris[:, 1, 1] + z1 = tris[:, 1, 2] - tris[:, 0, 2] + z2 = tris[:, 2, 2] - tris[:, 1, 2] + + s1 = uvs[:, 1, 0] - uvs[:, 0, 0] + s2 = uvs[:, 2, 0] - uvs[:, 1, 0] + t1 = uvs[:, 1, 1] - uvs[:, 0, 1] + t2 = uvs[:, 2, 1] - uvs[:, 1, 1] + + r = 1.0 / (s1 * t2 - s2 * t1) + + sdirx = (t2 * x1 - t1 * x2) * r + sdiry = (t2 * y1 - t1 * y2) * r + sdirz = (t2 * z1 - t1 * z2) * r + sdir = numpy.vstack((sdirx, sdiry, sdirz)).T + + tans1 = numpy.zeros(self._vertex.shape, dtype=self._vertex.dtype) + tans1[self._vertex_index[:, 0]] += sdir + tans1[self._vertex_index[:, 1]] += sdir + tans1[self._vertex_index[:, 2]] += sdir + + norm = self._normal[self._normal_index] + norm.shape = (-1, 3) + tan1 = tans1[self._vertex_index] + tan1.shape = (-1, 3) + + tangent = normalize_v3(tan1 - norm * dot_v3(norm, tan1)[:, numpy.newaxis]) + + self._textangentset = (tangent,) + self._textangent_indexset = (numpy.arange(len(self._vertex_index) * 3, dtype=self._vertex_index.dtype),) + self._textangent_indexset[0].shape = (len(self._vertex_index), 3) + + tdirx = (s1 * x2 - s2 * x1) * r + tdiry = (s1 * y2 - s2 * y1) * r + tdirz = (s1 * z2 - s2 * z1) * r + tdir = numpy.vstack((tdirx, tdiry, tdirz)).T + + tans2 = numpy.zeros(self._vertex.shape, dtype=self._vertex.dtype) + tans2[self._vertex_index[:, 0]] += tdir + tans2[self._vertex_index[:, 1]] += tdir + tans2[self._vertex_index[:, 2]] += tdir + + tan2 = tans2[self._vertex_index] + tan2.shape = (-1, 3) + + tanw = dot_v3(numpy.cross(norm, tan1), tan2) + tanw = numpy.sign(tanw) + + binorm = numpy.cross(norm, tangent).flatten() + binorm.shape = (-1, 3) + binorm = binorm * tanw[:, numpy.newaxis] + + self._texbinormalset = (binorm,) + self._texbinormal_indexset = (numpy.arange(len(self._vertex_index) * 3, + dtype=self._vertex_index.dtype),) + self._texbinormal_indexset[0].shape = (len(self._vertex_index), 3) + + def __str__(self): + return '' % len(self) + + def __repr__(self): + return str(self) + + +class BoundTriangleSet(primitive.BoundPrimitive): + """A triangle set bound to a transform matrix and materials mapping. + + * If ``T`` is an instance of :class:`collada.triangleset.BoundTriangleSet`, then ``len(T)`` + returns the number of triangles in the set. ``T[i]`` returns the i\\ :sup:`th` + triangle in the set. + """ + + def __init__(self, ts, matrix, materialnodebysymbol): + """Create a bound triangle set from a triangle set, transform and material mapping. + This gets created when a triangle set is instantiated in a scene. Do not create this manually.""" + M = numpy.asmatrix(matrix).transpose() + self._vertex = None if ts.vertex is None else numpy.asarray(ts._vertex * M[:3, :3]) + matrix[:3, 3] + self._normal = None if ts._normal is None else numpy.asarray(ts._normal * M[:3, :3]) + self._texcoordset = ts._texcoordset + self._textangentset = ts._textangentset + self._texbinormalset = ts._texbinormalset + matnode = materialnodebysymbol.get(ts.material) + if matnode: + self.material = matnode.target + self.inputmap = dict([(sem, (input_sem, set)) for sem, input_sem, set in matnode.inputs]) + else: + self.inputmap = self.material = None + self.index = ts.index + self._vertex_index = ts._vertex_index + self._normal_index = ts._normal_index + self._texcoord_indexset = ts._texcoord_indexset + self._textangent_indexset = ts._textangent_indexset + self._texbinormal_indexset = ts._texbinormal_indexset + self.ntriangles = ts.ntriangles + self.original = ts + + def __len__(self): + return len(self.index) + + def __getitem__(self, i): + vindex = self._vertex_index[i] + v = self._vertex[vindex] + + if self._normal is None: + n = None + nindex = None + else: + nindex = self._normal_index[i] + n = self._normal[nindex] + + uvindices = [] + uv = [] + for j, uvindex in enumerate(self._texcoord_indexset): + uvindices.append(uvindex[i]) + uv.append(self._texcoordset[j][uvindex[i]]) + + return Triangle(vindex, v, nindex, n, uvindices, uv, self.material) + + def triangles(self): + """Iterate through all the triangles contained in the set. + + :rtype: generator of :class:`collada.triangleset.Triangle` + """ + for i in range(self.ntriangles): + yield self[i] + + def shapes(self): + """Iterate through all the triangles contained in the set. + + :rtype: generator of :class:`collada.triangleset.Triangle` + """ + return self.triangles() + + def generateNormals(self): + """If :attr:`normals` is `None` or you wish for normals to be + recomputed, call this method to recompute them.""" + norms = numpy.zeros(self._vertex.shape, dtype=self._vertex.dtype) + tris = self._vertex[self._vertex_index] + n = numpy.cross(tris[::, 1] - tris[::, 0], tris[::, 2] - tris[::, 0]) + normalize_v3(n) + norms[self._vertex_index[:, 0]] += n + norms[self._vertex_index[:, 1]] += n + norms[self._vertex_index[:, 2]] += n + normalize_v3(norms) + + self._normal = norms + self._normal_index = self._vertex_index + + def __str__(self): + return '' % len(self) + + def __repr__(self): + return str(self) + + +def _extendFromStrip(indexlist, index): + """Convert triangle strip indices to triangle indices + + :param list indexlist: + list to append 1-dimensional index arrays to + :param numpy.ndarray index: + (#vertices, #inputs) shaped index array + """ + cw_ = numpy.array([index[0:-2:2], index[1:-1:2], index[2::2]]) + ccw = numpy.array([index[2:-1:2], index[1:-2:2], index[3::2]]) + indexlist.append(cw_.swapaxes(0, 1).ravel()) + indexlist.append(ccw.swapaxes(0, 1).ravel()) + + +def _extendFromFan(indexlist, index): + """Convert triangle fan indices to triangle indices + """ + c = numpy.concatenate(( + numpy.repeat(index[:1], len(index) - 2, 0), + index[1:-1], + index[2:]), 1) + indexlist.append(c.reshape(-1)) + + +_indexExtendFunctions = { + 'tristrips': _extendFromStrip, + 'trifans': _extendFromFan, + 'triangles': None, +} diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/util.py b/data/miniconda3/lib/python3.13/site-packages/collada/util.py new file mode 100644 index 0000000000000000000000000000000000000000..f512fdfff0cd80012cbd6cb716732a2b9d2f3921 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/collada/util.py @@ -0,0 +1,262 @@ +#################################################################### +# # +# THIS FILE IS PART OF THE pycollada LIBRARY SOURCE CODE. # +# USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS # +# GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE # +# IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. # +# # +# THE pycollada SOURCE CODE IS (C) COPYRIGHT 2011 # +# by Jeff Terrace and contributors # +# # +#################################################################### + +"""This module contains utility functions""" + +import numpy +import math + +from collada.common import DaeMalformedError, E, tag + + +def falmostEqual(a, b, rtol=1.0000000000000001e-05, atol=1e-08): + """Checks if the given floats are almost equal. Uses the algorithm + from numpy.allclose. + + :param float a: + First float to compare + :param float b: + Second float to compare + :param float rtol: + The relative tolerance parameter + :param float atol: + The absolute tolerance parameter + + :rtype: bool + + """ + + return math.fabs(a - b) <= (atol + rtol * math.fabs(b)) + + +def toUnitVec(vec): + """Converts the given vector to a unit vector + + :param numpy.array vec: + The vector to transform to unit length + + :rtype: numpy.array + + """ + return vec / numpy.sqrt(numpy.vdot(vec, vec)) + + +def checkSource(source, components, maxindex): + """Check if a source objects complies with the needed `components` and has the needed length + + :param collada.source.Source source: + A source instance to check + :param tuple components: + A tuple describing the needed channels, e.g. ``('X','Y','Z')`` + :param int maxindex: + The maximum index that refers to this source + + """ + if len(source.data) <= maxindex: + raise DaeMalformedError( + "Indexes (maxindex=%d) for source '%s' (len=%d) go beyond the limits of the source" + % (maxindex, source.id, len(source.data))) + + # some files will write sources with no named parameters + # by spec, these params should just be skipped, but we need to + # adapt to the failed output of others... + if len(source.components) == len(components): + source.components = components + + if source.components != components: + raise DaeMalformedError('Wrong format in source %s' % source.id) + return source + + +def normalize_v3(arr): + """Normalize a numpy array of 3 component vectors with shape (N,3) + + :param numpy.array arr: + The numpy array to normalize + + :rtype: numpy.array + + """ + lens = numpy.sqrt(arr[:, 0]**2 + arr[:, 1]**2 + arr[:, 2]**2) + lens[numpy.equal(lens, 0)] = 1 + arr[:, 0] /= lens + arr[:, 1] /= lens + arr[:, 2] /= lens + return arr + + +def dot_v3(arr1, arr2): + """Calculates the dot product for each vector in two arrays + + :param numpy.array arr1: + The first array, shape Nx3 + :param numpy.array arr2: + The second array, shape Nx3 + + :rtype: numpy.array + + """ + return arr1[:, 0] * arr2[:, 0] + arr1[:, 1] * arr2[:, 1] + arr2[:, 2] * arr1[:, 2] + + +class IndexedList(list): + """ + Class that combines a list and a dict into a single class + - Written by Hugh Bothwell (http://stackoverflow.com/users/33258/hugh-bothwell) + - Original source available at: + http://stackoverflow.com/questions/5332841/python-list-dict-property-best-practice/5334686#5334686 + - Modifications by Jeff Terrace + Given an object, obj, that has a property x, this allows you to create an IndexedList like so: + L = IndexedList([], ('x')) + o = obj() + o.x = 'test' + L.append(o) + L[0] # = o + L['test'] # = o + """ + + def __init__(self, items, attrs): + super(IndexedList, self).__init__(items) + # do indexing + self._attrs = tuple(attrs) + self._index = {} + _add = self._addindex + for obj in self: + _add(obj) + + def _addindex(self, obj): + _idx = self._index + for attr in self._attrs: + _idx[getattr(obj, attr)] = obj + + def _delindex(self, obj): + _idx = self._index + for attr in self._attrs: + try: + del _idx[getattr(obj, attr)] + except KeyError: + pass + + def __delitem__(self, ind): + try: + obj = list.__getitem__(self, ind) + except (IndexError, TypeError): + obj = self._index[ind] + ind = list.index(self, obj) + self._delindex(obj) + return list.__delitem__(self, ind) + + def __delslice__(self, i, j): + return list.__delslice__(self, i, j) + + def __getitem__(self, ind): + try: + return self._index[ind] + except KeyError: + if isinstance(ind, str): + raise + return list.__getitem__(self, ind) + + def get(self, key, default=None): + try: + return self._index[key] + except KeyError: + return default + + def __contains__(self, item): + if item in self._index: + return True + return list.__contains__(self, item) + + def __getslice__(self, i, j): + return IndexedList(list.__getslice__(self, i, j), self._attrs) + + def __setitem__(self, ind, new_obj): + try: + obj = list.__getitem__(self, ind) + except (IndexError, TypeError): + obj = self._index[ind] + ind = list.index(self, obj) + self._delindex(obj) + self._addindex(new_obj) + return list.__setitem__(ind, new_obj) + + def __setslice__(self, i, j, newItems): + _get = self.__getitem__ + _add = self._addindex + _del = self._delindex + newItems = list(newItems) + # remove indexing of items to remove + for ind in range(i, j): + _del(_get(ind)) + # add new indexing + if isinstance(newItems, IndexedList): + self._index.update(newItems._index) + else: + for obj in newItems: + _add(obj) + # replace items + return list.__setslice__(self, i, j, newItems) + + def append(self, obj): + self._addindex(obj) + return list.append(self, obj) + + def extend(self, newList): + newList = list(newList) + if isinstance(newList, IndexedList): + self._index.update(newList._index) + else: + _add = self._addindex + for obj in newList: + _add(obj) + return list.extend(self, newList) + + def insert(self, ind, new_obj): + # ensure that ind is a numeric index + try: + obj = list.__getitem__(self, ind) + except (IndexError, TypeError): + obj = self._index[ind] + ind = list.index(self, obj) + self._addindex(new_obj) + return list.insert(self, ind, new_obj) + + def pop(self, ind=-1): + # ensure that ind is a numeric index + try: + obj = list.__getitem__(self, ind) + except (IndexError, TypeError): + obj = self._index[ind] + ind = list.index(self, obj) + self._delindex(obj) + return list.pop(self, ind) + + def remove(self, ind_or_obj): + try: + obj = self._index[ind_or_obj] + ind = list.index(self, obj) + except KeyError: + ind = list.index(self, ind_or_obj) + obj = list.__getitem__(self, ind) + self._delindex(obj) + return list.remove(self, ind) + + +def _correctValInNode(outernode, tagname, value): + innernode = outernode.find(tag(tagname)) + if value is None and innernode is not None: + outernode.remove(innernode) + elif innernode is not None: + innernode.text = str(value) + elif value is not None: + outernode.append(E(tagname, str(value))) diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/xmlutil.py b/data/miniconda3/lib/python3.13/site-packages/collada/xmlutil.py new file mode 100644 index 0000000000000000000000000000000000000000..3fe020accc744f8de5108c8981979dbe69daad79 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/collada/xmlutil.py @@ -0,0 +1,122 @@ +import functools + +COLLADA_NS = 'http://www.collada.org/2005/11/COLLADASchema' +HAVE_LXML = False + +try: + from lxml import etree + HAVE_LXML = True +except ImportError: + from xml.etree import ElementTree as etree + +ET = etree + +try: + from functools import partial +except ImportError: + # fake it for pre-2.5 releases + def partial(func, tag): + return lambda *args, **kwargs: func(tag, *args, **kwargs) + +if HAVE_LXML: + from lxml.builder import E, ElementMaker + + def writeXML(xmlnode, fp): + xmlnode.write(fp, pretty_print=True) +else: + class ElementMaker(object): + def __init__(self, namespace=None, nsmap=None): + if namespace is not None: + self._namespace = '{' + namespace + '}' + else: + self._namespace = None + + def __call__(self, tag, *children, **attrib): + if self._namespace is not None and tag[0] != '{': + tag = self._namespace + tag + + elem = etree.Element(tag, attrib) + for item in children: + if isinstance(item, dict): + elem.attrib.update(item) + elif isinstance(item, str): + if len(elem): + elem[-1].tail = (elem[-1].tail or "") + item + else: + elem.text = (elem.text or "") + item + elif etree.iselement(item): + elem.append(item) + else: + raise TypeError("bad argument: %r" % item) + return elem + + def __getattr__(self, tag): + return functools.partial(self, tag) + + E = ElementMaker() + + if etree.VERSION[0:3] == '1.2': + # in etree < 1.3, this is a workaround for suppressing prefixes + + def fixtag(tag, namespaces): + import string + # given a decorated tag (of the form {uri}tag), return prefixed + # tag and namespace declaration, if any + if isinstance(tag, etree.QName): + tag = tag.text + namespace_uri, tag = string.split(tag[1:], "}", 1) + prefix = namespaces.get(namespace_uri) + if namespace_uri not in namespaces: + prefix = etree._namespace_map.get(namespace_uri) + if namespace_uri not in etree._namespace_map: + prefix = "ns%d" % len(namespaces) + namespaces[namespace_uri] = prefix + if prefix == "xml": + xmlns = None + else: + if prefix is not None: + nsprefix = ':' + prefix + else: + nsprefix = '' + xmlns = ("xmlns%s" % nsprefix, namespace_uri) + else: + xmlns = None + if prefix is not None: + prefix += ":" + else: + prefix = '' + + return "%s%s" % (prefix, tag), xmlns + + etree.fixtag = fixtag + etree._namespace_map[COLLADA_NS] = None + else: + # For etree > 1.3, use register_namespace function + etree.register_namespace('', COLLADA_NS) + + def indent(elem, level=0): + i = "\n" + level * " " + if len(elem): + if not elem.text or not elem.text.strip(): + elem.text = i + " " + if not elem.tail or not elem.tail.strip(): + elem.tail = i + for elem in elem: + indent(elem, level + 1) + if not elem.tail or not elem.tail.strip(): + elem.tail = i + else: + if level and (not elem.tail or not elem.tail.strip()): + elem.tail = i + + def writeXML(xmlnode, fp): + indent(xmlnode.getroot()) + xmlnode.write(fp) + + +def createElementTree(file): + if not HAVE_LXML: + return etree.ElementTree(element=None, file=file) + from lxml.etree import XMLParser, parse + parser = XMLParser(huge_tree=True) + return parse(file, parser=parser) diff --git a/data/miniconda3/lib/python3.13/site-packages/conda/__init__.py b/data/miniconda3/lib/python3.13/site-packages/conda/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8b3b3c9b4dfcf706be0c9e90bd08182e6e6b2940 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda/__init__.py @@ -0,0 +1,194 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""OS-agnostic, system-level binary package manager.""" + +from __future__ import annotations + +import os +import sys +from json import JSONEncoder # noqa: TID251 +from os.path import abspath, dirname +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from collections.abc import Iterable + from subprocess import Popen + from typing import Any + +try: + from ._version import __version__ +except ImportError: + # _version.py is only created after running `pip install` + try: + from setuptools_scm import get_version + + __version__ = get_version(root="..", relative_to=__file__) + except (ImportError, OSError, LookupError): + # ImportError: setuptools_scm isn't installed + # OSError: git isn't installed + # LookupError: setuptools_scm unable to detect version + # Conda abides by CEP-8 which specifies using CalVer, so the dev version is: + # YY.MM.MICRO.devN+gHASH[.dirty] + __version__ = "0.0.0.dev0+placeholder" + +__all__ = ( + "__name__", + "__version__", + "__author__", + "__email__", + "__license__", + "__summary__", + "__url__", + "CONDA_PACKAGE_ROOT", + "CondaError", + "CondaMultiError", + "CondaExitZero", + "conda_signal_handler", + "__copyright__", +) + +__name__ = "conda" +__author__ = "Anaconda, Inc." +__email__ = "conda@continuum.io" +__license__ = "BSD-3-Clause" +__copyright__ = "Copyright (c) 2012, Anaconda, Inc." +__summary__ = __doc__ +__url__ = "https://github.com/conda/conda" + +if os.getenv("CONDA_ROOT") is None: + os.environ["CONDA_ROOT"] = sys.prefix + +CONDA_PACKAGE_ROOT = abspath(dirname(__file__)) +"""The conda package directory.""" + +CONDA_SOURCE_ROOT = dirname(CONDA_PACKAGE_ROOT) +"""The path within which to find the conda package. + +If ``conda`` is statically installed this is the site-packages. If ``conda`` is an editable +install or otherwise uninstalled this is the git repo. +""" + + +class CondaError(Exception): + return_code: int = 1 + reportable: bool = False # Exception may be reported to core maintainers + + def __init__(self, message: str | None, caused_by: Any = None, **kwargs): + self.message = message or "" + self._kwargs = kwargs + self._caused_by = caused_by + super().__init__(message) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}: {self}" + + def __str__(self) -> str: + try: + return str(self.message) % self._kwargs + except Exception: + debug_message = "\n".join( + ( + "class: " + self.__class__.__name__, + "message:", + self.message, + "kwargs:", + str(self._kwargs), + "", + ) + ) + print(debug_message, file=sys.stderr) + raise + + def dump_map(self) -> dict[str, Any]: + result = {k: v for k, v in vars(self).items() if not k.startswith("_")} + result.update( + exception_type=str(type(self)), + exception_name=self.__class__.__name__, + message=str(self), + error=repr(self), + caused_by=repr(self._caused_by), + **self._kwargs, + ) + return result + + +class CondaMultiError(CondaError): + def __init__(self, errors: Iterable[CondaError]): + self.errors = errors + super().__init__(None) + + def __repr__(self) -> str: + errs = [] + for e in self.errors: + if isinstance(e, EnvironmentError) and not isinstance(e, CondaError): + errs.append(str(e)) + else: + # We avoid Python casting this back to a str() + # by using e.__repr__() instead of repr(e) + # https://github.com/scrapy/cssselect/issues/34 + errs.append(e.__repr__()) + res = "\n".join(errs) + return res + + def __str__(self) -> str: + return "\n".join(str(e) for e in self.errors) + "\n" + + def dump_map(self) -> dict[str, str | tuple[str, ...]]: + return dict( + exception_type=str(type(self)), + exception_name=self.__class__.__name__, + errors=tuple(error.dump_map() for error in self.errors), + error="Multiple Errors Encountered.", + ) + + def contains(self, exception_class: BaseException | tuple[BaseException]) -> bool: + return any(isinstance(e, exception_class) for e in self.errors) + + +class CondaExitZero(CondaError): + return_code = 0 + + +ACTIVE_SUBPROCESSES: Iterable[Popen] = set() + + +def conda_signal_handler(signum: int, frame: Any): + # This function is in the base __init__.py so that it can be monkey-patched by other code + # if downstream conda users so choose. The biggest danger of monkey-patching is that + # unlink/link transactions don't get rolled back if interrupted mid-transaction. + for p in ACTIVE_SUBPROCESSES: + if p.poll() is None: + p.send_signal(signum) + + from .exceptions import CondaSignalInterrupt + + raise CondaSignalInterrupt(signum) + + +def _default(self, obj): + from frozendict import frozendict + + from .deprecations import deprecated + + if isinstance(obj, frozendict): + deprecated.topic( + "26.3", + "26.9", + topic="Monkey-patching `json.JSONEncoder` to support `frozendict`", + addendum="Use `conda.common.serialize.json.CondaJSONEncoder` instead.", + ) + return dict(obj) + elif hasattr(obj, "to_json"): + deprecated.topic( + "26.3", + "26.9", + topic="Monkey-patching `json.JSONEncoder` to support `obj.to_json()`", + addendum="Use `conda.common.serialize.json.CondaJSONEncoder` instead.", + ) + return obj.to_json() + return _default.default(obj) + + +# FUTURE: conda 26.3, remove the following monkey patching +_default.default = JSONEncoder().default +JSONEncoder.default = _default diff --git a/data/miniconda3/lib/python3.13/site-packages/conda/__main__.py b/data/miniconda3/lib/python3.13/site-packages/conda/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..791e8e9cdbab3f17320b9f900dca2ebfdfcd03a4 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda/__main__.py @@ -0,0 +1,9 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Conda as a module entry point.""" + +import sys + +from .cli import main + +sys.exit(main()) diff --git a/data/miniconda3/lib/python3.13/site-packages/conda/_vendor.py b/data/miniconda3/lib/python3.13/site-packages/conda/_vendor.py new file mode 100644 index 0000000000000000000000000000000000000000..7d6e4b982021a48c7dcbcdfc380ee38b208b2fde --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda/_vendor.py @@ -0,0 +1,5 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +from .deprecations import deprecated + +deprecated.module("25.9", "26.3", addendum="Conda no longer vendors dependencies.") diff --git a/data/miniconda3/lib/python3.13/site-packages/conda/_version.py b/data/miniconda3/lib/python3.13/site-packages/conda/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..633d6cf44910bd38e8190c3bfdaf6d9b15c88277 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda/_version.py @@ -0,0 +1,34 @@ +# file generated by setuptools-scm +# don't change, don't track in version control + +__all__ = [ + "__version__", + "__version_tuple__", + "version", + "version_tuple", + "__commit_id__", + "commit_id", +] + +TYPE_CHECKING = False +if TYPE_CHECKING: + from typing import Tuple + from typing import Union + + VERSION_TUPLE = Tuple[Union[int, str], ...] + COMMIT_ID = Union[str, None] +else: + VERSION_TUPLE = object + COMMIT_ID = object + +version: str +__version__: str +__version_tuple__: VERSION_TUPLE +version_tuple: VERSION_TUPLE +commit_id: COMMIT_ID +__commit_id__: COMMIT_ID + +__version__ = version = '26.1.1' +__version_tuple__ = version_tuple = (26, 1, 1) + +__commit_id__ = commit_id = None diff --git a/data/miniconda3/lib/python3.13/site-packages/conda/activate.py b/data/miniconda3/lib/python3.13/site-packages/conda/activate.py new file mode 100644 index 0000000000000000000000000000000000000000..0fcb5c59e2507bc8a88d3715a79a5599d85b8b21 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda/activate.py @@ -0,0 +1,1158 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Conda activate and deactivate logic. + +Implementation for all shell interface logic exposed via +`conda shell.* [activate|deactivate|reactivate|hook|commands]`. This includes a custom argument +parser, an abstract shell class, and special path handling for Windows. + +See conda.cli.main.main_sourced for the entry point into this module. +""" + +from __future__ import annotations + +import abc +import os +import re +import sys +from logging import getLogger +from os.path import ( + abspath, + basename, + dirname, + exists, + expanduser, + expandvars, + isdir, + join, +) +from pathlib import Path +from typing import TYPE_CHECKING + +# Since we have to have configuration context here, anything imported by +# conda.base.context is fair game, but nothing more. +from . import CONDA_PACKAGE_ROOT +from .auxlib.compat import Utf8NamedTemporaryFile +from .base.constants import ( + CONDA_ENV_VARS_UNSET_VAR, + PACKAGE_ENV_VARS_DIR, + PREFIX_STATE_FILE, + RESERVED_ENV_VARS, +) +from .base.context import context, locate_prefix_by_name +from .common.compat import on_win +from .common.path import path_identity as _path_identity +from .common.path import paths_equal, unix_path_to_win, win_path_to_unix +from .common.serialize import json +from .deprecations import deprecated +from .exceptions import ActivateHelp, ArgumentError, DeactivateHelp, GenericHelp + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable + +log = getLogger(__name__) + + +BUILTIN_COMMANDS = { + "activate": ActivateHelp(), + "deactivate": DeactivateHelp(), + "hook": GenericHelp("hook"), + "commands": GenericHelp("commands"), + "reactivate": GenericHelp("reactivate"), +} + + +class _Activator(metaclass=abc.ABCMeta): + # Activate and deactivate have three tasks + # 1. Set and unset environment variables + # 2. Execute/source activate.d/deactivate.d scripts + # 3. Update the command prompt + # + # Shells should also use 'reactivate' following conda's install, update, and + # remove/uninstall commands. + # + # All core logic is in build_activate() or build_deactivate(), and is independent of + # shell type. Each returns a map containing the keys: + # export_vars + # unset_var + # activate_scripts + # deactivate_scripts + # + # The value of the CONDA_PROMPT_MODIFIER environment variable holds conda's contribution + # to the command prompt. + # + # To implement support for a new shell, ideally one would only need to add shell-specific + # information to the __init__ method of this class. + + # The following instance variables must be defined by each implementation. + pathsep_join: str + sep: str + path_conversion: Callable[ + [str | Iterable[str] | None], str | tuple[str, ...] | None + ] + script_extension: str + + tempfile_extension: str | None + """Temporary file's extension, None writes to stdout instead.""" + command_join: str + + unset_var_tmpl: str + export_var_tmpl: str + path_var_tmpl: str + set_var_tmpl: str + run_script_tmpl: str + + hook_source_path: Path | None + inline_hook_source: bool + + needs_line_ending_fix: bool + + def __init__(self, arguments=None): + self._raw_arguments = arguments + + def get_export_unset_vars(self, export_metavars=True, **kwargs): + """ + :param export_metavars: whether to export `conda_exe_vars` meta variables. + :param kwargs: environment variables to export. + .. if you pass and set any other variable to None, then it + emits it to the dict with a value of None. + + :return: A dict of env vars to export ordered the same way as kwargs. + And a list of env vars to unset. + """ + unset_vars = [] + export_vars = {} + + # split provided environment variables into exports vs unsets + for name, value in kwargs.items(): + if value is None: + unset_vars.append(name) + else: + export_vars[name] = value + + if export_metavars: + # split meta variables into exports vs unsets + for name, value in context.conda_exe_vars_dict.items(): + if value is None: + unset_vars.append(name) + elif "/" in value or "\\" in value: + export_vars[name] = self.path_conversion(value) + else: + export_vars[name] = value + else: + # unset all meta variables + unset_vars.extend(context.conda_exe_vars_dict) + + # normalize case if requested + if context.envvars_force_uppercase: + export_vars = {name.upper(): value for name, value in export_vars.items()} + unset_vars = [name.upper() for name in unset_vars] + + return export_vars, unset_vars + + def _finalize(self, commands, ext): + commands = (*commands, "") # add terminating newline + content = self.command_join.join(commands) + + # Normalize line endings for Unix shells on Windows + if on_win and self.path_conversion == win_path_to_unix: + content = content.replace("\r\n", "\n") + + if ext is None: + return content + elif ext: + with Utf8NamedTemporaryFile("w+", suffix=ext, delete=False) as tf: + # the default mode is 'w+b', and universal new lines don't work in that mode + tf.write(content) + return tf.name + else: + raise NotImplementedError() + + def activate(self): + if self.stack: + builder_result = self.build_stack(self.env_name_or_prefix) + else: + builder_result = self.build_activate(self.env_name_or_prefix) + return self._finalize( + self._yield_commands(builder_result), self.tempfile_extension + ) + + def deactivate(self): + return self._finalize( + self._yield_commands(self.build_deactivate()), self.tempfile_extension + ) + + def reactivate(self): + return self._finalize( + self._yield_commands(self.build_reactivate()), self.tempfile_extension + ) + + @deprecated.argument("25.9", "26.3", "auto_activate_base", rename="auto_activate") + def hook(self, auto_activate: bool | None = None) -> str: + builder: list[str] = [] + if preamble := self._hook_preamble(): + builder.append(preamble) + if self.hook_source_path: + if self.inline_hook_source: + builder.append(self.hook_source_path.read_text()) + else: + builder.append(self.run_script_tmpl % self.hook_source_path) + if auto_activate is None and context.auto_activate or auto_activate: + builder.append(f"conda activate '{context.default_activation_env}'\n") + postamble = self._hook_postamble() + if postamble is not None: + builder.append(postamble) + return "\n".join(builder) + + def execute(self): + # return value meant to be written to stdout + self._parse_and_set_args() + + # invoke pre/post commands, see conda.cli.conda_argparse.do_call + context.plugin_manager.invoke_pre_commands(self.command) + response = getattr(self, self.command)() + context.plugin_manager.invoke_post_commands(self.command) + return response + + def template_unset_var(self, key: str) -> str: + return self.unset_var_tmpl % key + + def template_export_var(self, key: str, value: str) -> str: + return self.export_var_tmpl % (key, value) + + def template_path_var(self, key: str, value: str) -> str: + return self.path_var_tmpl % (key, value) + + def _hook_preamble(self) -> str | None: + result = [] + for key, value in context.conda_exe_vars_dict.items(): + if value is None: + result.append(self.template_unset_var(key)) + elif {"/", "\\"}.intersection(value): + result.append(self.template_path_var(key, value)) + else: + result.append(self.template_export_var(key, value)) + if result: + return self.command_join.join(result) + self.command_join + return None + + def _hook_postamble(self) -> str | None: + return None + + def _parse_and_set_args(self) -> None: + command, *arguments = self._raw_arguments or [None] + help_flags = ("-h", "--help", "/?") + non_help_args = tuple(arg for arg in arguments if arg not in help_flags) + help_requested = len(arguments) != len(non_help_args) + remainder_args = list(arg for arg in non_help_args if arg and arg != command) + + if command not in BUILTIN_COMMANDS: + raise ArgumentError( + "'activate', 'deactivate', 'hook', 'commands', or 'reactivate' " + "command must be given." + (f", not '{command}'." if command else ".") + ) + elif help_requested: + raise BUILTIN_COMMANDS[command] + + if command.endswith("activate") or command == "hook": + try: + dev_idx = remainder_args.index("--dev") + except ValueError: + context.dev = False + else: + del remainder_args[dev_idx] + context.dev = True + + if command == "activate": + self.stack = context.auto_stack and context.shlvl <= context.auto_stack + try: + stack_idx = remainder_args.index("--stack") + except ValueError: + stack_idx = -1 + try: + no_stack_idx = remainder_args.index("--no-stack") + except ValueError: + no_stack_idx = -1 + if stack_idx >= 0 and no_stack_idx >= 0: + raise ArgumentError( + "cannot specify both --stack and --no-stack to " + command + ) + if stack_idx >= 0: + self.stack = True + del remainder_args[stack_idx] + if no_stack_idx >= 0: + self.stack = False + del remainder_args[no_stack_idx] + if len(remainder_args) > 1: + raise ArgumentError( + command + + " does not accept more than one argument:\n" + + str(remainder_args) + + "\n" + ) + if remainder_args: + self.env_name_or_prefix = remainder_args[0] + else: + self.env_name_or_prefix = context.default_activation_env + elif remainder_args: + raise ArgumentError( + f"{command} does not accept arguments\nremainder_args: {remainder_args}\n" + ) + + self.command = command + + def _yield_commands(self, cmds_dict): + for key, value in sorted(cmds_dict.get("export_path", {}).items()): + yield self.export_var_tmpl % (key, value) + + for script in cmds_dict.get("deactivate_scripts", ()): + yield self.run_script_tmpl % script + + for key in cmds_dict.get("unset_vars", ()): + yield self.unset_var_tmpl % key + + for key, value in cmds_dict.get("set_vars", {}).items(): + yield self.set_var_tmpl % (key, value) + + for key, value in cmds_dict.get("export_vars", {}).items(): + yield self.export_var_tmpl % (key, value) + + for script in cmds_dict.get("activate_scripts", ()): + yield self.run_script_tmpl % script + + def build_activate(self, env_name_or_prefix): + return self._build_activate_stack(env_name_or_prefix, False) + + def build_stack(self, env_name_or_prefix): + return self._build_activate_stack(env_name_or_prefix, True) + + def _build_activate_stack(self, env_name_or_prefix, stack): + # get environment prefix + if re.search(r"\\|/", env_name_or_prefix): + prefix = expand(env_name_or_prefix) + if not isdir(join(prefix, "conda-meta")): + from .exceptions import EnvironmentLocationNotFound + + raise EnvironmentLocationNotFound(prefix) + else: + prefix = locate_prefix_by_name(env_name_or_prefix) + + # get prior shlvl and prefix + old_conda_shlvl = int(os.getenv("CONDA_SHLVL", "").strip() or 0) + old_conda_prefix = os.getenv("CONDA_PREFIX") + + # if the prior active prefix is this prefix we are actually doing a reactivate + if old_conda_prefix == prefix and old_conda_shlvl > 0: + return self.build_reactivate() + + activate_scripts = self._get_activate_scripts(prefix) + conda_shlvl = old_conda_shlvl + 1 + conda_default_env = self._default_env(prefix) + conda_prompt_modifier = self._prompt_modifier(prefix, conda_default_env) + env_vars = { + name: value + for name, value in self._get_environment_env_vars(prefix).items() + if value != CONDA_ENV_VARS_UNSET_VAR + } + + # get clobbered environment variables + clobber_vars = set(env_vars).intersection(os.environ) + overwritten_clobber_vars = [ + clobber_var + for clobber_var in clobber_vars + if os.getenv(clobber_var) != env_vars[clobber_var] + ] + if overwritten_clobber_vars: + print( + "WARNING: overwriting environment variables set in the machine", + file=sys.stderr, + ) + print(f"overwriting variable {overwritten_clobber_vars}", file=sys.stderr) + for name in clobber_vars: + env_vars[f"__CONDA_SHLVL_{old_conda_shlvl}_{name}"] = os.getenv(name) + + if old_conda_shlvl == 0: + export_vars, unset_vars = self.get_export_unset_vars( + PATH=self.pathsep_join(self._add_prefix_to_path(prefix)), + CONDA_PREFIX=prefix, + CONDA_SHLVL=conda_shlvl, + CONDA_DEFAULT_ENV=conda_default_env, + CONDA_PROMPT_MODIFIER=conda_prompt_modifier, + **env_vars, + ) + deactivate_scripts = () + elif stack: + export_vars, unset_vars = self.get_export_unset_vars( + PATH=self.pathsep_join(self._add_prefix_to_path(prefix)), + CONDA_PREFIX=prefix, + CONDA_SHLVL=conda_shlvl, + CONDA_DEFAULT_ENV=conda_default_env, + CONDA_PROMPT_MODIFIER=conda_prompt_modifier, + **env_vars, + **{ + f"CONDA_PREFIX_{old_conda_shlvl}": old_conda_prefix, + f"CONDA_STACKED_{conda_shlvl}": "true", + }, + ) + deactivate_scripts = () + else: + export_vars, unset_vars = self.get_export_unset_vars( + PATH=self.pathsep_join( + self._replace_prefix_in_path(old_conda_prefix, prefix) + ), + CONDA_PREFIX=prefix, + CONDA_SHLVL=conda_shlvl, + CONDA_DEFAULT_ENV=conda_default_env, + CONDA_PROMPT_MODIFIER=conda_prompt_modifier, + **env_vars, + **{ + f"CONDA_PREFIX_{old_conda_shlvl}": old_conda_prefix, + }, + ) + deactivate_scripts = self._get_deactivate_scripts(old_conda_prefix) + + set_vars = {} + if context.changeps1: + self._update_prompt(set_vars, conda_prompt_modifier) + + return { + "unset_vars": unset_vars, + "set_vars": set_vars, + "export_vars": export_vars, + "deactivate_scripts": deactivate_scripts, + "activate_scripts": activate_scripts, + } + + def build_deactivate(self): + self._deactivate = True + # query environment + old_conda_prefix = os.getenv("CONDA_PREFIX") + old_conda_shlvl = int(os.getenv("CONDA_SHLVL", "").strip() or 0) + if not old_conda_prefix or old_conda_shlvl < 1: + # no active environment, so cannot deactivate; do nothing + return { + "unset_vars": (), + "set_vars": {}, + "export_vars": {}, + "deactivate_scripts": (), + "activate_scripts": (), + } + deactivate_scripts = self._get_deactivate_scripts(old_conda_prefix) + old_conda_environment_env_vars = self._get_environment_env_vars( + old_conda_prefix + ) + + new_conda_shlvl = old_conda_shlvl - 1 + set_vars = {} + if old_conda_shlvl == 1: + new_path = self.pathsep_join( + self._remove_prefix_from_path(old_conda_prefix) + ) + # You might think that you can remove the CONDA_EXE vars with export_metavars=False + # here so that "deactivate means deactivate" but you cannot since the conda shell + # scripts still refer to them and they only set them once at the top. We could change + # that though, the conda() shell function could set them instead of doing it at the + # top. This would be *much* cleaner. I personally cannot abide that I have + # deactivated conda and anything at all in my env still references it (apart from the + # shell script, we need something I suppose!) + export_vars, unset_vars = self.get_export_unset_vars( + CONDA_PREFIX=None, + CONDA_SHLVL=new_conda_shlvl, + CONDA_DEFAULT_ENV=None, + CONDA_PROMPT_MODIFIER=None, + ) + conda_prompt_modifier = "" + activate_scripts = () + export_path = {"PATH": new_path} + else: + if old_conda_shlvl <= 1: + raise ValueError("'old_conda_shlvl' must be 2 or larger") + new_prefix = os.getenv("CONDA_PREFIX_%d" % new_conda_shlvl) + if not new_prefix: + raise ValueError( + "This should not happen! You may have non-consecutive `CONDA_PREFIX_ " + "environment variables. Try restarting your shell and, if it persists, " + "check your shell profile to see what may be adding a faulty " + "CONDA_PREFIX_ environment variable." + ) + conda_default_env = self._default_env(new_prefix) + conda_prompt_modifier = self._prompt_modifier(new_prefix, conda_default_env) + new_conda_environment_env_vars = self._get_environment_env_vars(new_prefix) + + old_prefix_stacked = "CONDA_STACKED_%d" % old_conda_shlvl in os.environ + new_path = "" + + unset_vars = ["CONDA_PREFIX_%d" % new_conda_shlvl] + if old_prefix_stacked: + new_path = self.pathsep_join( + self._remove_prefix_from_path(old_conda_prefix) + ) + unset_vars.append("CONDA_STACKED_%d" % old_conda_shlvl) + else: + new_path = self.pathsep_join( + self._replace_prefix_in_path(old_conda_prefix, new_prefix) + ) + + export_vars, unset_vars2 = self.get_export_unset_vars( + CONDA_PREFIX=new_prefix, + CONDA_SHLVL=new_conda_shlvl, + CONDA_DEFAULT_ENV=conda_default_env, + CONDA_PROMPT_MODIFIER=conda_prompt_modifier, + **new_conda_environment_env_vars, + ) + unset_vars += unset_vars2 + export_path = {"PATH": new_path} + activate_scripts = self._get_activate_scripts(new_prefix) + + if context.changeps1: + self._update_prompt(set_vars, conda_prompt_modifier) + + # Handle environment variables that need to be unset during deactivation + for env_var in old_conda_environment_env_vars.keys(): + if save_value := os.getenv(f"__CONDA_SHLVL_{new_conda_shlvl}_{env_var}"): + export_vars[env_var] = save_value + else: + # Apply case conversion for environment variables that need to be unset + if context.envvars_force_uppercase: + unset_vars.append(env_var.upper()) + else: + unset_vars.append(env_var) + + return { + "unset_vars": unset_vars, + "set_vars": set_vars, + "export_vars": export_vars, + "export_path": export_path, + "deactivate_scripts": deactivate_scripts, + "activate_scripts": activate_scripts, + } + + def build_reactivate(self): + self._reactivate = True + conda_prefix = os.getenv("CONDA_PREFIX") + conda_shlvl = int(os.getenv("CONDA_SHLVL", "").strip() or 0) + if not conda_prefix or conda_shlvl < 1: + # no active environment, so cannot reactivate; do nothing + return { + "unset_vars": [], + "set_vars": {}, + "export_vars": {}, + "deactivate_scripts": (), + "activate_scripts": (), + } + conda_default_env = os.getenv( + "CONDA_DEFAULT_ENV", self._default_env(conda_prefix) + ) + new_path = self.pathsep_join( + self._replace_prefix_in_path(conda_prefix, conda_prefix) + ) + set_vars = {} + conda_prompt_modifier = self._prompt_modifier(conda_prefix, conda_default_env) + if context.changeps1: + self._update_prompt(set_vars, conda_prompt_modifier) + + export_vars, unset_vars = self.get_export_unset_vars( + PATH=new_path, + CONDA_SHLVL=conda_shlvl, + CONDA_PROMPT_MODIFIER=self._prompt_modifier( + conda_prefix, conda_default_env + ), + ) + + # environment variables are set only to aid transition from conda 4.3 to conda 4.4 + return { + "unset_vars": unset_vars, + "set_vars": set_vars, + "export_vars": export_vars, + "deactivate_scripts": self._get_deactivate_scripts(conda_prefix), + "activate_scripts": self._get_activate_scripts(conda_prefix), + } + + def _get_starting_path_list(self): + # For isolation, running the conda test suite *without* env. var. inheritance + # every so often is a good idea. We should probably make this a pytest fixture + # along with one that tests both hardlink-only and copy-only, but before that + # conda's testsuite needs to be a lot faster! + clean_paths = { + "darwin": "/usr/bin:/bin:/usr/sbin:/sbin", + # You may think 'let us do something more clever here and interpolate + # `%windir%`' but the point here is the the whole env. is cleaned out + "win32": "C:\\Windows\\system32;" + "C:\\Windows;" + "C:\\Windows\\System32\\Wbem;" + "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\", + } + path = os.getenv( + "PATH", + clean_paths[sys.platform] if sys.platform in clean_paths else "/usr/bin", + ) + path_split = path.split(os.pathsep) + return path_split + + def _get_path_dirs(self, prefix): + if on_win: # pragma: unix no cover + yield prefix.rstrip(self.sep) + + # We need to stat(2) for possible environments because + # tests can't be told where to look! + # + # mingw-w64 is a legacy variant used by m2w64-* packages + # + # We could include clang32 and mingw32 variants + variants = [] + for variant in ["ucrt64", "clang64", "mingw64", "clangarm64"]: + path = self.sep.join((prefix, "Library", variant)) + + # MSYS2 /c/ + # cygwin /cygdrive/c/ + if re.match("^(/[A-Za-z]/|/cygdrive/[A-Za-z]/).*", prefix): + path = unix_path_to_win(path, prefix) + + if isdir(path): + variants.append(variant) + + if len(variants) > 1: + print( + f"WARNING: {prefix}: {variants} MSYS2 envs exist: please check your dependencies", + file=sys.stderr, + ) + print( + f"WARNING: conda list -n {self._default_env(prefix)}", + file=sys.stderr, + ) + + if variants: + yield self.sep.join((prefix, "Library", variants[0], "bin")) + + yield self.sep.join((prefix, "Library", "mingw-w64", "bin")) + yield self.sep.join((prefix, "Library", "usr", "bin")) + yield self.sep.join((prefix, "Library", "bin")) + yield self.sep.join((prefix, "Scripts")) + yield self.sep.join((prefix, "bin")) + else: + yield self.sep.join((prefix, "bin")) + + def _add_prefix_to_path(self, prefix, starting_path_dirs=None): + prefix = self.path_conversion(prefix) + if starting_path_dirs is None: + path_list = list(self.path_conversion(self._get_starting_path_list())) + else: + path_list = list(self.path_conversion(starting_path_dirs)) + + # If this is the first time we're activating an environment, we need to ensure that + # the condabin directory is included in the path list. + # Under normal conditions, if the shell hook is working correctly, this should + # never trigger. + old_conda_shlvl = int(os.getenv("CONDA_SHLVL", "").strip() or 0) + if not old_conda_shlvl and not any(p.endswith("condabin") for p in path_list): + condabin_dir = self.path_conversion(join(context.conda_prefix, "condabin")) + path_list.insert(0, condabin_dir) + + path_list[0:0] = list(self.path_conversion(self._get_path_dirs(prefix))) + return tuple(path_list) + + def _remove_prefix_from_path(self, prefix, starting_path_dirs=None): + return self._replace_prefix_in_path(prefix, None, starting_path_dirs) + + def _replace_prefix_in_path(self, old_prefix, new_prefix, starting_path_dirs=None): + old_prefix = self.path_conversion(old_prefix) + new_prefix = self.path_conversion(new_prefix) + if starting_path_dirs is None: + path_list = list(self.path_conversion(self._get_starting_path_list())) + else: + path_list = list(self.path_conversion(starting_path_dirs)) + + def index_of_path(paths, test_path): + for q, path in enumerate(paths): + if paths_equal(path, test_path): + return q + return None + + if old_prefix is not None: + prefix_dirs = tuple(self._get_path_dirs(old_prefix)) + first_idx = index_of_path(path_list, prefix_dirs[0]) + if first_idx is None: + first_idx = 0 + else: + prefix_dirs_idx = len(prefix_dirs) - 1 + last_idx = None + while last_idx is None and prefix_dirs_idx > -1: + last_idx = index_of_path(path_list, prefix_dirs[prefix_dirs_idx]) + if last_idx is None: + print( + f"Did not find path entry {prefix_dirs[prefix_dirs_idx]}", + file=sys.stderr, + ) + prefix_dirs_idx = prefix_dirs_idx - 1 + # this compensates for an extra Library/bin dir entry from the interpreter on + # windows. If that entry isn't being added, it should have no effect. + library_bin_dir = self.path_conversion( + self.sep.join((sys.prefix, "Library", "bin")) + ) + if path_list[last_idx + 1] == library_bin_dir: + last_idx += 1 + del path_list[first_idx : last_idx + 1] + else: + first_idx = 0 + + if new_prefix is not None: + path_list[first_idx:first_idx] = list(self._get_path_dirs(new_prefix)) + + return tuple(path_list) + + def _update_prompt(self, set_vars, conda_prompt_modifier): + pass + + def _default_env(self, prefix): + if paths_equal(prefix, context.root_prefix): + return "base" + return basename(prefix) if basename(dirname(prefix)) == "envs" else prefix + + def _prompt_modifier(self, prefix, conda_default_env): + if context.changeps1: + # Get current environment and prompt stack + env_stack = [] + prompt_stack = [] + old_shlvl = int(os.getenv("CONDA_SHLVL", "0").rstrip()) + for i in range(1, old_shlvl + 1): + if i == old_shlvl: + env_i = self._default_env(os.getenv("CONDA_PREFIX", "")) + else: + env_i = self._default_env( + os.getenv(f"CONDA_PREFIX_{i}", "").rstrip() + ) + stacked_i = bool(os.getenv(f"CONDA_STACKED_{i}", "").rstrip()) + env_stack.append(env_i) + if not stacked_i: + prompt_stack = prompt_stack[0:-1] + prompt_stack.append(env_i) + + # Modify prompt stack according to pending operation + deactivate = getattr(self, "_deactivate", False) + reactivate = getattr(self, "_reactivate", False) + if deactivate: + prompt_stack = prompt_stack[0:-1] + env_stack = env_stack[0:-1] + stacked = bool(os.getenv(f"CONDA_STACKED_{old_shlvl}", "").rstrip()) + if not stacked and env_stack: + prompt_stack.append(env_stack[-1]) + elif reactivate: + pass + else: + stack = getattr(self, "stack", False) + if not stack: + prompt_stack = prompt_stack[0:-1] + prompt_stack.append(conda_default_env) + + conda_stacked_env = ",".join(prompt_stack[::-1]) + + return context.env_prompt.format( + default_env=conda_default_env, + stacked_env=conda_stacked_env, + prefix=prefix, + name=basename(prefix), + ) + else: + return "" + + def _get_activate_scripts(self, prefix): + _script_extension = self.script_extension + se_len = -len(_script_extension) + try: + paths = ( + entry.path + for entry in os.scandir(join(prefix, "etc", "conda", "activate.d")) + ) + except OSError: + return () + return self.path_conversion( + sorted(p for p in paths if p[se_len:] == _script_extension) + ) + + def _get_deactivate_scripts(self, prefix): + _script_extension = self.script_extension + se_len = -len(_script_extension) + try: + paths = ( + entry.path + for entry in os.scandir(join(prefix, "etc", "conda", "deactivate.d")) + ) + except OSError: + return () + return self.path_conversion( + sorted((p for p in paths if p[se_len:] == _script_extension), reverse=True) + ) + + def _get_environment_env_vars(self, prefix): + env_vars_file = join(prefix, PREFIX_STATE_FILE) + pkg_env_var_dir = join(prefix, PACKAGE_ENV_VARS_DIR) + env_vars = {} + + # First get env vars from packages + if exists(pkg_env_var_dir): + for pkg_env_var_path in sorted( + entry.path for entry in os.scandir(pkg_env_var_dir) + ): + with open(pkg_env_var_path) as f: + env_vars.update(json.loads(f.read())) + + # Then get env vars from environment specification + if exists(env_vars_file): + with open(env_vars_file) as f: + prefix_state = json.loads(f.read()) + prefix_state_env_vars = prefix_state.get("env_vars", {}) + dup_vars = [ + ev for ev in env_vars.keys() if ev in prefix_state_env_vars.keys() + ] + for dup in dup_vars: + print( + "WARNING: duplicate env vars detected. Vars from the environment " + "will overwrite those from packages", + file=sys.stderr, + ) + print(f"variable {dup} duplicated", file=sys.stderr) + env_vars.update(prefix_state_env_vars) + + # Remove reserved environment variables and warn if they're being set + collect_reserved_vars = [] + for reserved in RESERVED_ENV_VARS: + if reserved in env_vars: + # Only warn if the variable is actually being set (not unset) + if env_vars[reserved] != CONDA_ENV_VARS_UNSET_VAR: + collect_reserved_vars.append(reserved) + # Remove from env_vars regardless + env_vars.pop(reserved) + + if collect_reserved_vars: + print_reserved_vars = ", ".join(collect_reserved_vars) + print( + f"WARNING: the configured environment variable(s) for prefix '{prefix}' " + f"are reserved and will be ignored: {print_reserved_vars}.\n\n" + f"Remove the invalid configuration with `conda env config vars unset " + f"-p {prefix} {' '.join(collect_reserved_vars)}`.\n", + file=sys.stderr, + ) + return env_vars + + +def expand(path): + return abspath(expanduser(expandvars(path))) + + +def backslash_to_forwardslash( + paths: str | Iterable[str] | None, +) -> str | tuple[str, ...] | None: + if paths is None: + return None + elif isinstance(paths, str): + return paths.replace("\\", "/") + else: + return tuple([path.replace("\\", "/") for path in paths]) + + +class PosixActivator(_Activator): + pathsep_join = ":".join + sep = "/" + path_conversion = staticmethod(win_path_to_unix if on_win else _path_identity) + script_extension = ".sh" + tempfile_extension = None # output to stdout + command_join = "\n" + needs_line_ending_fix = True + + # Using `unset %s` would cause issues for people running + # with shell flag -u set (error on unset). + unset_var_tmpl = "export %s=''" # unset %s + export_var_tmpl = "export %s='%s'" + path_var_tmpl = "export %s=\"$(cygpath '%s')\"" if on_win else export_var_tmpl + set_var_tmpl = "%s='%s'" + run_script_tmpl = ". \"`cygpath '%s'`\"" if on_win else '. "%s"' + + hook_source_path = Path( + CONDA_PACKAGE_ROOT, + "shell", + "etc", + "profile.d", + "conda.sh", + ) + inline_hook_source = True + + def _update_prompt(self, set_vars, conda_prompt_modifier): + ps1 = os.getenv("PS1", "") + if "POWERLINE_COMMAND" in ps1: + # Defer to powerline (https://github.com/powerline/powerline) if it's in use. + return + current_prompt_modifier = os.getenv("CONDA_PROMPT_MODIFIER") + if current_prompt_modifier: + ps1 = re.sub(re.escape(current_prompt_modifier), r"", ps1) + # Because we're using single-quotes to set shell variables, we need to handle the + # proper escaping of single quotes that are already part of the string. + # Best solution appears to be https://stackoverflow.com/a/1250279 + ps1 = ps1.replace("'", "'\"'\"'") + set_vars.update( + { + "PS1": conda_prompt_modifier + ps1, + } + ) + + +class CshActivator(_Activator): + pathsep_join = ":".join + sep = "/" + path_conversion = staticmethod(win_path_to_unix if on_win else _path_identity) + script_extension = ".csh" + tempfile_extension = None # output to stdout + command_join = ";\n" + needs_line_ending_fix = True + + unset_var_tmpl = "unsetenv %s" + export_var_tmpl = 'setenv %s "%s"' + path_var_tmpl = "setenv %s \"`cygpath '%s'`\"" if on_win else export_var_tmpl + set_var_tmpl = "set %s='%s'" + run_script_tmpl = "source \"`cygpath '%s'`\"" if on_win else 'source "%s"' + + hook_source_path = Path( + CONDA_PACKAGE_ROOT, + "shell", + "etc", + "profile.d", + "conda.csh", + ) + # TCSH/CSH removes newlines when doing command substitution (see `man tcsh`), + # source conda.csh directly and use line terminators to separate commands + inline_hook_source = False + + def _update_prompt(self, set_vars, conda_prompt_modifier): + prompt = os.getenv("prompt", "") + current_prompt_modifier = os.getenv("CONDA_PROMPT_MODIFIER") + if current_prompt_modifier: + prompt = re.sub(re.escape(current_prompt_modifier), r"", prompt) + set_vars.update( + { + "prompt": conda_prompt_modifier + prompt, + } + ) + + +class XonshActivator(_Activator): + pathsep_join = ";".join if on_win else ":".join + sep = "/" + path_conversion = staticmethod( + backslash_to_forwardslash if on_win else _path_identity + ) + # 'scripts' really refer to de/activation scripts, not scripts in the language per se + # xonsh can piggy-back activation scripts from other languages depending on the platform + script_extension = ".bat" if on_win else ".sh" + tempfile_extension = None # output to stdout + command_join = "\n" + needs_line_ending_fix = False + + unset_var_tmpl = "try:\n del $%s\nexcept KeyError:\n pass" + export_var_tmpl = "$%s = '%s'" + path_var_tmpl = export_var_tmpl + set_var_tmpl = export_var_tmpl + run_script_tmpl = ( + 'source-cmd --suppress-skip-message "%s"' + if on_win + else 'source-bash --suppress-skip-message -n "%s"' + ) + + hook_source_path = Path(CONDA_PACKAGE_ROOT, "shell", "conda.xsh") + inline_hook_source = True + + def template_path_var(self, key: str, value: str) -> str: + return self.path_var_tmpl % (key, self.path_conversion(value)) + + +class CmdExeActivator(_Activator): + pathsep_join = ";".join + sep = "\\" + path_conversion = staticmethod(_path_identity) + script_extension = ".bat" + tempfile_extension = ".env" + command_join = "\n" + needs_line_ending_fix = False + + # we are not generating a script to run but rather an INI style file + # with key=value pairs to set environment variables, key= to unset them, + # and _CONDA_SCRIPT=script pairs to run scripts + unset_var_tmpl = "%s=" + export_var_tmpl = "%s=%s" + path_var_tmpl = export_var_tmpl + set_var_tmpl = export_var_tmpl + run_script_tmpl = "_CONDA_SCRIPT=%s" + + hook_source_path = None + inline_hook_source = None + + def _update_prompt(self, set_vars, conda_prompt_modifier): + prompt = os.getenv("PROMPT", "") + current_prompt_modifier = os.getenv("CONDA_PROMPT_MODIFIER") + if current_prompt_modifier: + prompt = re.sub(re.escape(current_prompt_modifier), r"", prompt) + set_vars["PROMPT"] = conda_prompt_modifier + prompt + + def _hook_preamble(self) -> None: + # TODO: cmd.exe doesn't get a hook function? Or do we need to do something different? + # Like, for cmd.exe only, put a special directory containing only conda.bat on PATH? + pass + + +class CmdExeRunActivator(CmdExeActivator): + # CmdExeActivator writes an .env file by default; let's force in-memory output here + # so that we can embed the activation output directly into our wrapper script. + tempfile_extension = None + + unset_var_tmpl = 'SET "%s="' + export_var_tmpl = 'SET "%s=%s"' + path_var_tmpl = export_var_tmpl + set_var_tmpl = export_var_tmpl + # If any of these calls to the activation hook scripts fail, we want + # to exit the wrapper immediately and abort `conda run` right away. + run_script_tmpl = 'CALL "%s"\nIF %%ERRORLEVEL%% NEQ 0 EXIT /b %%ERRORLEVEL%%' + + +class FishActivator(_Activator): + pathsep_join = '" "'.join + sep = "/" + path_conversion = staticmethod(win_path_to_unix if on_win else _path_identity) + script_extension = ".fish" + tempfile_extension = None # output to stdout + command_join = ";\n" + needs_line_ending_fix = True + + unset_var_tmpl = "set -e %s || true" + export_var_tmpl = 'set -gx %s "%s"' + path_var_tmpl = 'set -gx %s (cygpath "%s")' if on_win else export_var_tmpl + set_var_tmpl = 'set -g %s "%s"' + run_script_tmpl = 'source "%s"' + + hook_source_path = Path( + CONDA_PACKAGE_ROOT, + "shell", + "etc", + "fish", + "conf.d", + "conda.fish", + ) + inline_hook_source = True + + +class PowerShellActivator(_Activator): + pathsep_join = ";".join if on_win else ":".join + sep = "\\" if on_win else "/" + path_conversion = staticmethod(_path_identity) + script_extension = ".ps1" + tempfile_extension = None # output to stdout + command_join = "\n" + needs_line_ending_fix = False + + unset_var_tmpl = "$Env:%s = $null" + export_var_tmpl = '$Env:%s = "%s"' + path_var_tmpl = export_var_tmpl + set_var_tmpl = export_var_tmpl + run_script_tmpl = '. "%s"' + + hook_source_path = Path( + CONDA_PACKAGE_ROOT, + "shell", + "condabin", + "conda-hook.ps1", + ) + inline_hook_source = True + + def _hook_preamble(self) -> str: + module_args = f"$CondaModuleArgs = @{{ChangePs1 = ${context.changeps1}}}" + return super()._hook_preamble() + module_args + self.command_join + + def _hook_postamble(self) -> str: + return "Remove-Variable CondaModuleArgs" + + +class JSONFormatMixin(_Activator): + """Returns the necessary values for activation as JSON, so that tools can use them.""" + + pathsep_join = list + tempfile_extension = None # output to stdout + command_join = list + + def _hook_preamble(self): + return context.conda_exe_vars_dict + + def _finalize(self, commands, ext): + merged = {} + for _cmds in commands: + merged.update(_cmds) + + commands = merged + if ext is None: + return json.dumps(commands, indent=2) + elif ext: + with Utf8NamedTemporaryFile("w+", suffix=ext, delete=False) as tf: + # the default mode is 'w+b', and universal new lines don't work in that mode + # command_join should account for that + json.dump(commands, tf) + return tf.name + else: + raise NotImplementedError() + + def _yield_commands(self, cmds_dict): + # TODO: _Is_ defining our own object shape here any better than + # just dumping the `cmds_dict`? + path = cmds_dict.get("export_path", {}) + export_vars = cmds_dict.get("export_vars", {}) + # treat PATH specially + if "PATH" in export_vars: + new_path = path.get("PATH", []) + new_path.extend(export_vars.pop("PATH")) + path["PATH"] = new_path + + yield { + "path": path, + "vars": { + "export": export_vars, + "unset": cmds_dict.get("unset_vars", ()), + "set": cmds_dict.get("set_vars", {}), + }, + "scripts": { + "activate": cmds_dict.get("activate_scripts", ()), + "deactivate": cmds_dict.get("deactivate_scripts", ()), + }, + } + + +activator_map: dict[str, type[_Activator]] = { + "posix": PosixActivator, + "ash": PosixActivator, + "bash": PosixActivator, + "dash": PosixActivator, + "zsh": PosixActivator, + "csh": CshActivator, + "tcsh": CshActivator, + "xonsh": XonshActivator, + "cmd.exe": CmdExeActivator, + "cmd.exe.run": CmdExeRunActivator, + "fish": FishActivator, + "powershell": PowerShellActivator, +} + +formatter_map = { + "json": JSONFormatMixin, +} + + +def _build_activator_cls(shell): + """Dynamically construct the activator class. + + Detect the base activator and any number of formatters (appended using '+' to the base name). + For example, `posix+json` (as in `conda shell.posix+json activate`) would use the + `PosixActivator` base class and add the `JSONFormatMixin`. + """ + shell_etc = shell.split("+") + activator, formatters = shell_etc[0], shell_etc[1:] + + bases = [activator_map[activator]] + for f in formatters: + bases.append(formatter_map[f]) + + cls = type("Activator", tuple(reversed(bases)), {}) + return cls diff --git a/data/miniconda3/lib/python3.13/site-packages/conda/api.py b/data/miniconda3/lib/python3.13/site-packages/conda/api.py new file mode 100644 index 0000000000000000000000000000000000000000..34bd5cef7c037eaf40ba760c6f3fecc143315a67 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda/api.py @@ -0,0 +1,501 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Collection of conda's high-level APIs.""" + +from .base.constants import DepsModifier as _DepsModifier +from .base.constants import UpdateModifier as _UpdateModifier +from .base.context import context +from .common.constants import NULL +from .core.package_cache_data import PackageCacheData as _PackageCacheData +from .core.prefix_data import PrefixData as _PrefixData +from .core.subdir_data import SubdirData as _SubdirData +from .models.channel import Channel + +DepsModifier = _DepsModifier +"""Flags to enable alternate handling of dependencies.""" + +UpdateModifier = _UpdateModifier +"""Flags to enable alternate handling for updates of existing packages in the environment.""" + + +class Solver: + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + A high-level API to conda's solving logic. Three public methods are provided to access a + solution in various forms. + + * :meth:`solve_final_state` + * :meth:`solve_for_diff` + * :meth:`solve_for_transaction` + + """ + + def __init__( + self, prefix, channels, subdirs=(), specs_to_add=(), specs_to_remove=() + ): + """ + **Beta** + + Args: + prefix (str): + The conda prefix / environment location for which the :class:`Solver` + is being instantiated. + channels (Sequence[:class:`Channel`]): + A prioritized list of channels to use for the solution. + subdirs (Sequence[str]): + A prioritized list of subdirs to use for the solution. + specs_to_add (set[:class:`MatchSpec`]): + The set of package specs to add to the prefix. + specs_to_remove (set[:class:`MatchSpec`]): + The set of package specs to remove from the prefix. + + """ + solver_backend = context.plugin_manager.get_cached_solver_backend() + self._internal = solver_backend( + prefix, channels, subdirs, specs_to_add, specs_to_remove + ) + + def solve_final_state( + self, + update_modifier=NULL, + deps_modifier=NULL, + prune=NULL, + ignore_pinned=NULL, + force_remove=NULL, + ): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Gives the final, solved state of the environment. + + Args: + deps_modifier (DepsModifier): + An optional flag indicating special solver handling for dependencies. The + default solver behavior is to be as conservative as possible with dependency + updates (in the case the dependency already exists in the environment), while + still ensuring all dependencies are satisfied. Options include + * NO_DEPS + * ONLY_DEPS + * UPDATE_DEPS + * UPDATE_DEPS_ONLY_DEPS + * FREEZE_INSTALLED + prune (bool): + If ``True``, the solution will not contain packages that were + previously brought into the environment as dependencies but are no longer + required as dependencies and are not user-requested. + ignore_pinned (bool): + If ``True``, the solution will ignore pinned package configuration + for the prefix. + force_remove (bool): + Forces removal of a package without removing packages that depend on it. + + Returns: + tuple[PackageRef]: + In sorted dependency order from roots to leaves, the package references for + the solved state of the environment. + + """ + return self._internal.solve_final_state( + update_modifier, deps_modifier, prune, ignore_pinned, force_remove + ) + + def solve_for_diff( + self, + update_modifier=NULL, + deps_modifier=NULL, + prune=NULL, + ignore_pinned=NULL, + force_remove=NULL, + force_reinstall=False, + ): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Gives the package references to remove from an environment, followed by + the package references to add to an environment. + + Args: + deps_modifier (DepsModifier): + See :meth:`solve_final_state`. + prune (bool): + See :meth:`solve_final_state`. + ignore_pinned (bool): + See :meth:`solve_final_state`. + force_remove (bool): + See :meth:`solve_final_state`. + force_reinstall (bool): + For requested specs_to_add that are already satisfied in the environment, + instructs the solver to remove the package and spec from the environment, + and then add it back--possibly with the exact package instance modified, + depending on the spec exactness. + + Returns: + tuple[PackageRef], tuple[PackageRef]: + A two-tuple of PackageRef sequences. The first is the group of packages to + remove from the environment, in sorted dependency order from leaves to roots. + The second is the group of packages to add to the environment, in sorted + dependency order from roots to leaves. + + """ + return self._internal.solve_for_diff( + update_modifier, + deps_modifier, + prune, + ignore_pinned, + force_remove, + force_reinstall, + ) + + def solve_for_transaction( + self, + update_modifier=NULL, + deps_modifier=NULL, + prune=NULL, + ignore_pinned=NULL, + force_remove=NULL, + force_reinstall=False, + ): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Gives an UnlinkLinkTransaction instance that can be used to execute the solution + on an environment. + + Args: + deps_modifier (DepsModifier): + See :meth:`solve_final_state`. + prune (bool): + See :meth:`solve_final_state`. + ignore_pinned (bool): + See :meth:`solve_final_state`. + force_remove (bool): + See :meth:`solve_final_state`. + force_reinstall (bool): + See :meth:`solve_for_diff`. + + Returns: + UnlinkLinkTransaction: + + """ + return self._internal.solve_for_transaction( + update_modifier, + deps_modifier, + prune, + ignore_pinned, + force_remove, + force_reinstall, + ) + + +class SubdirData: + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + High-level management and usage of repodata.json for subdirs. + """ + + def __init__(self, channel): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Args: + channel (str or Channel): + The target subdir for the instance. Must either be a url that includes a subdir + or a :obj:`Channel` that includes a subdir. e.g.: + * 'https://repo.anaconda.com/pkgs/main/linux-64' + * Channel('https://repo.anaconda.com/pkgs/main/linux-64') + * Channel('conda-forge/osx-64') + """ + channel = Channel(channel) + if not channel.subdir: + raise ValueError("SubdirData requires platform-aware Channel objects.") + self._internal = _SubdirData(channel) + + def query(self, package_ref_or_match_spec): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Run a query against this specific instance of repodata. + + Args: + package_ref_or_match_spec (PackageRef or MatchSpec or str): + Either an exact :obj:`PackageRef` to match against, or a :obj:`MatchSpec` + query object. A :obj:`str` will be turned into a :obj:`MatchSpec` automatically. + + Returns: + tuple[PackageRecord] + + """ + return tuple(self._internal.query(package_ref_or_match_spec)) + + @staticmethod + def query_all(package_ref_or_match_spec, channels=None, subdirs=None): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Run a query against all repodata instances in channel/subdir matrix. + + Args: + package_ref_or_match_spec (PackageRef or MatchSpec or str): + Either an exact :obj:`PackageRef` to match against, or a :obj:`MatchSpec` + query object. A :obj:`str` will be turned into a :obj:`MatchSpec` automatically. + channels (Iterable[Channel or str] or None): + An iterable of urls for channels or :obj:`Channel` objects. If None, will fall + back to context.channels. + subdirs (Iterable[str] or None): + If None, will fall back to context.subdirs. + + Returns: + tuple[PackageRecord] + + """ + return tuple( + _SubdirData.query_all(package_ref_or_match_spec, channels, subdirs) + ) + + def iter_records(self): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Returns: + Iterable[PackageRecord]: A generator over all records contained in the repodata.json + instance. Warning: this is a generator that is exhausted on first use. + + """ + return self._internal.iter_records() + + def reload(self): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Update the instance with new information. Backing information (i.e. repodata.json) + is lazily downloaded/loaded on first use by the other methods of this class. You + should only use this method if you are *sure* you have outdated data. + + Returns: + SubdirData + + """ + self._internal = self._internal.reload() + return self + + +class PackageCacheData: + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + High-level management and usage of package caches. + """ + + def __init__(self, pkgs_dir): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Args: + pkgs_dir (str): + """ + self._internal = _PackageCacheData(pkgs_dir) + + def get(self, package_ref, default=NULL): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Args: + package_ref (PackageRef): + A :obj:`PackageRef` instance representing the key for the + :obj:`PackageCacheRecord` being sought. + default: The default value to return if the record does not exist. If not + specified and no record exists, :exc:`KeyError` is raised. + + Returns: + PackageCacheRecord + + """ + return self._internal.get(package_ref, default) + + def query(self, package_ref_or_match_spec): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Run a query against this specific package cache instance. + + Args: + package_ref_or_match_spec (PackageRef or MatchSpec or str): + Either an exact :obj:`PackageRef` to match against, or a :obj:`MatchSpec` + query object. A :obj:`str` will be turned into a :obj:`MatchSpec` automatically. + + Returns: + tuple[PackageCacheRecord] + + """ + return tuple(self._internal.query(package_ref_or_match_spec)) + + @staticmethod + def query_all(package_ref_or_match_spec, pkgs_dirs=None): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Run a query against all package caches. + + Args: + package_ref_or_match_spec (PackageRef or MatchSpec or str): + Either an exact :obj:`PackageRef` to match against, or a :obj:`MatchSpec` + query object. A :obj:`str` will be turned into a :obj:`MatchSpec` automatically. + pkgs_dirs (Iterable[str] or None): + If None, will fall back to context.pkgs_dirs. + + Returns: + tuple[PackageCacheRecord] + + """ + return tuple(_PackageCacheData.query_all(package_ref_or_match_spec, pkgs_dirs)) + + def iter_records(self): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Returns: + Iterable[PackageCacheRecord]: A generator over all records contained in the package + cache instance. Warning: this is a generator that is exhausted on first use. + + """ + return self._internal.iter_records() + + @property + def is_writable(self): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Indicates if the package cache location is writable or read-only. + + Returns: + bool + + """ + return self._internal.is_writable + + @staticmethod + def first_writable(pkgs_dirs=None): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Get an instance object for the first writable package cache. + + Args: + pkgs_dirs (Iterable[str]): + If None, will fall back to context.pkgs_dirs. + + Returns: + PackageCacheData: + An instance for the first writable package cache. + + """ + return PackageCacheData(_PackageCacheData.first_writable(pkgs_dirs).pkgs_dir) + + def reload(self): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Update the instance with new information. Backing information (i.e. contents of + the pkgs_dir) is lazily loaded on first use by the other methods of this class. You + should only use this method if you are *sure* you have outdated data. + + Returns: + PackageCacheData + + """ + self._internal = self._internal.reload() + return self + + +class PrefixData: + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + High-level management and usage of conda environment prefixes. + """ + + def __init__(self, prefix_path): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Args: + prefix_path (str): + """ + self._internal = _PrefixData(prefix_path) + + def get(self, package_ref, default=NULL): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Args: + package_ref (PackageRef): + A :obj:`PackageRef` instance representing the key for the + :obj:`PrefixRecord` being sought. + default: The default value to return if the record does not exist. If not + specified and no record exists, :exc:`KeyError` is raised. + + Returns: + PrefixRecord + + """ + return self._internal.get(package_ref.name, default) + + def query(self, package_ref_or_match_spec): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Run a query against this specific prefix instance. + + Args: + package_ref_or_match_spec (PackageRef or MatchSpec or str): + Either an exact :obj:`PackageRef` to match against, or a :obj:`MatchSpec` + query object. A :obj:`str` will be turned into a :obj:`MatchSpec` automatically. + + Returns: + tuple[PrefixRecord] + + """ + return tuple(self._internal.query(package_ref_or_match_spec)) + + def iter_records(self): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Returns: + Iterable[PrefixRecord]: A generator over all records contained in the prefix. + Warning: this is a generator that is exhausted on first use. + + """ + return self._internal.iter_records() + + @property + def is_writable(self): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Indicates if the prefix is writable or read-only. + + Returns: + bool or None: + True if the prefix is writable. False if read-only. None if the prefix + does not exist as a conda environment. + + """ + return self._internal.is_writable + + def reload(self): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Update the instance with new information. Backing information (i.e. contents of + the conda-meta directory) is lazily loaded on first use by the other methods of this + class. You should only use this method if you are *sure* you have outdated data. + + Returns: + PrefixData + + """ + self._internal = self._internal.reload() + return self diff --git a/data/miniconda3/lib/python3.13/site-packages/conda/deprecations.py b/data/miniconda3/lib/python3.13/site-packages/conda/deprecations.py new file mode 100644 index 0000000000000000000000000000000000000000..837fab51fdf4304102eb041ea35f28c769c2cc48 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda/deprecations.py @@ -0,0 +1,481 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Tools to aid in deprecating code.""" + +from __future__ import annotations + +import sys +import warnings +from argparse import SUPPRESS, Action +from dataclasses import dataclass, field +from functools import wraps +from types import ModuleType +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from argparse import ArgumentParser, Namespace + from collections.abc import Callable + from typing import Any, ParamSpec, Self, TypeVar + + from packaging.version import Version + + T = TypeVar("T") + P = ParamSpec("P") + + ActionType = TypeVar("ActionType", bound=type[Action]) + +from . import __version__ + + +class DeprecatedError(RuntimeError): + pass + + +# inspired by deprecation (https://deprecation.readthedocs.io/en/latest/) and +# CPython's warnings._deprecated +class DeprecationHandler: + _version: str | None + _version_tuple: tuple[int, ...] | None + _version_object: Version | None + + def __init__(self: Self, version: str) -> None: + """Factory to create a deprecation handle for the specified version. + + :param version: The version to compare against when checking deprecation statuses. + """ + self._version = version + # Try to parse the version string as a simple tuple[int, ...] to avoid + # packaging.version import and costlier version comparisons. + self._version_tuple = self._get_version_tuple(version) + self._version_object = None + + @staticmethod + def _get_version_tuple(version: str) -> tuple[int, ...] | None: + """Return version as non-empty tuple of ints if possible, else None. + + :param version: Version string to parse. + """ + try: + return tuple(int(part) for part in version.strip().split(".")) or None + except (AttributeError, ValueError): + return None + + def _version_less_than(self: Self, version: str) -> bool: + """Test whether own version is less than the given version. + + :param version: Version string to compare against. + """ + if self._version_tuple and (version_tuple := self._get_version_tuple(version)): + return self._version_tuple < version_tuple + + # If self._version or version could not be represented by a simple + # tuple[int, ...], do a more elaborate version parsing and comparison. + # Avoid this import otherwise to reduce import time for conda activate. + from packaging.version import parse + + if self._version_object is None: + try: + self._version_object = parse(self._version) # type: ignore[arg-type] + except TypeError: + # TypeError: self._version could not be parsed + self._version_object = parse("0.0.0.dev0+placeholder") + return self._version_object < parse(version) + + def __call__( + self: Self, + deprecate_in: str, + remove_in: str, + *, + addendum: str | None = None, + stack: int = 0, + deprecation_type: type[Warning] = DeprecationWarning, + ) -> Callable[[Callable[P, T]], Callable[P, T]]: + """Deprecation decorator for functions, methods, & classes. + + :param deprecate_in: Version in which code will be marked as deprecated. + :param remove_in: Version in which code is expected to be removed. + :param addendum: Optional additional messaging. Useful to indicate what to do instead. + :param stack: Optional stacklevel increment. + """ + + def deprecated_decorator(obj: Callable[P, T]) -> Callable[P, T]: + # detect function name and generate message + category, message = self._generate_message( + deprecate_in=deprecate_in, + remove_in=remove_in, + prefix=f"{obj.__module__}.{obj.__qualname__}", + addendum=addendum, + deprecation_type=deprecation_type, + ) + + # alert developer that it's time to remove something + if not category: + raise DeprecatedError(message) + + # if obj is a class, wrap the __init__ + isclass = False + func: Callable[P, T] + if isinstance(obj, type): + try: + func = obj.__init__ # type: ignore[misc] + except AttributeError: + # AttributeError: obj has no __init__ + func = obj + else: + isclass = True + else: + func = obj + + # alert user that it's time to remove something + @wraps(func) # type: ignore[reportArgumentType] + def inner(*args: P.args, **kwargs: P.kwargs) -> T: + warnings.warn(message, category, stacklevel=2 + stack) + + return func(*args, **kwargs) + + if isclass: + obj.__init__ = inner # type: ignore[misc] + return obj + else: + return inner + + return deprecated_decorator + + def argument( + self: Self, + deprecate_in: str, + remove_in: str, + argument: str, + *, + rename: str | None = None, + addendum: str | None = None, + stack: int = 0, + deprecation_type: type[Warning] = DeprecationWarning, + ) -> Callable[[Callable[P, T]], Callable[P, T]]: + """Deprecation decorator for keyword arguments. + + :param deprecate_in: Version in which code will be marked as deprecated. + :param remove_in: Version in which code is expected to be removed. + :param argument: The argument to deprecate. + :param rename: Optional new argument name. + :param addendum: Optional additional messaging. Useful to indicate what to do instead. + :param stack: Optional stacklevel increment. + """ + + def deprecated_decorator(func: Callable[P, T]) -> Callable[P, T]: + # detect function name and generate message + category, message = self._generate_message( + deprecate_in=deprecate_in, + remove_in=remove_in, + prefix=f"{func.__module__}.{func.__qualname__}({argument})", + # provide a default addendum if renaming and no addendum is provided + addendum=( + f"Use '{rename}' instead." if rename and not addendum else addendum + ), + deprecation_type=deprecation_type, + ) + + # alert developer that it's time to remove something + if not category: + raise DeprecatedError(message) + + # alert user that it's time to remove something + @wraps(func) + def inner(*args: P.args, **kwargs: P.kwargs) -> T: + # only warn about argument deprecations if the argument is used + if argument in kwargs: + warnings.warn(message, category, stacklevel=2 + stack) + + # rename argument deprecations as needed + value = kwargs.pop(argument, None) + if rename: + kwargs.setdefault(rename, value) + + return func(*args, **kwargs) + + return inner + + return deprecated_decorator + + def action( + self: Self, + deprecate_in: str, + remove_in: str, + action: ActionType, + *, + addendum: str | None = None, + stack: int = 0, + deprecation_type: type[Warning] = FutureWarning, + ) -> ActionType: + """Wraps any argparse.Action to issue a deprecation warning.""" + + class DeprecationMixin(Action): + category: type[Warning] + help: str # override argparse.Action's help type annotation + + def __init__(inner_self: Self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + category, message = self._generate_message( + deprecate_in=deprecate_in, + remove_in=remove_in, + prefix=( + # option_string are ordered shortest to longest, + # use the longest as it's the most descriptive + f"`{inner_self.option_strings[-1]}`" + if inner_self.option_strings + # if not a flag/switch, use the destination itself + else f"`{inner_self.dest}`" + ), + addendum=addendum, + deprecation_type=deprecation_type, + ) + + # alert developer that it's time to remove something + if not category: + raise DeprecatedError(message) + + inner_self.category = category + inner_self.deprecation = message + if inner_self.help is not SUPPRESS: + inner_self.help = message + + def __call__( + inner_self: Self, + parser: ArgumentParser, + namespace: Namespace, + values: Any, + option_string: str | None = None, + ) -> None: + # alert user that it's time to remove something + from conda.common.constants import NULL + + if values is not NULL: + warnings.warn( + inner_self.deprecation, + inner_self.category, + stacklevel=7 + stack, + ) + + super().__call__(parser, namespace, values, option_string) + + return type(action.__name__, (DeprecationMixin, action), {}) # type: ignore[return-value] + + def module( + self: Self, + deprecate_in: str, + remove_in: str, + *, + addendum: str | None = None, + stack: int = 0, + ) -> None: + """Deprecation function for modules. + + :param deprecate_in: Version in which code will be marked as deprecated. + :param remove_in: Version in which code is expected to be removed. + :param addendum: Optional additional messaging. Useful to indicate what to do instead. + :param stack: Optional stacklevel increment. + """ + self.topic( + deprecate_in=deprecate_in, + remove_in=remove_in, + topic=self._get_module(stack)[1], + addendum=addendum, + stack=2 + stack, + ) + + def constant( + self: Self, + deprecate_in: str, + remove_in: str, + constant: str, + value: Any, + *, + addendum: str | None = None, + stack: int = 0, + deprecation_type: type[Warning] = DeprecationWarning, + ) -> None: + """Deprecation function for module constant/global. + + :param deprecate_in: Version in which code will be marked as deprecated. + :param remove_in: Version in which code is expected to be removed. + :param constant: + :param value: + :param addendum: Optional additional messaging. Useful to indicate what to do instead. + :param stack: Optional stacklevel increment. + """ + # detect calling module + module, fullname = self._get_module(stack) + # detect function name and generate message + category, message = self._generate_message( + deprecate_in=deprecate_in, + remove_in=remove_in, + prefix=f"{fullname}.{constant}", + addendum=addendum, + deprecation_type=deprecation_type, + ) + + # alert developer that it's time to remove something + if not category: + raise DeprecatedError(message) + + # patch module level __getattr__ to alert user that it's time to remove something + if isinstance( + fallback := getattr(module, "__getattr__", None), + _ConstantDeprecationRegistry, + ): + deprecations = fallback + else: + deprecations = _ConstantDeprecationRegistry(fullname, fallback) + module.__getattr__ = deprecations # type: ignore[method-assign] + + deprecations.register(constant, message, category, stack, value) + + def topic( + self: Self, + deprecate_in: str, + remove_in: str, + *, + topic: str, + addendum: str | None = None, + stack: int = 0, + deprecation_type: type[Warning] = DeprecationWarning, + ) -> None: + """Deprecation function for a topic. + + :param deprecate_in: Version in which code will be marked as deprecated. + :param remove_in: Version in which code is expected to be removed. + :param topic: The topic being deprecated. + :param addendum: Optional additional messaging. Useful to indicate what to do instead. + :param stack: Optional stacklevel increment. + """ + # detect function name and generate message + category, message = self._generate_message( + deprecate_in=deprecate_in, + remove_in=remove_in, + prefix=topic, + addendum=addendum, + deprecation_type=deprecation_type, + ) + + # alert developer that it's time to remove something + if not category: + raise DeprecatedError(message) + + # alert user that it's time to remove something + warnings.warn(message, category, stacklevel=2 + stack) + + def _get_module(self: Self, stack: int) -> tuple[ModuleType, str]: + """Detect the module from which we are being called. + + :param stack: The stacklevel increment. + :return: The module and module name. + """ + try: + frame = sys._getframe(2 + stack) + except IndexError: + # IndexError: 2 + stack is out of range + pass + else: + # Shortcut finding the module by manually inspecting loaded modules. + try: + filename = frame.f_code.co_filename + except AttributeError: + # AttributeError: frame.f_code.co_filename is undefined + pass + else: + # use a copy of sys.modules to avoid RuntimeError during iteration + # see https://github.com/conda/conda/issues/13754 + for loaded in tuple(sys.modules.values()): + if not isinstance(loaded, ModuleType): + continue + if not hasattr(loaded, "__file__"): + continue + if loaded.__file__ == filename: + return (loaded, loaded.__name__) + + # If above failed, do an expensive import and costly getmodule call. + import inspect + + module = inspect.getmodule(frame) + if module is not None: + return (module, module.__name__) + + raise DeprecatedError("unable to determine the calling module") + + def _generate_message( + self: Self, + deprecate_in: str, + remove_in: str, + prefix: str, + addendum: str | None, + *, + deprecation_type: type[Warning], + ) -> tuple[type[Warning] | None, str]: + """Generate the standardized deprecation message and determine whether the + deprecation is pending, active, or past. + + :param deprecate_in: Version in which code will be marked as deprecated. + :param remove_in: Version in which code is expected to be removed. + :param prefix: The message prefix, usually the function name. + :param addendum: Additional messaging. Useful to indicate what to do instead. + :param deprecation_type: The warning type to use for active deprecations. + :return: The warning category (if applicable) and the message. + """ + category: type[Warning] | None + if self._version_less_than(deprecate_in): + category = PendingDeprecationWarning + warning = f"is pending deprecation and will be removed in {remove_in}." + elif self._version_less_than(remove_in): + category = deprecation_type + warning = f"is deprecated and will be removed in {remove_in}." + else: + category = None + warning = f"was slated for removal in {remove_in}." + + return ( + category, + " ".join(filter(None, [prefix, warning, addendum])), # message + ) + + +@dataclass +class _ConstantDeprecationRegistry: + """Registry of deprecated module constants. + + Serves as a module's __getattr__, issuing deprecation warnings + when registered constants are accessed. + """ + + deprecations: dict[str, tuple[str, type[Warning], int, Any]] = field( + default_factory=dict, + init=False, + repr=False, + ) + fullname: str + fallback: Callable[[str], Any] | None + + def __call__(self, name: str) -> Any: + if name in self.deprecations: + message, category, stacklevel, value = self.deprecations[name] + warnings.warn(message, category, stacklevel=stacklevel) + return value + + if self.fallback: + return self.fallback(name) + + raise AttributeError(f"module '{self.fullname}' has no attribute '{name}'") + + def register( + self, + constant: str, + message: str, + category: type[Warning], + stack: int, + value: Any, + ) -> None: + # stacklevel=2 points from __call__ to user code accessing the constant + self.deprecations[constant] = (message, category, 2 + stack, value) + + +deprecated = DeprecationHandler(__version__) diff --git a/data/miniconda3/lib/python3.13/site-packages/conda/exception_handler.py b/data/miniconda3/lib/python3.13/site-packages/conda/exception_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..a389777d3a9be4c9a71ac4a63d27f1f02adb2507 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda/exception_handler.py @@ -0,0 +1,430 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Error handling and error reporting.""" + +from __future__ import annotations + +import os +import sys +from functools import cached_property, partial +from logging import getLogger +from typing import TYPE_CHECKING + +from .common.compat import ensure_text_type, on_win +from .deprecations import deprecated + +if TYPE_CHECKING: + from collections.abc import Callable + from types import TracebackType + from typing import Any, TypeVar + + T = TypeVar("T") + +log = getLogger(__name__) + + +class ExceptionHandler: + # FUTURE: Python 3.10+, use typing.ParamSpec + def __call__(self, func: Callable[..., T], *args, **kwargs) -> T | int: + try: + return func(*args, **kwargs) + except: + _, exc_val, exc_tb = sys.exc_info() + return self.handle_exception(exc_val, exc_tb) + + def write_out(self, *content: str) -> None: + from logging import getLogger + + from .cli.main import init_loggers + + init_loggers() + getLogger("conda.stderr").info("\n".join(content)) + + @property + def http_timeout(self): + from .base.context import context + + return context.remote_connect_timeout_secs, context.remote_read_timeout_secs + + @property + def user_agent(self): + from .base.context import context + + return context.user_agent + + @property + @deprecated( + "26.9", + "27.3", + ) + def error_upload_url(self): + from .base.context import context + + return context.error_upload_url + + def handle_exception(self, exc_val: BaseException, exc_tb: TracebackType) -> int: + from errno import ENOSPC + + from .exceptions import ( + CondaError, + CondaMemoryError, + NoSpaceLeftError, + ) + + if isinstance(exc_val, CondaError): + if exc_val.reportable: + return self.handle_reportable_application_exception(exc_val, exc_tb) + else: + return self.handle_application_exception(exc_val, exc_tb) + if isinstance(exc_val, EnvironmentError): + if getattr(exc_val, "errno", None) == ENOSPC: + return self.handle_application_exception( + NoSpaceLeftError(exc_val), exc_tb + ) + if isinstance(exc_val, MemoryError): + return self.handle_application_exception(CondaMemoryError(exc_val), exc_tb) + if isinstance(exc_val, KeyboardInterrupt): + self._print_conda_exception(CondaError("KeyboardInterrupt"), exc_tb) + return 1 + if isinstance(exc_val, SystemExit): + return exc_val.code + return self.handle_unexpected_exception(exc_val, exc_tb) + + def handle_application_exception( + self, exc_val: BaseException, exc_tb: TracebackType + ) -> int: + self._print_conda_exception(exc_val, exc_tb) + return exc_val.return_code + + def _print_conda_exception( + self, + exc_val: BaseException, + exc_tb: TracebackType, + ) -> None: + from .exceptions import print_conda_exception + + print_conda_exception(exc_val, exc_tb) + + def handle_unexpected_exception( + self, exc_val: BaseException, exc_tb: TracebackType + ) -> int: + error_report = self.get_error_report(exc_val, exc_tb) + self.print_unexpected_error_report(error_report) + rc = getattr(exc_val, "return_code", None) + return rc if rc is not None else 1 + + def handle_reportable_application_exception( + self, exc_val: BaseException, exc_tb: TracebackType + ) -> int: + error_report = self.get_error_report(exc_val, exc_tb) + from .base.context import context + + if context.json: + error_report.update(exc_val.dump_map()) + self.print_expected_error_report(error_report) + return exc_val.return_code + + def get_error_report( + self, + exc_val: BaseException, + exc_tb: TracebackType, + ) -> dict[str, str]: + from .exceptions import CondaError, _format_exc + + command = " ".join(ensure_text_type(s) for s in sys.argv) + info_dict = {} + if " info" not in command: + # get info_dict, but if we get an exception here too, record it without trampling + # the original exception + try: + from .cli.main_info import get_info_dict + + info_dict = get_info_dict() + except Exception as info_e: + info_traceback = _format_exc() + info_dict = { + "error": repr(info_e), + "exception_name": info_e.__class__.__name__, + "exception_type": str(exc_val.__class__), + "traceback": info_traceback, + } + + error_report = { + "error": repr(exc_val), + "exception_name": exc_val.__class__.__name__, + "exception_type": str(exc_val.__class__), + "command": command, + "traceback": _format_exc(exc_val, exc_tb), + "conda_info": info_dict, + } + + if isinstance(exc_val, CondaError): + error_report["conda_error_components"] = exc_val.dump_map() + + return error_report + + def print_unexpected_error_report(self, error_report: dict[str, str]) -> None: + from .base.context import context + + if context.json: + from .cli.common import stdout_json + + stdout_json(error_report) + else: + message_builder = [] + message_builder.append("") + message_builder.append( + "# >>>>>>>>>>>>>>>>>>>>>> ERROR REPORT <<<<<<<<<<<<<<<<<<<<<<" + ) + message_builder.append("") + message_builder.extend( + " " + line for line in error_report["traceback"].splitlines() + ) + message_builder.append("") + message_builder.append("`$ {}`".format(error_report["command"])) + message_builder.append("") + if error_report["conda_info"]: + from .cli.main_info import get_env_vars_str, get_main_info_str + + try: + # TODO: Sanitize env vars to remove secrets (e.g credentials for PROXY) + message_builder.append(get_env_vars_str(error_report["conda_info"])) + message_builder.append( + get_main_info_str(error_report["conda_info"]) + ) + except Exception as e: + log.warning("%r", e, exc_info=True) + message_builder.append("conda info could not be constructed.") + message_builder.append(f"{e!r}") + message_builder.extend( + [ + "", + "An unexpected error has occurred. Conda has prepared the above report." + "", + "If you suspect this error is being caused by a malfunctioning plugin,", + "consider using the --no-plugins option to turn off plugins.", + "", + "Example: conda --no-plugins install ", + "", + "Alternatively, you can set the CONDA_NO_PLUGINS environment variable on", + "the command line to run the command without plugins enabled.", + "", + "Example: CONDA_NO_PLUGINS=true conda install ", + "", + ] + ) + self.write_out(*message_builder) + + def print_expected_error_report(self, error_report: dict[str, str]) -> None: + from .base.context import context + + if context.json: + from .cli.common import stdout_json + + stdout_json(error_report) + else: + message_builder = [] + message_builder.append("") + message_builder.append( + "# >>>>>>>>>>>>>>>>>>>>>> ERROR REPORT <<<<<<<<<<<<<<<<<<<<<<" + ) + message_builder.append("") + message_builder.append("`$ {}`".format(error_report["command"])) + message_builder.append("") + if error_report["conda_info"]: + from .cli.main_info import get_env_vars_str, get_main_info_str + + try: + # TODO: Sanitize env vars to remove secrets (e.g credentials for PROXY) + message_builder.append(get_env_vars_str(error_report["conda_info"])) + message_builder.append( + get_main_info_str(error_report["conda_info"]) + ) + except Exception as e: + log.warning("%r", e, exc_info=True) + message_builder.append("conda info could not be constructed.") + message_builder.append(f"{e!r}") + message_builder.append("") + message_builder.append( + "V V V V V V V V V V V V V V V V V V V V V V V V V V V V V V V" + ) + message_builder.append("") + + message_builder.extend(error_report["error"].splitlines()) + message_builder.append("") + + message_builder.append( + "A reportable application error has occurred. Conda has prepared the above report." + ) + message_builder.append("") + self.write_out(*message_builder) + + @cached_property + def _isatty(self) -> bool: + try: + return os.isatty(0) or on_win + except Exception as e: + log.debug("%r", e) + return True + + @deprecated( + "26.9", + "27.3", + ) + def _upload(self, error_report: dict[str, str]) -> None: + """Determine whether or not to upload the error report.""" + from .base.context import context + + post_upload = False + if context.report_errors is False: + # no prompt and no submission + do_upload = False + elif context.report_errors is True or context.always_yes: + # no prompt and submit + do_upload = True + elif context.json or context.quiet or not self._isatty: + # never prompt under these conditions, submit iff always_yes + do_upload = bool(not context.offline and context.always_yes) + else: + # prompt whether to submit + do_upload = self._ask_upload() + post_upload = True + + # the upload state is one of the following: + # - True: upload error report + # - False: do not upload error report + # - None: while prompting a timeout occurred + + if do_upload: + # user wants report to be submitted + self._execute_upload(error_report) + + if post_upload: + # post submission text + self._post_upload(do_upload) + + @deprecated( + "26.9", + "27.3", + ) + def _ask_upload(self) -> bool: + from .auxlib.type_coercion import boolify + from .common.io import timeout + + try: + do_upload = timeout( + 40, + partial( + input, + "If submitted, this report will be used by core maintainers to improve\n" + "future releases of conda.\n" + "Would you like conda to send this report to the core maintainers? " + "[y/N]: ", + ), + ) + return do_upload and boolify(do_upload) + except Exception as e: + log.debug("%r", e) + return False + + @deprecated( + "26.9", + "27.3", + ) + def _execute_upload(self, error_report: dict[str, Any]) -> None: + import getpass + + from .common.serialize import json + + headers = { + "User-Agent": self.user_agent, + } + _timeout = self.http_timeout + username = getpass.getuser() + error_report["is_ascii"] = ( + True if all(ord(c) < 128 for c in username) else False + ) + error_report["has_spaces"] = True if " " in str(username) else False + data = json.dumps(error_report, sort_keys=True) + "\n" + data = data.replace(str(username), "USERNAME_REMOVED") + response = None + try: + # requests does not follow HTTP standards for redirects of non-GET methods + # That is, when following a 301 or 302, it turns a POST into a GET. + # And no way to disable. WTF + import requests + + redirect_counter = 0 + url = self.error_upload_url + response = requests.post( + url, headers=headers, timeout=_timeout, data=data, allow_redirects=False + ) + response.raise_for_status() + while response.status_code in (301, 302) and response.headers.get( + "Location" + ): + url = response.headers["Location"] + response = requests.post( + url, + headers=headers, + timeout=_timeout, + data=data, + allow_redirects=False, + ) + response.raise_for_status() + redirect_counter += 1 + if redirect_counter > 15: + from . import CondaError + + raise CondaError("Redirect limit exceeded") + log.debug("upload response status: %s", response and response.status_code) + except Exception as e: # pragma: no cover + log.info("%r", e) + try: + if response and response.ok: + self.write_out("Upload successful.") + else: + self.write_out("Upload did not complete.") + if response and response.status_code: + self.write_out(f" HTTP {response.status_code}") + except Exception as e: + log.debug(f"{e!r}") + + @deprecated( + "26.9", + "27.3", + ) + def _post_upload(self, do_upload: bool) -> None: + if do_upload is True: + # report was submitted + self.write_out( + "", + "Thank you for helping to improve conda.", + "Opt-in to always sending reports (and not see this message again)", + "by running", + "", + " $ conda config --set report_errors true", + "", + ) + elif do_upload is None: + # timeout was reached while prompting user + self.write_out( + "", + "Timeout reached. No report sent.", + "", + ) + else: + # no report submitted + self.write_out( + "", + "No report sent. To permanently opt-out, use", + "", + " $ conda config --set report_errors false", + "", + ) + + +def conda_exception_handler(func: Callable[..., T], *args, **kwargs) -> T | int: + exception_handler = ExceptionHandler() + return_value = exception_handler(func, *args, **kwargs) + return return_value diff --git a/data/miniconda3/lib/python3.13/site-packages/conda/exceptions.py b/data/miniconda3/lib/python3.13/site-packages/conda/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..eb883664e1506219696506a0c6ad46cf150185d7 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda/exceptions.py @@ -0,0 +1,1505 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Conda exceptions.""" + +from __future__ import annotations + +import os +import sys +from collections import defaultdict +from datetime import timedelta +from logging import getLogger +from os.path import join +from textwrap import dedent, indent +from traceback import format_exception, format_exception_only +from typing import TYPE_CHECKING + +from . import CondaError, CondaExitZero, CondaMultiError +from .auxlib.ish import dals +from .auxlib.logz import stringify +from .base.constants import ( + COMPATIBLE_SHELLS, + PREFIX_PINNED_FILE, + PathConflict, + SafetyChecks, +) +from .common.compat import on_win +from .common.io import dashlist +from .common.iterators import groupby_to_dict as groupby +from .common.serialize.json import JSONDecodeError +from .common.serialize.json import dumps as json_dumps +from .common.signals import get_signal_name +from .common.url import join_url, maybe_unquote +from .deprecations import DeprecatedError # noqa: F401 +from .exception_handler import ExceptionHandler, conda_exception_handler # noqa: F401 +from .models.channel import Channel + +if TYPE_CHECKING: + from collections.abc import Iterable + from types import TracebackType + from typing import Any + + import requests + + from conda.base.context import Context + from conda.common.path import PathType + from conda.models.match_spec import MatchSpec + from conda.models.records import PackageRecord + from conda.plugins.types import CondaEnvironmentExporter + +log = getLogger(__name__) + + +# TODO: for conda-build compatibility only +# remove in conda 4.4 +class ResolvePackageNotFound(CondaError): + def __init__(self, bad_deps: Iterable[Iterable[MatchSpec]]): + # bad_deps is a list of lists + # bad_deps should really be named 'invalid_chains' + self.bad_deps = tuple(dep for deps in bad_deps for dep in deps if dep) + formatted_chains = tuple( + " -> ".join(map(str, bad_chain)) for bad_chain in bad_deps + ) + self._formatted_chains = formatted_chains + message = "\n" + "\n".join( + (f" - {bad_chain}") for bad_chain in formatted_chains + ) + super().__init__(message) + + +NoPackagesFound = NoPackagesFoundError = ResolvePackageNotFound + + +class LockError(CondaError, OSError): + def __init__(self, message: str): + msg = str(message) + super().__init__(msg) + + +class ArgumentError(CondaError): + return_code = 2 + + def __init__(self, message: str, **kwargs): + super().__init__(message, **kwargs) + + +class Help(CondaError): + pass + + +class ActivateHelp(Help): + def __init__(self): + message = dals( + """ + usage: conda activate [-h] [--[no-]stack] [env_name_or_prefix] + + Activate a conda environment. + + Options: + + positional arguments: + env_name_or_prefix The environment name or prefix to activate. If the + prefix is a relative path, it must start with './' + (or '.\\' on Windows). + + optional arguments: + -h, --help Show this help message and exit. + --stack Stack the environment being activated on top of the + previous active environment, rather replacing the + current active environment with a new one. Currently, + only the PATH environment variable is stacked. This + may be enabled implicitly by the 'auto_stack' + configuration variable. + --no-stack Do not stack the environment. Overrides 'auto_stack' + setting. + """ + ) + super().__init__(message) + + +class DeactivateHelp(Help): + def __init__(self): + message = dals( + """ + usage: conda deactivate [-h] + + Deactivate the current active conda environment. + + Options: + + optional arguments: + -h, --help Show this help message and exit. + """ + ) + super().__init__(message) + + +class GenericHelp(Help): + def __init__(self, command: str): + message = f"help requested for {command}" + super().__init__(message) + + +class CondaSignalInterrupt(CondaError): + def __init__(self, signum: int): + signal_name = get_signal_name(signum) + super().__init__( + "Signal interrupt %(signal_name)s", signal_name=signal_name, signum=signum + ) + + +class TooManyArgumentsError(ArgumentError): + def __init__( + self, + expected: int, + received: int, + offending_arguments: Iterable[str], + optional_message: str = "", + *args, + ): + self.expected = expected + self.received = received + self.offending_arguments = offending_arguments + self.optional_message = optional_message + + suffix = "s" if received - expected > 1 else "" + msg = "{} Got {} argument{} ({}) but expected {}.".format( + optional_message, + received, + suffix, + ", ".join(offending_arguments), + expected, + ) + super().__init__(msg, *args) + + +class ClobberError(CondaError): + def __init__(self, message: str, path_conflict: PathConflict, **kwargs): + self.path_conflict = path_conflict + super().__init__(message, **kwargs) + + def __repr__(self): + clz_name = ( + "ClobberWarning" + if self.path_conflict == PathConflict.warn + else "ClobberError" + ) + return f"{clz_name}: {self}\n" + + +class BasicClobberError(ClobberError): + def __init__(self, source_path: PathType, target_path: PathType, context: Context): + message = dals( + """ + Conda was asked to clobber an existing path. + source path: %(source_path)s + target path: %(target_path)s + """ + ) + if context.path_conflict == PathConflict.prevent: + message += ( + "Conda no longer clobbers existing paths without the use of the " + "--clobber option\n." + ) + super().__init__( + message, + context.path_conflict, + target_path=target_path, + source_path=source_path, + ) + + +class KnownPackageClobberError(ClobberError): + def __init__( + self, + target_path: PathType, + colliding_dist_being_linked: PackageRecord | str, + colliding_linked_dist: PackageRecord | str, + context: Context, + ): + message = dals( + """ + The package '%(colliding_dist_being_linked)s' cannot be installed due to a + path collision for '%(target_path)s'. + This path already exists in the target prefix, and it won't be removed by + an uninstall action in this transaction. The path appears to be coming from + the package '%(colliding_linked_dist)s', which is already installed in the prefix. + """ + ) + if context.path_conflict == PathConflict.prevent: + message += ( + "If you'd like to proceed anyway, re-run the command with " + "the `--clobber` flag.\n." + ) + super().__init__( + message, + context.path_conflict, + target_path=target_path, + colliding_dist_being_linked=colliding_dist_being_linked, + colliding_linked_dist=colliding_linked_dist, + ) + + +class UnknownPackageClobberError(ClobberError): + def __init__( + self, + target_path: PathType, + colliding_dist_being_linked: PackageRecord | str, + context: Context, + ): + message = dals( + """ + The package '%(colliding_dist_being_linked)s' cannot be installed due to a + path collision for '%(target_path)s'. + This path already exists in the target prefix, and it won't be removed + by an uninstall action in this transaction. The path is one that conda + doesn't recognize. It may have been created by another package manager. + """ + ) + if context.path_conflict == PathConflict.prevent: + message += ( + "If you'd like to proceed anyway, re-run the command with " + "the `--clobber` flag.\n." + ) + super().__init__( + message, + context.path_conflict, + target_path=target_path, + colliding_dist_being_linked=colliding_dist_being_linked, + ) + + +class SharedLinkPathClobberError(ClobberError): + def __init__( + self, + target_path: PathType, + incompatible_package_dists: Iterable[PackageRecord | str], + context: Context, + ): + message = dals( + """ + This transaction has incompatible packages due to a shared path. + packages: %(incompatible_packages)s + path: '%(target_path)s' + """ + ) + if context.path_conflict == PathConflict.prevent: + message += ( + "If you'd like to proceed anyway, re-run the command with " + "the `--clobber` flag.\n." + ) + super().__init__( + message, + context.path_conflict, + target_path=target_path, + incompatible_packages=", ".join(str(d) for d in incompatible_package_dists), + ) + + +class CommandNotFoundError(CondaError): + def __init__(self, command: str): + activate_commands = { + "activate", + "deactivate", + "run", + } + conda_commands = { + "clean", + "config", + "create", + "--help", # https://github.com/conda/conda/issues/11585 + "info", + "install", + "list", + "package", + "remove", + "search", + "uninstall", + "update", + "upgrade", + } + build_commands = { + "build", + "convert", + "develop", + "index", + "inspect", + "metapackage", + "render", + "skeleton", + } + from .cli.main import init_loggers + + init_loggers() + if command in activate_commands: + # TODO: Point users to a page at conda-docs, which explains this context in more detail + builder = [ + "Your shell has not been properly configured to use 'conda %(command)s'." + ] + if on_win: + builder.append( + dals( + """ + If using 'conda %(command)s' from a batch script, change your + invocation to 'CALL conda.bat %(command)s'. + """ + ) + ) + builder.append( + dals( + """ + To initialize your shell, run + + $ conda init + + Currently supported shells are:%(supported_shells)s + + See 'conda init --help' for more information and options. + + IMPORTANT: You may need to close and restart your shell after running 'conda init'. + """ + ) + % { + "supported_shells": dashlist(COMPATIBLE_SHELLS), + } + ) + message = "\n".join(builder) + elif command in build_commands: + message = "To use 'conda %(command)s', install conda-build." + else: + from difflib import get_close_matches + + from .cli.find_commands import find_commands + + message = "No command 'conda %(command)s'." + choices = ( + activate_commands + | conda_commands + | build_commands + | set(find_commands()) + ) + close = get_close_matches(command, choices) + if close: + message += f"\nDid you mean 'conda {close[0]}'?" + super().__init__(message, command=command) + + +class PathNotFoundError(CondaError, OSError): + def __init__(self, path: PathType): + message = "%(path)s" + super().__init__(message, path=path) + + +class DirectoryNotFoundError(CondaError): + def __init__(self, path: PathType): + message = "%(path)s" + super().__init__(message, path=path) + + +class EnvironmentLocationNotFound(CondaError): + def __init__(self, location: PathType): + message = "Not a conda environment: %(location)s" + super().__init__(message, location=location) + + +class EnvironmentNameNotFound(CondaError): + def __init__(self, environment_name: str): + message = dals( + """ + Could not find conda environment: %(environment_name)s + You can list all discoverable environments with `conda info --envs`. + """ + ) + super().__init__(message, environment_name=environment_name) + + +class NoBaseEnvironmentError(CondaError): + def __init__(self): + message = dals( + """ + This conda installation has no default base environment. Use + 'conda create' to create new environments and 'conda activate' to + activate environments. + """ + ) + super().__init__(message) + + +class DirectoryNotACondaEnvironmentError(CondaError): + def __init__(self, target_directory: PathType): + message = dals( + """ + The target directory exists, but it is not a conda environment. + Use 'conda create' to convert the directory to a conda environment. + target directory: %(target_directory)s + """ + ) + super().__init__(message, target_directory=target_directory) + + +class CondaEnvironmentError(CondaError, EnvironmentError): + def __init__(self, message: str, *args): + msg = f"{message}" + super().__init__(msg, *args) + + +class DryRunExit(CondaExitZero): + def __init__(self): + msg = "Dry run. Exiting." + super().__init__(msg) + + +class CondaSystemExit(CondaExitZero, SystemExit): + def __init__(self, *args): + msg = " ".join(str(arg) for arg in self.args) + super().__init__(msg) + + +class PaddingError(CondaError): + def __init__(self, dist: str, placeholder: str, placeholder_length: int): + msg = ( + "Placeholder of length '%d' too short in package %s.\n" + "The package must be rebuilt with conda-build > 2.0." + % (placeholder_length, dist) + ) + super().__init__(msg) + + +class LinkError(CondaError): + def __init__(self, message: str): + super().__init__(message) + + +class CondaOSError(CondaError, OSError): + def __init__(self, message: str, **kwargs): + msg = f"{message}" + super().__init__(msg, **kwargs) + + +class ProxyError(CondaError): + def __init__(self, message: str | None = None): + if message is None: + message = dals( + """ + Conda cannot proceed due to an error in your proxy configuration. + Check for typos and other configuration errors in any '.netrc' file in your home directory, + any environment variables ending in '_PROXY', and any other system-wide proxy + configuration settings. + """ + ) + super().__init__(message) + + +class CondaIOError(CondaError, IOError): + def __init__(self, message: str, *args): + msg = f"{message}" + super().__init__(msg) + + +class CondaFileIOError(CondaIOError): + def __init__(self, filepath: PathType, message: str, *args): + self.filepath = filepath + + msg = f"'{filepath}'. {message}" + super().__init__(msg, *args) + + +class CondaKeyError(CondaError, KeyError): + def __init__(self, key: Any, message: str, *args): + self.key = key + self.msg = f"{key!r}: {message}" + super().__init__(self.msg, *args) + + +class ChannelError(CondaError): + pass + + +class ChannelNotAllowed(ChannelError): + warning = "Channel not included in allowlist" + + def __init__(self, channel: Channel): + channel_name = channel.name + channel_url = maybe_unquote(channel.base_url) + message = dals( + """ + %(warning)s: + channel name: %(channel_name)s + channel url: %(channel_url)s + """ + ) + super().__init__( + message, + channel_url=channel_url, + channel_name=channel_name, + warning=self.warning, + ) + + +class ChannelDenied(ChannelNotAllowed): + warning = "Channel included in denylist" + + +class UnavailableInvalidChannel(ChannelError): + status_code: str | int + + def __init__( + self, + channel: Channel | str, + status_code: str | int, + response: requests.models.Response | None = None, + ): + # parse channel + channel = Channel(channel) + channel_name = channel.name + channel_url = maybe_unquote(channel.base_url) + + # define hardcoded/default reason/message + reason = getattr(response, "reason", None) + message = dals( + """ + The channel is not accessible or is invalid. + + You will need to adjust your conda configuration to proceed. + Use `conda config --show channels` to view your configuration's current state, + and use `conda config --show-sources` to view config file locations. + """ + ) + if channel.scheme == "file": + url = join_url(channel.location, channel.name) + message += dedent( + f""" + As of conda 4.3, a valid channel must contain a + `noarch/repodata.json` even if `noarch/repodata.json` is + empty. Use `conda index {url}`, or create `noarch/repodata.json` + """ + ) + + # if response includes a valid json body we prefer the reason/message defined there + try: + body = response.json() + except (AttributeError, JSONDecodeError): + body = {} + else: + reason = body.get("reason") or reason + message = body.get("message") or message + # if RFC 9457 'detail' is present, it is preferred over 'message' + # See https://datatracker.ietf.org/doc/html/rfc9457 + message = body.get("detail") or message + + # standardize arguments + status_code = status_code or "000" + reason = reason or "UNAVAILABLE OR INVALID" + + self.status_code = status_code + + super().__init__( + f"HTTP {status_code} {reason} for channel {channel_name} <{channel_url}>\n\n{message}", + channel_name=channel_name, + channel_url=channel_url, + status_code=status_code, + reason=reason, + response_details=stringify(response, content_max_len=1024) or "", + json=body, + ) + + +class OperationNotAllowed(CondaError): + def __init__(self, message: str): + super().__init__(message) + + +class CondaImportError(CondaError, ImportError): + def __init__(self, message: str): + msg = f"{message}" + super().__init__(msg) + + +class ParseError(CondaError): + def __init__(self, message: str): + msg = f"{message}" + super().__init__(msg) + + +class CouldntParseError(ParseError): + def __init__(self, reason: str): + self.reason = reason + super().__init__(self.args[0]) + + +class ChecksumMismatchError(CondaError): + def __init__( + self, + url: str, + target_full_path: PathType, + checksum_type: str, + expected_checksum: str, + actual_checksum: str, + partial_download: bool = False, + ): + message = dals( + """ + Conda detected a mismatch between the expected content and downloaded content + for url '%(url)s'. + download saved to: %(target_full_path)s + expected %(checksum_type)s: %(expected_checksum)s + actual %(checksum_type)s: %(actual_checksum)s + """ + ) + url = maybe_unquote(url) + super().__init__( + message, + url=url, + target_full_path=target_full_path, + checksum_type=checksum_type, + expected_checksum=expected_checksum, + actual_checksum=actual_checksum, + partial_download=partial_download, + ) + + +class PackageNotInstalledError(CondaError): + def __init__(self, prefix: PathType, package_name: str): + message = dals( + """ + Package is not installed in prefix. + prefix: %(prefix)s + package name: %(package_name)s + """ + ) + super().__init__(message, prefix=prefix, package_name=package_name) + + +class CondaHTTPError(CondaError): + def __init__( + self, + message: str, + url: str, + status_code: int | str, + reason: str, + elapsed_time: timedelta | str, + response: requests.Response | None = None, + caused_by: Any = None, + ): + # if response includes a valid json body we prefer the reason/message defined there + try: + body = response.json() + except (AttributeError, JSONDecodeError): + body = {} + else: + reason = body.get("reason") or reason + message = body.get("message") or message + # if RFC 9457 'detail' is present, it is preferred over 'message' + # See https://datatracker.ietf.org/doc/html/rfc9457 + message = body.get("detail") or message + + # standardize arguments + url = maybe_unquote(url) + status_code = status_code or "000" + reason = reason or "CONNECTION FAILED" + elapsed_time = elapsed_time or "-" + if isinstance(elapsed_time, timedelta): + elapsed_time = str(elapsed_time).split(":", 1)[-1] + + # extract CF-RAY + try: + cf_ray = response.headers["CF-RAY"] + except (AttributeError, KeyError): + cf_ray = "" + else: + cf_ray = f"CF-RAY: {cf_ray}\n" + + super().__init__( + dals( + f""" + HTTP {status_code} {reason} for url <{url}> + Elapsed: {elapsed_time} + {cf_ray} + """ + ) + # since message may include newlines don't include in f-string/dals above + + message, + url=url, + status_code=status_code, + reason=reason, + elapsed_time=elapsed_time, + response_details=stringify(response, content_max_len=1024) or "", + json=body, + caused_by=caused_by, + ) + + +class CondaSSLError(CondaError): + pass + + +class AuthenticationError(CondaError): + pass + + +class PackagesNotFoundError(CondaError): + def __init__( + self, + packages: Iterable[MatchSpec | PackageRecord | str], + channel_urls: Iterable[str] = (), + ): + if channel_urls: + message = dals( + """ + The following packages are not available from current channels: + %(packages_formatted)s + + Current channels: + %(channels_formatted)s + + To search for alternate channels that may provide the conda package you're + looking for, navigate to + + https://anaconda.org + + and use the search bar at the top of the page. + """ + ) + from .base.context import context + + if context.use_only_tar_bz2: + message += dals( + """ + Note: 'use_only_tar_bz2' is enabled. This might be omitting some + packages from the index. Set this option to 'false' and retry. + """ + ) + packages_formatted = dashlist(packages) + channels_formatted = dashlist(channel_urls) + else: + message = dals( + """ + The following packages are missing from the target environment: + %(packages_formatted)s + """ + ) + packages_formatted = dashlist(packages) + channels_formatted = "" + + super().__init__( + message, + packages=packages, + packages_formatted=packages_formatted, + channel_urls=list(channel_urls), + channels_formatted=channels_formatted, + ) + + +class NoChannelsConfiguredError(CondaError): + def __init__(self, packages: Iterable[str] = ()): + packages_str = ", ".join(packages) if packages else "the requested packages" + + message = dals( + """ + No channels are configured. Conda requires at least one channel to search for packages. + + You have attempted to install: %(packages_str)s + + To fix this issue, you may do one of the following: + + 1. Add a channel for this command: + conda install -c %(packages_str)s + + 2. Configure channels permanently: + conda config --append channels + + 3. Create or modify your .condarc file to include channels. + + For more information, visit: https://docs.conda.io/projects/conda/en/stable/user-guide/configuration/use-condarc.html#channel-locations-channels + and https://docs.conda.io/projects/conda/en/stable/user-guide/concepts/channels.html#specifying-channels-when-installing-packages + """ + ) + + super().__init__( + message, + packages=list(packages), + packages_str=packages_str, + ) + + +class UnsatisfiableError(CondaError): + """An exception to report unsatisfiable dependencies. + + Args: + bad_deps: a list of tuples of objects (likely MatchSpecs). + chains: (optional) if True, the tuples are interpreted as chains + of dependencies, from top level to bottom. If False, the tuples + are interpreted as simple lists of conflicting specs. + + Returns: + Raises an exception with a formatted message detailing the + unsatisfiable specifications. + """ + + def _format_chain_str(self, bad_deps: Iterable[Iterable[MatchSpec]]): + chains = {} + for dep in sorted(bad_deps, key=len, reverse=True): + dep1 = [s.partition(" ") for s in dep[1:]] + key = (dep[0],) + tuple(v[0] for v in dep1) + vals = ("",) + tuple(v[2] for v in dep1) + found = False + for key2, csets in chains.items(): + if key2[: len(key)] == key: + for cset, val in zip(csets, vals): + cset.add(val) + found = True + if not found: + chains[key] = [{val} for val in vals] + for key, csets in chains.items(): + deps = [] + for name, cset in zip(key, csets): + if "" not in cset: + pass + elif len(cset) == 1: + cset.clear() + else: + cset.remove("") + cset.add("*") + if name[0] == "@": + name = "feature:" + name[1:] + deps.append( + "{} {}".format(name, "|".join(sorted(cset))) if cset else name + ) + chains[key] = " -> ".join(deps) + return [chains[key] for key in sorted(chains.keys())] + + def __init__( + self, + bad_deps: Iterable[Iterable[MatchSpec]], + chains: bool = True, + strict: bool = False, + ): + from .models.match_spec import MatchSpec + + messages = { + "python": dals( + """ + +The following specifications were found +to be incompatible with the existing python installation in your environment: + +Specifications:\n{specs} + +Your python: {ref} + +If python is on the left-most side of the chain, that's the version you've asked for. +When python appears to the right, that indicates that the thing on the left is somehow +not available for the python version you are constrained to. Note that conda will not +change your python version to a different minor version unless you explicitly specify +that. + + """ + ), + "request_conflict_with_history": dals( + """ + +The following specifications were found to be incompatible with a past +explicit spec that is not an explicit spec in this operation ({ref}):\n{specs} + + """ + ), + "direct": dals( + """ + +The following specifications were found to be incompatible with each other: + """ + ), + "virtual_package": dals( + """ + +The following specifications were found to be incompatible with your system:\n{specs} + +Your installed version is: {ref} +""" + ), + } + + msg = "" + self.unsatisfiable = [] + if len(bad_deps) == 0: + msg += """ +Did not find conflicting dependencies. If you would like to know which +packages conflict ensure that you have enabled unsatisfiable hints. + +conda config --set unsatisfiable_hints True + """ + else: + for class_name, dep_class in bad_deps.items(): + if dep_class: + _chains = [] + if class_name == "direct": + msg += messages["direct"] + last_dep_entry = {d[0][-1].name for d in dep_class} + dep_constraint_map = {} + for dep in dep_class: + if dep[0][-1].name in last_dep_entry: + if not dep_constraint_map.get(dep[0][-1].name): + dep_constraint_map[dep[0][-1].name] = [] + dep_constraint_map[dep[0][-1].name].append(dep[0]) + msg += "\nOutput in format: Requested package -> Available versions" + for dep, chain in dep_constraint_map.items(): + if len(chain) > 1: + msg += f"\n\nPackage {dep} conflicts for:\n" + msg += "\n".join( + [" -> ".join([str(i) for i in c]) for c in chain] + ) + self.unsatisfiable += [ + tuple(entries) for entries in chain + ] + else: + for dep_chain, installed_blocker in dep_class: + # Remove any target values from the MatchSpecs, convert to strings + dep_chain = [ + str(MatchSpec(dep, target=None)) for dep in dep_chain + ] + _chains.append(dep_chain) + + if _chains: + _chains = self._format_chain_str(_chains) + else: + _chains = [", ".join(c) for c in _chains] + msg += messages[class_name].format( + specs=dashlist(_chains), ref=installed_blocker + ) + if strict: + msg += ( + "\nNote that strict channel priority may have removed " + "packages required for satisfiability." + ) + + super().__init__(msg) + + +class RemoveError(CondaError): + def __init__(self, message: str): + msg = f"{message}" + super().__init__(msg) + + +class DisallowedPackageError(CondaError): + def __init__(self, package_ref: PackageRecord, **kwargs): + from .models.records import PackageRecord + + package_ref = PackageRecord.from_objects(package_ref) + message = ( + "The package '%(dist_str)s' is disallowed by configuration.\n" + "See 'conda config --show disallowed_packages'." + ) + super().__init__( + message, package_ref=package_ref, dist_str=package_ref.dist_str(), **kwargs + ) + + +class SpecsConfigurationConflictError(CondaError): + def __init__( + self, + requested_specs: Iterable[MatchSpec], + pinned_specs: Iterable[MatchSpec], + prefix: PathType, + ): + message = dals( + """ + Requested specs conflict with configured specs. + requested specs: {requested_specs_formatted} + pinned specs: {pinned_specs_formatted} + Use 'conda config --show-sources' to look for 'pinned_specs' and 'track_features' + configuration parameters. Pinned specs may also be defined in the file + {pinned_specs_path}. + """ + ).format( + requested_specs_formatted=dashlist(requested_specs, 4), + pinned_specs_formatted=dashlist(pinned_specs, 4), + pinned_specs_path=join(prefix, PREFIX_PINNED_FILE), + ) + super().__init__( + message, + requested_specs=requested_specs, + pinned_specs=pinned_specs, + prefix=prefix, + ) + + +class CondaIndexError(CondaError, IndexError): + def __init__(self, message: str): + msg = f"{message}" + super().__init__(msg) + + +class CondaValueError(CondaError, ValueError): + def __init__(self, message: str, *args, **kwargs): + super().__init__(message, *args, **kwargs) + + +class CyclicalDependencyError(CondaError, ValueError): + def __init__(self, packages_with_cycles: Iterable[PackageRecord], **kwargs): + from .models.records import PackageRecord + + packages_with_cycles = tuple( + PackageRecord.from_objects(p) for p in packages_with_cycles + ) + message = f"Cyclic dependencies exist among these items: {dashlist(p.dist_str() for p in packages_with_cycles)}" + super().__init__(message, packages_with_cycles=packages_with_cycles, **kwargs) + + +class CorruptedEnvironmentError(CondaError): + def __init__( + self, + environment_location: PathType, + corrupted_file: PathType, + **kwargs, + ): + message = dals( + """ + The target environment has been corrupted. Corrupted environments most commonly + occur when the conda process is force-terminated while in an unlink-link + transaction. + environment location: %(environment_location)s + corrupted file: %(corrupted_file)s + """ + ) + super().__init__( + message, + environment_location=environment_location, + corrupted_file=corrupted_file, + **kwargs, + ) + + +class CondaHistoryError(CondaError): + def __init__(self, message: str): + msg = f"{message}" + super().__init__(msg) + + +class CondaUpgradeError(CondaError): + def __init__(self, message: str): + msg = f"{message}" + super().__init__(msg) + + +class CondaVerificationError(CondaError): + def __init__(self, message: str): + super().__init__(message) + + +class SafetyError(CondaError): + def __init__(self, message: str): + super().__init__(message) + + +class CondaMemoryError(CondaError, MemoryError): + def __init__(self, caused_by: Any, **kwargs): + message = "The conda process ran out of memory. Increase system memory and/or try again." + super().__init__(message, caused_by=caused_by, **kwargs) + + +class NotWritableError(CondaError, OSError): + def __init__(self, path: PathType, errno: int, **kwargs): + kwargs.update( + { + "path": path, + "errno": errno, + } + ) + if on_win: + message = dals( + """ + The current user does not have write permissions to a required path. + path: %(path)s + """ + ) + else: + message = dals( + """ + The current user does not have write permissions to a required path. + path: %(path)s + uid: %(uid)s + gid: %(gid)s + + If you feel that permissions on this path are set incorrectly, you can manually + change them by executing + + $ sudo chown %(uid)s:%(gid)s %(path)s + + In general, it's not advisable to use 'sudo conda'. + """ + ) + kwargs.update( + { + "uid": os.geteuid(), + "gid": os.getegid(), + } + ) + super().__init__(message, **kwargs) + self.errno = errno + + +class NoWritableEnvsDirError(CondaError): + def __init__(self, envs_dirs: Iterable[PathType], **kwargs): + message = f"No writeable envs directories configured.{dashlist(envs_dirs)}" + super().__init__(message, envs_dirs=envs_dirs, **kwargs) + + +class NoWritablePkgsDirError(CondaError): + def __init__(self, pkgs_dirs: Iterable[PathType], **kwargs): + message = f"No writeable pkgs directories configured.{dashlist(pkgs_dirs)}" + super().__init__(message, pkgs_dirs=pkgs_dirs, **kwargs) + + +class EnvironmentIsFrozenError(CondaError): + def __init__(self, prefix: PathType, message: str = "", **kwargs): + error = f"Cannot modify '{prefix}'. The environment is marked as frozen. " + if message: + error += "Reason:\n\n" + error += indent(message, " ") + error += "\n\n" + error += ( + "You can bypass these protections with the `--override-frozen` flag," + " at your own risk." + ) + super().__init__(error, **kwargs) + + +class EnvironmentNotWritableError(CondaError): + def __init__(self, environment_location: PathType, **kwargs): + kwargs.update( + { + "environment_location": environment_location, + } + ) + if on_win: + message = dals( + """ + The current user does not have write permissions to the target environment. + environment location: %(environment_location)s + """ + ) + else: + message = dals( + """ + The current user does not have write permissions to the target environment. + environment location: %(environment_location)s + uid: %(uid)s + gid: %(gid)s + """ + ) + kwargs.update( + { + "uid": os.geteuid(), + "gid": os.getegid(), + } + ) + super().__init__(message, **kwargs) + + +class CondaDependencyError(CondaError): + def __init__(self, message: str): + super().__init__(message) + + +class BinaryPrefixReplacementError(CondaError): + def __init__( + self, + path: PathType, + placeholder: str, + new_prefix: PathType, + original_data_length: int, + new_data_length: int, + ): + message = dals( + """ + Refusing to replace mismatched data length in binary file. + path: %(path)s + placeholder: %(placeholder)s + new prefix: %(new_prefix)s + original data Length: %(original_data_length)d + new data length: %(new_data_length)d + """ + ) + kwargs = { + "path": path, + "placeholder": placeholder, + "new_prefix": new_prefix, + "original_data_length": original_data_length, + "new_data_length": new_data_length, + } + super().__init__(message, **kwargs) + + +class InvalidSpec(CondaError, ValueError): + def __init__(self, message: str, **kwargs): + super().__init__(message, **kwargs) + + +class InvalidVersionSpec(InvalidSpec): + def __init__(self, invalid_spec: str | MatchSpec, details: str): + message = "Invalid version '%(invalid_spec)s': %(details)s" + super().__init__(message, invalid_spec=invalid_spec, details=details) + + +class InvalidMatchSpec(InvalidSpec): + def __init__(self, invalid_spec: str | MatchSpec, details: str): + message = "Invalid spec '%(invalid_spec)s': %(details)s" + super().__init__(message, invalid_spec=invalid_spec, details=details) + + +class EncodingError(CondaError): + def __init__(self, caused_by: Any, **kwargs): + message = ( + dals( + """ + A unicode encoding or decoding error has occurred. + Python 2 is the interpreter under which conda is running in your base environment. + Replacing your base environment with one having Python 3 may help resolve this issue. + If you still have a need for Python 2 environments, consider using 'conda create' + and 'conda activate'. For example: + + $ conda create -n py2 python=2 + $ conda activate py2 + + Error details: %r + + """ + ) + % caused_by + ) + super().__init__(message, caused_by=caused_by, **kwargs) + + +class NoSpaceLeftError(CondaError): + def __init__(self, caused_by: Any, **kwargs): + message = "No space left on devices." + super().__init__(message, caused_by=caused_by, **kwargs) + + +class CondaEnvException(CondaError): + def __init__(self, message: str, *args, **kwargs): + msg = f"{message}" + super().__init__(msg, *args, **kwargs) + + +class EnvironmentFileInvalid(CondaEnvException): + def __init__(self, msg: str, *args, **kwargs): + msg = f"Provided environment.yaml is invalid: {msg}" + super().__init__(msg, *args, **kwargs) + + +class EnvironmentFileNotFound(CondaEnvException): + def __init__(self, filename: PathType, *args, **kwargs): + msg = f"'{filename}' file not found" + self.filename = filename + super().__init__(msg, *args, **kwargs) + + +class EnvironmentFileExtensionNotValid(CondaEnvException): + def __init__(self, filename: PathType, *args, **kwargs): + msg = f"'{filename}' file extension must be one of '.txt', '.yaml' or '.yml'" + self.filename = filename + super().__init__(msg, *args, **kwargs) + + +class EnvironmentFileTypeMismatchError(CondaError): + def __init__(self, file_types: dict[str, str], *args, **kwargs): + type_groups = defaultdict(list) + for file, file_type in file_types.items(): + type_groups[file_type].append(file) + + lines = ["Cannot mix environment file formats.\n"] + + for file_type, files in type_groups.items(): + lines.extend(f"'{file}' is a {file_type} format file" for file in files) + + super().__init__("\n".join(lines), *args, **kwargs) + + +class EnvironmentFileEmpty(CondaEnvException): + def __init__(self, filename: PathType, *args, **kwargs): + self.filename = filename + msg = f"Environment file '{filename}' is empty." + super().__init__(msg, *args, **kwargs) + + +class EnvironmentFileNotDownloaded(CondaError): + def __init__(self, username: str, packagename: str, *args, **kwargs): + msg = f"{username}/{packagename} file not downloaded" + self.username = username + self.packagename = packagename + super().__init__(msg, *args, **kwargs) + + +class PluginError(CondaError): + pass + + +class SpecNotFound(CondaError): + def __init__(self, msg: str, *args, **kwargs): + super().__init__(msg, *args, **kwargs) + + +class EnvironmentSpecPluginNotDetected(SpecNotFound): + def __init__( + self, + name: str, + plugin_names: Iterable[str], + autodetect_disabled_plugins: Iterable[str] = (), + *args, + **kwargs, + ): + self.name = name + msg = dals( + f""" + Environment at {name} is not able to be detected by any installed environment specifier plugins. + + Available plugins: {dashlist(plugin_names, 16)} + + """ + ) + if autodetect_disabled_plugins: + msg += dals( + """ + Found compatible plugins but they must be explicitly selected. + Request conda to use these plugins by providing + the cli argument `--environment-spec PLUGIN_NAME`: + """ + ) + dashlist(autodetect_disabled_plugins, 4) + super().__init__(msg, *args, **kwargs) + + +class EnvironmentExporterNotDetected(CondaError): + def __init__( + self, + filename: str, + exporters: Iterable[CondaEnvironmentExporter], + *args, + **kwargs, + ): + self.filename = filename + supported_filenames: list[str] = [] + available_formats: list[str] = [] + for exporter in exporters: + supported_filenames.extend( + f"{filename:<20} (format: {exporter.name})" + for filename in exporter.default_filenames + ) + available_formats.append( + f"{exporter.name:<20} (aliases: {', '.join(exporter.aliases)})" + if exporter.aliases + else exporter.name + ) + msg = ( + f"No environment exporter plugin found for filename '{filename}'.\n" + f"\n" + f"Supported filenames:{dashlist(supported_filenames)}\n" + f"\n" + f"Available formats:{dashlist(available_formats)}\n" + f"\n" + f"Use conda export --format=FORMAT to specify the export format explicitly, " + f"or rename your file to match a supported filename pattern." + ) + super().__init__(msg, *args, **kwargs) + + +class SpecNotFoundInPackageCache(CondaError): + def __init__(self, msg: str, *args, **kwargs): + super().__init__(msg, *args, **kwargs) + + +def maybe_raise(error: BaseException, context: Context): + if isinstance(error, CondaMultiError): + groups = groupby(lambda e: isinstance(e, ClobberError), error.errors) + clobber_errors = groups.get(True, ()) + groups = groupby(lambda e: isinstance(e, SafetyError), groups.get(False, ())) + safety_errors = groups.get(True, ()) + other_errors = groups.get(False, ()) + + if ( + (safety_errors and context.safety_checks == SafetyChecks.enabled) + or ( + clobber_errors + and context.path_conflict == PathConflict.prevent + and not context.clobber + ) + or other_errors + ): + raise error + elif (safety_errors and context.safety_checks == SafetyChecks.warn) or ( + clobber_errors + and context.path_conflict == PathConflict.warn + and not context.clobber + ): + print_conda_exception(error) + + elif isinstance(error, ClobberError): + if context.path_conflict == PathConflict.prevent and not context.clobber: + raise error + elif context.path_conflict == PathConflict.warn and not context.clobber: + print_conda_exception(error) + + elif isinstance(error, SafetyError): + if context.safety_checks == SafetyChecks.enabled: + raise error + elif context.safety_checks == SafetyChecks.warn: + print_conda_exception(error) + + else: + raise error + + +def print_conda_exception(exc_val: CondaError, exc_tb: TracebackType | None = None): + from .base.context import context + + rc = getattr(exc_val, "return_code", None) + if context.debug or (not isinstance(exc_val, DryRunExit) and context.info): + print(_format_exc(exc_val, exc_tb), file=sys.stderr) + elif context.json: + if isinstance(exc_val, DryRunExit): + return + logger = getLogger("conda.stdout" if rc else "conda.stderr") + exc_json = json_dumps(exc_val.dump_map(), sort_keys=True) + logger.info(f"{exc_json}\n") + else: + stderrlog = getLogger("conda.stderr") + stderrlog.error("\n%r\n", exc_val) + # An alternative which would allow us not to reload sys with newly setdefaultencoding() + # is to not use `%r`, e.g.: + # Still, not being able to use `%r` seems too great a price to pay. + # stderrlog.error("\n" + exc_val.__repr__() + \n") + + +def _format_exc( + exc_val: BaseException | None = None, exc_tb: TracebackType | None = None +): + if exc_val is None: + exc_type, exc_val, exc_tb = sys.exc_info() + else: + exc_type = type(exc_val) + if exc_tb: + formatted_exception = format_exception(exc_type, exc_val, exc_tb) + else: + formatted_exception = format_exception_only(exc_type, exc_val) + return "".join(formatted_exception) + + +class InvalidInstaller(Exception): + def __init__(self, name: str): + msg = f"Unable to load installer for {name}" + super().__init__(msg) + + +class OfflineError(CondaError, RuntimeError): + pass + + +class CondaUpdatePackageError(CondaError): + def __init__(self, spec: str | list[str]): + spec_format = dashlist(spec, 4) if isinstance(spec, list) else spec + msg = ( + f"`conda update` only supports name-only spec, but received: {spec_format}\n" + f"Use `conda install` to install a specific version of a package." + ) + super().__init__(msg) diff --git a/data/miniconda3/lib/python3.13/site-packages/conda/exports.py b/data/miniconda3/lib/python3.13/site-packages/conda/exports.py new file mode 100644 index 0000000000000000000000000000000000000000..db7d8fb88b934edd1a9c8300d1dccba0bdb42213 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda/exports.py @@ -0,0 +1,395 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Backported exports for conda-build.""" + +from __future__ import annotations + +from builtins import input # noqa: UP029 +from io import StringIO +from typing import TYPE_CHECKING + +from . import CondaError +from .base.constants import ( + DEFAULT_CHANNELS, + DEFAULT_CHANNELS_UNIX, + DEFAULT_CHANNELS_WIN, + PREFIX_PLACEHOLDER, +) +from .base.context import ( # noqa: F401 + context, + non_x86_machines, + reset_context, + sys_rc_path, +) +from .cli.common import spec_from_line, specs_from_args, specs_from_url # noqa: F401 +from .cli.conda_argparse import ArgumentParser # noqa: F401 +from .cli.helpers import ( # noqa: F401 + add_parser_channels, + add_parser_prefix, +) +from .common import compat # noqa: F401 +from .common.serialize.json import CondaJSONEncoder +from .common.toposort import _toposort # noqa: F401 +from .core.index import ( + Index, + dist_str_in_index, # noqa: F401 +) +from .core.package_cache_data import ProgressiveFetchExtract # noqa: F401 +from .core.prefix_data import delete_prefix_from_linked_data +from .core.solve import Solver # noqa: F401 +from .core.subdir_data import cache_fn_url # noqa: F401 +from .deprecations import deprecated +from .exceptions import ( + CondaHTTPError, + CondaOSError, + LinkError, + LockError, + PaddingError, + PathNotFoundError, + UnsatisfiableError, +) +from .gateways.connection.download import TmpDownload # noqa: F401 +from .gateways.connection.download import download as _download +from .gateways.connection.session import CondaSession # noqa: F401 +from .gateways.disk.create import TemporaryDirectory # noqa: F401 +from .gateways.disk.delete import delete_trash # noqa: F401 +from .gateways.disk.link import lchmod # noqa: F401 +from .gateways.subprocess import ACTIVE_SUBPROCESSES, subprocess_call # noqa: F401 +from .misc import untracked, walk_prefix # noqa: F401 +from .models.channel import Channel, get_conda_build_local_url # noqa: F401 +from .models.dist import Dist +from .models.enums import FileMode, PathEnum # noqa: F401 +from .models.version import VersionOrder, normalized_version # noqa: F401 +from .resolve import ( # noqa: F401 + MatchSpec, + Resolve, + ResolvePackageNotFound, + Unsatisfiable, +) +from .utils import human_bytes, url_path # noqa: F401 + +if TYPE_CHECKING: + from typing import Any + +reset_context() # initialize context when conda.exports is imported + + +NoPackagesFound = NoPackagesFoundError = ResolvePackageNotFound +non_x86_linux_machines = non_x86_machines +arch_name = context.arch_name +binstar_upload = context.anaconda_upload +bits = context.bits +default_prefix = context.default_prefix +default_python = context.default_python +envs_dirs = context.envs_dirs +pkgs_dirs = context.pkgs_dirs +platform = context.platform +root_dir = context.root_prefix +root_writable = context.root_writable +subdir = context.subdir +conda_build = context.conda_build +get_rc_urls = lambda: list(context.channels) +get_local_urls = lambda: list(get_conda_build_local_url()) or [] +load_condarc = lambda fn: reset_context([fn]) +PaddingError = PaddingError +LinkError = LinkError +CondaOSError = CondaOSError +# Replacements for six exports for compatibility + + +# FUTURE: conda 26.3+ remove this +def __getattr__(name: str) -> Any: + # lazy load the deprecated module + if name == "plan": + from . import plan + + return plan + + raise AttributeError(f"module '{__name__}' has no attribute '{name}'") + + +deprecated.constant( + "26.3", + "26.9", + "EntityEncoder", + CondaJSONEncoder, + addendum="Use `conda.common.serialize.json.CondaJSONEncoder` instead.", +) +del CondaJSONEncoder + +deprecated.constant( + "26.9", + "27.3", + "input", + input, + addendum="Use `builtins.input` instead.", +) +del input + +deprecated.constant( + "26.9", + "27.3", + "StringIO", + StringIO, + addendum="Use `io.StringIO` instead.", +) +del StringIO + +deprecated.constant( + "26.9", + "27.3", + "PY3", + True, + addendum="Python 2 is no longer supported.", +) + +deprecated.constant( + "26.9", + "27.3", + "string_types", + str, + addendum="Use `str` instead.", +) + +deprecated.constant( + "26.9", + "27.3", + "text_type", + str, + addendum="Use `str` instead.", +) + +deprecated.constant( + "26.9", + "27.3", + "DEFAULT_CHANNELS", + DEFAULT_CHANNELS, + addendum="Use `conda.base.constants.DEFAULT_CHANNELS` instead.", +) +del DEFAULT_CHANNELS + +deprecated.constant( + "26.9", + "27.3", + "DEFAULT_CHANNELS_UNIX", + DEFAULT_CHANNELS_UNIX, + addendum="Use `conda.base.constants.DEFAULT_CHANNELS_UNIX` instead.", +) +del DEFAULT_CHANNELS_UNIX + +deprecated.constant( + "26.9", + "27.3", + "DEFAULT_CHANNELS_WIN", + DEFAULT_CHANNELS_WIN, + addendum="Use `conda.base.constants.DEFAULT_CHANNELS_WIN` instead.", +) +del DEFAULT_CHANNELS_WIN + +deprecated.constant( + "26.9", + "27.3", + "PREFIX_PLACEHOLDER", + PREFIX_PLACEHOLDER, + addendum="Use `conda.base.constants.PREFIX_PLACEHOLDER` instead.", +) + +deprecated.constant( + "26.9", + "27.3", + "_PREFIX_PLACEHOLDER", + PREFIX_PLACEHOLDER, + addendum="Use `conda.base.constants.PREFIX_PLACEHOLDER` instead.", +) + +deprecated.constant( + "26.9", + "27.3", + "prefix_placeholder", + PREFIX_PLACEHOLDER, + addendum="Use `conda.base.constants.PREFIX_PLACEHOLDER` instead.", +) +del PREFIX_PLACEHOLDER + +deprecated.constant( + "26.9", + "27.3", + "CondaError", + CondaError, + addendum="Use `conda.CondaError` instead.", +) +del CondaError + +deprecated.constant( + "26.9", + "27.3", + "CondaHTTPError", + CondaHTTPError, + addendum="Use `conda.exceptions.CondaHTTPError` instead.", +) +del CondaHTTPError + +deprecated.constant( + "26.9", + "27.3", + "CondaOSError", + CondaOSError, + addendum="Use `conda.exceptions.CondaOSError` instead.", +) +del CondaOSError + +deprecated.constant( + "26.9", + "27.3", + "LinkError", + LinkError, + addendum="Use `conda.exceptions.LinkError` instead.", +) +del LinkError + +deprecated.constant( + "26.9", + "27.3", + "LockError", + LockError, + addendum="Use `conda.exceptions.LockError` instead.", +) +del LockError + +deprecated.constant( + "26.9", + "27.3", + "PaddingError", + PaddingError, + addendum="Use `conda.exceptions.PaddingError` instead.", +) +del PaddingError + +deprecated.constant( + "26.9", + "27.3", + "PathNotFoundError", + PathNotFoundError, + addendum="Use `conda.exceptions.PathNotFoundError` instead.", +) + +deprecated.constant( + "26.9", + "27.3", + "CondaFileNotFoundError", + PathNotFoundError, + addendum="Use `conda.exceptions.PathNotFoundError` instead.", +) +del PathNotFoundError + +deprecated.constant( + "26.9", + "27.3", + "UnsatisfiableError", + UnsatisfiableError, + addendum="Use `conda.exceptions.UnsatisfiableError` instead.", +) +del UnsatisfiableError + + +def get_default_urls(): + from .base.constants import DEFAULT_CHANNELS + + return DEFAULT_CHANNELS + + +def rm_rf(path, max_retries=5, trash=True): + from .gateways.disk.delete import rm_rf + + rm_rf(path) + delete_prefix_from_linked_data(path) + + +def get_index( + channel_urls=(), + prepend=True, + platform=None, + use_local=False, + use_cache=False, + unknown=None, + prefix=None, +): + index = Index( + channel_urls, prepend, platform, use_local, use_cache, unknown, prefix + ) + return {Dist(prec): prec for prec in index.values()} + + +def package_cache(): + from .core.package_cache_data import PackageCacheData + + class package_cache: + def __contains__(self, dist): + return bool( + PackageCacheData.first_writable().get(Dist(dist).to_package_ref(), None) + ) + + def keys(self): + return (Dist(v) for v in PackageCacheData.first_writable().values()) + + def __delitem__(self, dist): + PackageCacheData.first_writable().remove(Dist(dist).to_package_ref()) + + return package_cache() + + +def linked_data(prefix, ignore_channels=False): + """Return a dictionary of the linked packages in prefix.""" + from .core.prefix_data import PrefixData + from .models.dist import Dist + + pd = PrefixData(prefix) + return { + Dist(prefix_record): prefix_record + for prefix_record in pd._prefix_records.values() + } + + +def linked(prefix, ignore_channels=False): + """Return the Dists of linked packages in prefix.""" + from .models.enums import PackageType + + conda_package_types = PackageType.conda_package_types() + ld = linked_data(prefix, ignore_channels=ignore_channels).items() + return { + dist + for dist, prefix_rec in ld + if prefix_rec.package_type in conda_package_types + } + + +# exports +def is_linked(prefix, dist): + """ + Return the install metadata for a linked package in a prefix, or None + if the package is not linked in the prefix. + """ + # FIXME Functions that begin with `is_` should return True/False + from .core.prefix_data import PrefixData + + pd = PrefixData(prefix) + prefix_record = pd.get(dist.name, None) + if prefix_record is None: + return None + elif MatchSpec(dist).match(prefix_record): + return prefix_record + else: + return None + + +def download( + url, + dst_path, + session=None, + md5sum=None, + urlstxt=False, + retries=3, + sha256=None, + size=None, +): + return _download(url, dst_path, md5=md5sum, sha256=sha256, size=size) diff --git a/data/miniconda3/lib/python3.13/site-packages/conda/history.py b/data/miniconda3/lib/python3.13/site-packages/conda/history.py new file mode 100644 index 0000000000000000000000000000000000000000..7947531acbe3146f180e1310271fc8b745082cc3 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda/history.py @@ -0,0 +1,426 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Tools interfacing with conda's history file.""" + +from __future__ import annotations + +import logging +import os +import re +import sys +import time +import warnings +from ast import literal_eval +from errno import EACCES, EPERM, EROFS +from itertools import islice +from operator import itemgetter +from os.path import isdir, isfile, join +from textwrap import dedent +from typing import TYPE_CHECKING + +from . import __version__ as CONDA_VERSION +from .auxlib.ish import dals +from .base.constants import DEFAULTS_CHANNEL_NAME +from .base.context import context +from .common.compat import ensure_text_type, open_utf8 +from .common.iterators import groupby_to_dict as groupby +from .common.path import paths_equal +from .core.prefix_data import PrefixData +from .exceptions import CondaHistoryError, NotWritableError +from .gateways.disk.update import touch +from .models.dist import dist_str_to_quad +from .models.match_spec import MatchSpec +from .models.version import VersionOrder, version_relation_re + +if TYPE_CHECKING: + from .common.path import PathType + +log = logging.getLogger(__name__) + + +class CondaHistoryWarning(Warning): + pass + + +def write_head(fo): + fo.write("==> {} <==\n".format(time.strftime("%Y-%m-%d %H:%M:%S"))) + fo.write("# cmd: {}\n".format(" ".join(ensure_text_type(s) for s in sys.argv))) + fo.write( + "# conda version: {}\n".format(".".join(islice(CONDA_VERSION.split("."), 3))) + ) + + +def is_diff(content): + return any(s.startswith(("-", "+")) for s in content) + + +def pretty_diff(diff): + added = {} + removed = {} + for s in diff: + fn = s[1:] + name, version, _, channel = dist_str_to_quad(fn) + if channel != DEFAULTS_CHANNEL_NAME: + version += f" ({channel})" + if s.startswith("-"): + removed[name.lower()] = version + elif s.startswith("+"): + added[name.lower()] = version + changed = set(added) & set(removed) + for name in sorted(changed): + yield f" {name} {{{removed[name]} -> {added[name]}}}" + for name in sorted(set(removed) - changed): + yield f"-{name}-{removed[name]}" + for name in sorted(set(added) - changed): + yield f"+{name}-{added[name]}" + + +def pretty_content(content): + if is_diff(content): + return pretty_diff(content) + else: + return iter(sorted(content)) + + +class History: + com_pat = re.compile(r"#\s*cmd:\s*(.+)") + spec_pat = re.compile(r"#\s*(\w+)\s*specs:\s*(.+)?") + conda_v_pat = re.compile(r"#\s*conda version:\s*(.+)") + + def __init__(self, prefix: PathType): + self.prefix = prefix + self.meta_dir = join(prefix, "conda-meta") + self.path = join(self.meta_dir, "history") + + def __enter__(self): + self.init_log_file() + return self + + def __exit__(self, exc_type, exc_value, traceback): + self.update() + + def init_log_file(self): + touch(self.path, True) + + def file_is_empty(self): + return os.stat(self.path).st_size == 0 + + def update(self) -> None: + """Update the history file (creating a new one if necessary).""" + try: + try: + last = set(self.get_state()) + except CondaHistoryError as e: + warnings.warn(f"Error in {self.path}: {e}", CondaHistoryWarning) + return + pd = PrefixData(self.prefix) + curr = {prefix_rec.dist_str() for prefix_rec in pd.iter_records()} + self.write_changes(last, curr) + except OSError as e: + if e.errno in (EACCES, EPERM, EROFS): + raise NotWritableError(self.path, e.errno) + else: + raise + + def parse(self) -> list[tuple[str, set[str], list[str]]]: + """Parse the history file. + + Return a list of tuples(datetime strings, set of distributions/diffs, comments). + + Comments appearing before the first section header (e.g. ``==> 2024-01-01 00:00:00 <==``) + in the history file will be ignored. + """ + res = [] + if not isfile(self.path): + return res + sep_pat = re.compile(r"==>\s*(.+?)\s*<==") + with open_utf8(self.path) as f: + lines = f.read().splitlines() + for line in lines: + line = line.strip() + if not line: + continue + m = sep_pat.match(line) + if m: + res.append((m.group(1), set(), [])) + elif line.startswith("#") and res: + res[-1][2].append(line) + elif res: + res[-1][1].add(line) + return res + + @staticmethod + def _parse_old_format_specs_string(specs_string): + """ + Parse specifications string that use conda<4.5 syntax. + + Examples + -------- + - "param >=1.5.1,<2.0'" + - "python>=3.5.1,jupyter >=1.0.0,<2.0,matplotlib >=1.5.1,<2.0" + """ + specs = [] + for spec in specs_string.split(","): + # If the spec starts with a version qualifier, then it actually belongs to the + # previous spec. But don't try to join if there was no previous spec. + if version_relation_re.match(spec) and specs: + specs[-1] = ",".join([specs[-1], spec]) + else: + specs.append(spec) + return specs + + @classmethod + def _parse_comment_line(cls, line): + """ + Parse comment lines in the history file. + + These lines can be of command type or action type. + + Examples + -------- + - "# cmd: /scratch/mc3/bin/conda install -c conda-forge param>=1.5.1,<2.0" + - "# install specs: python>=3.5.1,jupyter >=1.0.0,<2.0,matplotlib >=1.5.1,<2.0" + """ + item = {} + m = cls.com_pat.match(line) + if m: + argv = m.group(1).split() + if argv[0].endswith("conda"): + argv[0] = "conda" + item["cmd"] = argv + + m = cls.conda_v_pat.match(line) + if m: + item["conda_version"] = m.group(1) + + m = cls.spec_pat.match(line) + if m: + action, specs_string = m.groups() + specs_string = specs_string or "" + item["action"] = action + + if specs_string.startswith("["): + specs = literal_eval(specs_string) + elif "[" not in specs_string: + specs = History._parse_old_format_specs_string(specs_string) + + specs = [spec for spec in specs if spec and not spec.endswith("@")] + + if specs and action in ("update", "install", "create"): + item["update_specs"] = item["specs"] = specs + elif specs and action in ("remove", "uninstall"): + item["remove_specs"] = item["specs"] = specs + elif specs and action in ("neutered",): + item["neutered_specs"] = item["specs"] = specs + + return item + + def get_user_requests(self): + """Return a list of user requested items. + + Each item is a dict with the following keys: + 'date': the date and time running the command + 'cmd': a list of argv of the actual command which was run + 'action': install/remove/update + 'specs': the specs being used + """ + res = [] + for dt, unused_cont, comments in self.parse(): + item = {"date": dt} + for line in comments: + comment_items = self._parse_comment_line(line) + item.update(comment_items) + + if "cmd" in item: + res.append(item) + + dists = groupby(itemgetter(0), unused_cont) + item["unlink_dists"] = dists.get("-", ()) + item["link_dists"] = dists.get("+", ()) + + conda_versions_from_history = tuple( + x["conda_version"] for x in res if "conda_version" in x + ) + if conda_versions_from_history and not context.allow_conda_downgrades: + minimum_conda_version = sorted( + conda_versions_from_history, key=VersionOrder + )[-1] + minimum_major_minor = ".".join(islice(minimum_conda_version.split("."), 2)) + current_major_minor = ".".join(islice(CONDA_VERSION.split("."), 2)) + if VersionOrder(current_major_minor) < VersionOrder(minimum_major_minor): + message = dals( + """ + This environment has previously been operated on by a conda version that's newer + than the conda currently being used. A newer version of conda is required. + target environment location: %(target_prefix)s + current conda version: %(conda_version)s + minimum conda version: %(minimum_version)s + """ + ) % { + "target_prefix": self.prefix, + "conda_version": CONDA_VERSION, + "minimum_version": minimum_major_minor, + } + if not paths_equal(self.prefix, context.root_prefix): + message += dedent( + """ + Update conda and try again. + $ conda install -p "%(base_prefix)s" "conda>=%(minimum_version)s" + """ + ) % { + "base_prefix": context.root_prefix, + "minimum_version": minimum_major_minor, + } + message += dedent( + """ + To work around this restriction, one can also set the config parameter + 'allow_conda_downgrades' to False at their own risk. + """ + ) + + # TODO: we need to rethink this. It's fine as a warning to try to get users + # to avoid breaking their system. However, right now it is preventing + # normal conda operation after downgrading conda. + # raise CondaUpgradeError(message) + + return res + + def get_requested_specs_map(self): + # keys are package names and values are specs + spec_map = {} + for request in self.get_user_requests(): + remove_specs = (MatchSpec(spec) for spec in request.get("remove_specs", ())) + for spec in remove_specs: + spec_map.pop(spec.name, None) + update_specs = (MatchSpec(spec) for spec in request.get("update_specs", ())) + spec_map.update((s.name, s) for s in update_specs) + # here is where the neutering takes effect, overriding past values + neutered_specs = ( + MatchSpec(spec) for spec in request.get("neutered_specs", ()) + ) + spec_map.update((s.name, s) for s in neutered_specs) + + # Conda hasn't always been good about recording when specs have been removed from + # environments. If the package isn't installed in the current environment, then we + # shouldn't try to force it here. + prefix_recs = {_.name for _ in PrefixData(self.prefix).iter_records()} + return {name: spec for name, spec in spec_map.items() if name in prefix_recs} + + def construct_states(self): + """Return a list of tuples(datetime strings, set of distributions).""" + res = [] + cur = set() + for dt, cont, unused_com in self.parse(): + if not is_diff(cont): + cur = cont + else: + for s in cont: + if s.startswith("-"): + cur.discard(s[1:]) + elif s.startswith("+"): + cur.add(s[1:]) + else: + raise CondaHistoryError(f"Did not expect: {s}") + res.append((dt, cur.copy())) + return res + + def get_state(self, rev=-1): + """Return the state, i.e. the set of distributions, for a given revision. + + Defaults to latest (which is the same as the current state when + the log file is up-to-date). + + Returns a list of dist_strs. + """ + states = self.construct_states() + if not states: + return set() + times, pkgs = zip(*states) + return pkgs[rev] + + def print_log(self): + for i, (date, content, unused_com) in enumerate(self.parse()): + print("%s (rev %d)" % (date, i)) + for line in pretty_content(content): + print(f" {line}") + print() + + def object_log(self): + result = [] + for i, (date, content, unused_com) in enumerate(self.parse()): + # Based on Mateusz's code; provides more details about the + # history event + event = { + "date": date, + "rev": i, + "install": [], + "remove": [], + "upgrade": [], + "downgrade": [], + } + added = {} + removed = {} + if is_diff(content): + for pkg in content: + name, version, build, channel = dist_str_to_quad(pkg[1:]) + if pkg.startswith("+"): + added[name.lower()] = (version, build, channel) + elif pkg.startswith("-"): + removed[name.lower()] = (version, build, channel) + + changed = set(added) & set(removed) + for name in sorted(changed): + old = removed[name] + new = added[name] + details = { + "old": "-".join((name,) + old), + "new": "-".join((name,) + new), + } + + if new > old: + event["upgrade"].append(details) + else: + event["downgrade"].append(details) + + for name in sorted(set(removed) - changed): + event["remove"].append("-".join((name,) + removed[name])) + + for name in sorted(set(added) - changed): + event["install"].append("-".join((name,) + added[name])) + else: + for pkg in sorted(content): + event["install"].append(pkg) + result.append(event) + return result + + def write_changes(self, last_state, current_state): + if not isdir(self.meta_dir): + os.makedirs(self.meta_dir) + with open(self.path, mode="a", encoding="utf-8") as fo: + write_head(fo) + for fn in sorted(last_state - current_state): + fo.write(f"-{fn}\n") + for fn in sorted(current_state - last_state): + fo.write(f"+{fn}\n") + + def write_specs(self, remove_specs=(), update_specs=(), neutered_specs=()): + remove_specs = [str(MatchSpec(s)) for s in remove_specs] + update_specs = [str(MatchSpec(s)) for s in update_specs] + neutered_specs = [str(MatchSpec(s)) for s in neutered_specs] + if any((update_specs, remove_specs, neutered_specs)): + with open(self.path, mode="a", encoding="utf-8") as fh: + if remove_specs: + fh.write(f"# remove specs: {remove_specs}\n") + if update_specs: + fh.write(f"# update specs: {update_specs}\n") + if neutered_specs: + fh.write(f"# neutered specs: {neutered_specs}\n") + + +if __name__ == "__main__": + from pprint import pprint + + # Don't use in context manager mode---it augments the history every time + h = History(sys.prefix) + pprint(h.get_user_requests()) + print(h.get_requested_specs_map()) diff --git a/data/miniconda3/lib/python3.13/site-packages/conda/instructions.py b/data/miniconda3/lib/python3.13/site-packages/conda/instructions.py new file mode 100644 index 0000000000000000000000000000000000000000..c38a07516e94ca52763d0dae2a9a6e56304077ec --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda/instructions.py @@ -0,0 +1,108 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Define the instruction set (constants) for conda operations.""" + +from logging import getLogger +from os.path import isfile, join + +from .core.link import UnlinkLinkTransaction +from .core.package_cache_data import ProgressiveFetchExtract +from .exceptions import CondaFileIOError +from .gateways.disk.link import islink + +log = getLogger(__name__) + +# op codes +CHECK_FETCH = "CHECK_FETCH" +FETCH = "FETCH" +CHECK_EXTRACT = "CHECK_EXTRACT" +EXTRACT = "EXTRACT" +RM_EXTRACTED = "RM_EXTRACTED" +RM_FETCHED = "RM_FETCHED" +PRINT = "PRINT" +PROGRESS = "PROGRESS" +SYMLINK_CONDA = "SYMLINK_CONDA" +UNLINK = "UNLINK" +LINK = "LINK" +UNLINKLINKTRANSACTION = "UNLINKLINKTRANSACTION" +PROGRESSIVEFETCHEXTRACT = "PROGRESSIVEFETCHEXTRACT" + + +PROGRESS_COMMANDS = {EXTRACT, RM_EXTRACTED} +ACTION_CODES = ( + CHECK_FETCH, + FETCH, + CHECK_EXTRACT, + EXTRACT, + UNLINK, + LINK, + SYMLINK_CONDA, + RM_EXTRACTED, + RM_FETCHED, +) + + +def PRINT_CMD(state, arg): # pragma: no cover + if arg.startswith(("Unlinking packages", "Linking packages")): + return + getLogger("conda.stdout.verbose").info(arg) + + +def FETCH_CMD(state, package_cache_entry): + raise NotImplementedError() + + +def EXTRACT_CMD(state, arg): + raise NotImplementedError() + + +def PROGRESSIVEFETCHEXTRACT_CMD(state, progressive_fetch_extract): # pragma: no cover + if not isinstance(progressive_fetch_extract, ProgressiveFetchExtract): + raise TypeError( + "'progressive_fetch_extract' must be a ProgressiveFetchExtract instance." + ) + progressive_fetch_extract.execute() + + +def UNLINKLINKTRANSACTION_CMD(state, arg): # pragma: no cover + unlink_link_transaction = arg + if not isinstance(unlink_link_transaction, UnlinkLinkTransaction): + raise TypeError( + "'unlink_link_transaction' must be an UnlinkLinkTransaction instance." + ) + unlink_link_transaction.execute() + + +def check_files_in_package(source_dir, files): + for f in files: + source_file = join(source_dir, f) + if isfile(source_file) or islink(source_file): + return True + else: + raise CondaFileIOError(source_file, f"File {f} does not exist in tarball") + + +# Map instruction to command (a python function) +commands = { + PRINT: PRINT_CMD, + FETCH: FETCH_CMD, + PROGRESS: lambda x, y: None, + EXTRACT: EXTRACT_CMD, + RM_EXTRACTED: lambda x, y: None, + RM_FETCHED: lambda x, y: None, + UNLINK: None, + LINK: None, + SYMLINK_CONDA: lambda x, y: None, + UNLINKLINKTRANSACTION: UNLINKLINKTRANSACTION_CMD, + PROGRESSIVEFETCHEXTRACT: PROGRESSIVEFETCHEXTRACT_CMD, +} + + +OP_ORDER = ( + RM_FETCHED, + FETCH, + RM_EXTRACTED, + EXTRACT, + UNLINK, + LINK, +) diff --git a/data/miniconda3/lib/python3.13/site-packages/conda/misc.py b/data/miniconda3/lib/python3.13/site-packages/conda/misc.py new file mode 100644 index 0000000000000000000000000000000000000000..e28be9f09a422f4503c8f3068e373b704985bdca --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda/misc.py @@ -0,0 +1,395 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Miscellaneous utility functions.""" + +from __future__ import annotations + +import os +import re +import shutil +from logging import getLogger +from os.path import abspath, dirname, exists, isdir, isfile, join, relpath +from typing import TYPE_CHECKING + +from .base.constants import EXPLICIT_MARKER +from .base.context import context +from .common.compat import on_mac, on_win, open_utf8 +from .common.io import dashlist +from .common.path import expand +from .common.url import is_url, join_url, path_to_url +from .core.index import Index +from .core.link import PrefixSetup, UnlinkLinkTransaction +from .core.package_cache_data import PackageCacheData, ProgressiveFetchExtract +from .core.prefix_data import PrefixData +from .deprecations import deprecated +from .exceptions import ( + DisallowedPackageError, + DryRunExit, + PackagesNotFoundError, + ParseError, + SpecNotFoundInPackageCache, +) +from .gateways.disk.delete import rm_rf +from .gateways.disk.link import islink, readlink, symlink +from .models.match_spec import ChannelMatch, MatchSpec +from .models.prefix_graph import PrefixGraph + +if TYPE_CHECKING: + from collections.abc import Iterable, Sequence + from typing import Any + + from .models.records import PackageCacheRecord, PackageRecord + + +log = getLogger(__name__) + + +def conda_installed_files(prefix, exclude_self_build=False): + """ + Return the set of files which have been installed (using conda) into + a given prefix. + """ + res = set() + for meta in PrefixData(prefix).iter_records(): + if exclude_self_build and "file_hash" in meta: + continue + res.update(set(meta.get("files", ()))) + return res + + +deprecated.constant( + "26.9", + "27.3", + "url_pat", + re.compile( + r"(?:(?P.+)(?:[/\\]))?" + r"(?P[^/\\#]+(?:\.conda|\.tar\.bz2))" + r"(?:#(" + r"(?P[0-9a-f]{32})" + r"|((sha256:)?(?P[0-9a-f]{64}))" + r"))?$" + ), + addendum="Use `conda.misc._get_url_pattern()` instead.", +) + + +def _get_url_pattern() -> re.Pattern: + """Build URL pattern dynamically based on registered package extensions.""" + extensions = context.plugin_manager.get_package_extractors().keys() + ext_pattern = "|".join(map(re.escape, extensions)) + return re.compile( + r"(?:(?P.+)(?:[/\\]))?" + rf"(?P[^/\\#]+(?:{ext_pattern}))" + r"(?:#(" + r"(?P[0-9a-f]{32})" + r"|((sha256:)?(?P[0-9a-f]{64}))" + r"))?$" + ) + + +def _match_specs_from_explicit(specs: Iterable[str]) -> Iterable[MatchSpec]: + url_pat = _get_url_pattern() + for spec in specs: + if spec == EXPLICIT_MARKER: + continue + + if not is_url(spec): + """ + # This does not work because url_to_path does not enforce Windows + # backslashes. Should it? Seems like a dangerous change to make but + # it would be cleaner. + expanded = expand(spec) + urled = path_to_url(expanded) + pathed = url_to_path(urled) + assert pathed == expanded + """ + spec = path_to_url(expand(spec)) + + # parse URL + m = url_pat.match(spec) + if m is None: + raise ParseError(f"Could not parse explicit URL: {spec}") + url_p, fn = m.group("url_p"), m.group("fn") + url = join_url(url_p, fn) + # url_p is everything but the tarball_basename and the checksum + checksums = {} + if md5 := m.group("md5"): + checksums["md5"] = md5 + if sha256 := m.group("sha256"): + checksums["sha256"] = sha256 + yield MatchSpec(url, **checksums) + + +def explicit( + specs: Iterable[str], + prefix: str, + verbose: bool = False, + force_extract: bool = True, + index: Any = None, + requested_specs: Sequence[str] | None = None, +) -> None: + package_cache_records = get_package_records_from_explicit(specs) + install_explicit_packages( + package_cache_records=package_cache_records, + prefix=prefix, + requested_specs=requested_specs, + ) + + +def install_explicit_packages( + package_cache_records: list[PackageRecord], + prefix: str, + requested_specs: Sequence[str] | None = None, +): + """Install a list of PackageRecords into a prefix""" + specs_pcrecs = tuple([rec.to_match_spec(), rec] for rec in package_cache_records) + + precs_to_remove = [] + prefix_data = PrefixData(prefix) + for q, (spec, pcrec) in enumerate(specs_pcrecs): + new_spec = MatchSpec(spec, name=pcrec.name) + specs_pcrecs[q][0] = new_spec + + prec = prefix_data.get(pcrec.name, None) + if prec: + # If we've already got matching specifications, then don't bother re-linking it + if next(prefix_data.query(new_spec), None): + specs_pcrecs[q][0] = None + else: + precs_to_remove.append(prec) + + # Record user-requested specs in history when provided, otherwise fall back to + # all processed specs for backwards compatibility + if requested_specs: + update_specs_for_history = tuple(MatchSpec(spec) for spec in requested_specs) + else: + update_specs_for_history = tuple(sp[0] for sp in specs_pcrecs if sp[0]) + + stp = PrefixSetup( + prefix, + precs_to_remove, + tuple(sp[1] for sp in specs_pcrecs if sp[0]), + (), + update_specs_for_history, + (), + ) + + txn = UnlinkLinkTransaction(stp) + if not context.json and not context.quiet: + txn.print_transaction_summary() + txn.execute() + + +def _get_package_record_from_specs(specs: list[str]) -> Iterable[PackageCacheRecord]: + """Given a list of specs, find the corresponding PackageCacheRecord. If + some PackageCacheRecords are missing, raise an error. + """ + specs_pcrecs = tuple( + [spec, next(PackageCacheData.query_all(spec), None)] for spec in specs + ) + + # Assert that every spec has a PackageCacheRecord + specs_with_missing_pcrecs = [ + str(spec) for spec, pcrec in specs_pcrecs if pcrec is None + ] + if specs_with_missing_pcrecs: + if len(specs_with_missing_pcrecs) == len(specs_pcrecs): + raise SpecNotFoundInPackageCache("No package cache records found") + else: + missing_precs_list = ", ".join(specs_with_missing_pcrecs) + raise SpecNotFoundInPackageCache( + f"Missing package cache records for: {missing_precs_list}" + ) + return [rec[1] for rec in specs_pcrecs] + + +def get_package_records_from_explicit(lines: list[str]) -> Iterable[PackageCacheRecord]: + """Given the lines from an explicit.txt, create the PackageRecords for each of the + specified packages. This may require downloading the package, if it does not already + exist in the package cache. + """ + # Extract the list of specs + fetch_specs = list(_match_specs_from_explicit(lines)) + + if context.dry_run: + raise DryRunExit() + + # Fetch the packages - if they are already cached nothing new will be downloaded + pfe = ProgressiveFetchExtract(fetch_specs) + pfe.execute() + + # Get the package records from the cache + return _get_package_record_from_specs(fetch_specs) + + +def walk_prefix(prefix, ignore_predefined_files=True, windows_forward_slashes=True): + """Return the set of all files in a given prefix directory.""" + res = set() + prefix = abspath(prefix) + ignore = { + "pkgs", + "envs", + "conda-bld", + "conda-meta", + ".conda_lock", + "users", + "LICENSE.txt", + "info", + "conda-recipes", + ".index", + ".unionfs", + ".nonadmin", + } + binignore = {"conda", "activate", "deactivate"} + if on_mac: + ignore.update({"python.app", "Launcher.app"}) + for fn in (entry.name for entry in os.scandir(prefix)): + if ignore_predefined_files and fn in ignore: + continue + if isfile(join(prefix, fn)): + res.add(fn) + continue + for root, dirs, files in os.walk(join(prefix, fn)): + should_ignore = ignore_predefined_files and root == join(prefix, "bin") + for fn2 in files: + if should_ignore and fn2 in binignore: + continue + res.add(relpath(join(root, fn2), prefix)) + for dn in dirs: + path = join(root, dn) + if islink(path): + res.add(relpath(path, prefix)) + + if on_win and windows_forward_slashes: + return {path.replace("\\", "/") for path in res} + else: + return res + + +def untracked(prefix, exclude_self_build=False): + """Return (the set) of all untracked files for a given prefix.""" + conda_files = conda_installed_files(prefix, exclude_self_build) + return { + path + for path in walk_prefix(prefix) - conda_files + if not ( + path.endswith("~") + or on_mac + and path.endswith(".DS_Store") + or path.endswith(".pyc") + and path[:-1] in conda_files + ) + } + + +@deprecated("25.9", "26.3", addendum="Use PrefixData.set_nonadmin()") +def touch_nonadmin(prefix): + """Creates $PREFIX/.nonadmin if sys.prefix/.nonadmin exists (on Windows).""" + if on_win and exists(join(context.root_prefix, ".nonadmin")): + if not isdir(prefix): + os.makedirs(prefix) + with open_utf8(join(prefix, ".nonadmin"), "w") as fo: + fo.write("") + + +def clone_env(prefix1, prefix2, verbose=True, quiet=False, index_args=None): + """Clone existing prefix1 into new prefix2.""" + untracked_files = untracked(prefix1) + drecs = {prec for prec in PrefixData(prefix1).iter_records()} + + # Resolve URLs for packages that do not have URLs + index = {} + unknowns = [prec for prec in drecs if not prec.get("url")] + notfound = [] + if unknowns: + index_args = index_args or {} + index_args["channels"] = index_args.pop("channel_urls") + index = Index(**index_args) + + for prec in unknowns: + spec = MatchSpec(name=prec.name, version=prec.version, build=prec.build) + precs = tuple(prec for prec in index.values() if spec.match(prec)) + if not precs: + notfound.append(spec) + elif len(precs) > 1: + drecs.remove(prec) + drecs.add(_get_best_prec_match(precs)) + else: + drecs.remove(prec) + drecs.add(precs[0]) + if notfound: + raise PackagesNotFoundError(notfound) + + # Assemble the URL and channel list + urls = {} + for prec in drecs: + urls[prec] = prec["url"] + + precs = tuple(PrefixGraph(urls).graph) + urls = [urls[prec] for prec in precs] + + disallowed = tuple(MatchSpec(s) for s in context.disallowed_packages) + for prec in precs: + if any(d.match(prec) for d in disallowed): + raise DisallowedPackageError(prec) + + if verbose: + print("Packages: %d" % len(precs)) + print("Files: %d" % len(untracked_files)) + + if context.dry_run: + raise DryRunExit() + + for f in untracked_files: + src = join(prefix1, f) + dst = join(prefix2, f) + dst_dir = dirname(dst) + if islink(dst_dir) or isfile(dst_dir): + rm_rf(dst_dir) + if not isdir(dst_dir): + os.makedirs(dst_dir) + if islink(src): + symlink(readlink(src), dst) + continue + + try: + with open_utf8(src, "rb") as fi: + data = fi.read() + except OSError: + continue + + try: + s = data.decode("utf-8") + s = s.replace(prefix1, prefix2) + data = s.encode("utf-8") + except UnicodeDecodeError: # data is binary + pass + + with open_utf8(dst, "wb") as fo: + fo.write(data) + shutil.copystat(src, dst) + + actions = explicit( + urls, + prefix2, + verbose=not quiet, + index=index, + force_extract=False, + ) + return actions, untracked_files + + +def _get_best_prec_match(precs): + if not precs: + raise ValueError("'precs' cannot be empty.") + for channel in context.channels: + channel_matcher = ChannelMatch(channel) + prec_matches = tuple( + prec for prec in precs if channel_matcher.match(prec.channel.name) + ) + if prec_matches: + break + else: + prec_matches = precs + log.warning("Multiple packages found: %s", dashlist(prec_matches)) + return prec_matches[0] diff --git a/data/miniconda3/lib/python3.13/site-packages/conda/plan.py b/data/miniconda3/lib/python3.13/site-packages/conda/plan.py new file mode 100644 index 0000000000000000000000000000000000000000..ce02d3e6e01468409ad30760cbf602a91057548c --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda/plan.py @@ -0,0 +1,250 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +""" +Handle the planning of installs and their execution. + +NOTE: + conda.install uses canonical package names in its interface functions, + whereas conda.resolve uses package filenames, as those are used as index + keys. We try to keep fixes to this "impedance mismatch" local to this + module. +""" + +import sys +from collections import defaultdict +from logging import getLogger + +from boltons.setutils import IndexedSet + +from .base.constants import DEFAULTS_CHANNEL_NAME, UNKNOWN_CHANNEL +from .base.context import context, reset_context +from .common.constants import TRACE +from .common.io import dashlist, env_vars, time_recorder +from .common.iterators import groupby_to_dict as groupby +from .core.index import LAST_CHANNEL_URLS +from .core.link import PrefixSetup, UnlinkLinkTransaction +from .deprecations import deprecated +from .instructions import FETCH, LINK, SYMLINK_CONDA, UNLINK +from .models.channel import Channel, prioritize_channels +from .models.dist import Dist +from .models.enums import LinkType +from .models.match_spec import MatchSpec +from .models.records import PackageRecord +from .models.version import normalized_version +from .utils import human_bytes + +deprecated.module("25.9", "26.3") + +deprecated.constant( + "25.9", + "26.3", + "log", + getLogger(__name__), + addendum="Use builtin `logging` instead.", +) +deprecated.constant("25.9", "26.3", "sys", sys, addendum="Use builtin `sys` instead.") +del sys +deprecated.constant( + "25.9", + "26.3", + "defaultdict", + defaultdict, + addendum="Use builtin `collections.defaultdict` instead.", +) +del defaultdict +deprecated.constant( + "25.9", + "26.3", + "IndexedSet", + IndexedSet, + addendum="Use `boltons.setutils.IndexedSet` instead.", +) +del IndexedSet +deprecated.constant( + "25.9", + "26.3", + "DEFAULTS_CHANNEL_NAME", + DEFAULTS_CHANNEL_NAME, + addendum="Use `conda.base.constants.DEFAULTS_CHANNEL_NAME` instead.", +) +del DEFAULTS_CHANNEL_NAME +deprecated.constant( + "25.9", + "26.3", + "UNKNOWN_CHANNEL", + UNKNOWN_CHANNEL, + addendum="Use `conda.base.constants.UNKNOWN_CHANNEL` instead.", +) +del UNKNOWN_CHANNEL +deprecated.constant( + "25.9", + "26.3", + "context", + context, + addendum="Use `conda.base.context.context` instead.", +) +del context +deprecated.constant( + "25.9", + "26.3", + "reset_context", + reset_context, + addendum="Use `conda.base.context.reset_context` instead.", +) +del reset_context +deprecated.constant( + "25.9", + "26.3", + "TRACE", + TRACE, + addendum="Use `conda.common.constants.TRACE` instead.", +) +del TRACE +deprecated.constant( + "25.9", + "26.3", + "dashlist", + dashlist, + addendum="Use `conda.common.io.dashlist` instead.", +) +del dashlist +deprecated.constant( + "25.9", + "26.3", + "env_vars", + env_vars, + addendum="Use `conda.common.io.env_vars` instead.", +) +del env_vars +deprecated.constant( + "25.9", + "26.3", + "time_recorder", + time_recorder, + addendum="Use `conda.common.io.time_recorder` instead.", +) +del time_recorder +deprecated.constant( + "25.9", + "26.3", + "groupby", + groupby, + addendum="Use `conda.common.iterators.groupby_to_dict` instead.", +) +del groupby +deprecated.constant( + "25.9", + "26.3", + "LAST_CHANNEL_URLS", + LAST_CHANNEL_URLS, + addendum="Use `conda.core.index.LAST_CHANNEL_URLS` instead.", +) +del LAST_CHANNEL_URLS +deprecated.constant( + "25.9", + "26.3", + "PrefixSetup", + PrefixSetup, + addendum="Use `conda.core.link.PrefixSetup` instead.", +) +del PrefixSetup +deprecated.constant( + "25.9", + "26.3", + "UnlinkLinkTransaction", + UnlinkLinkTransaction, + addendum="Use `conda.core.link.UnlinkLinkTransaction` instead.", +) +del UnlinkLinkTransaction +deprecated.constant( + "25.9", + "26.3", + "FETCH", + FETCH, + addendum="Use `conda.instructions.FETCH` instead.", +) +del FETCH +deprecated.constant( + "25.9", "26.3", "LINK", LINK, addendum="Use `conda.instructions.LINK` instead." +) +del LINK +deprecated.constant( + "25.9", + "26.3", + "SYMLINK_CONDA", + SYMLINK_CONDA, + addendum="Use `conda.instructions.SYMLINK_CONDA` instead.", +) +del SYMLINK_CONDA +deprecated.constant( + "25.9", + "26.3", + "UNLINK", + UNLINK, + addendum="Use `conda.instructions.UNLINK` instead.", +) +del UNLINK +deprecated.constant( + "25.9", + "26.3", + "Channel", + Channel, + addendum="Use `conda.models.channel.Channel` instead.", +) +del Channel +deprecated.constant( + "25.9", + "26.3", + "prioritize_channels", + prioritize_channels, + addendum="Use `conda.models.channel.prioritize_channels` instead.", +) +del prioritize_channels +deprecated.constant( + "25.9", + "26.3", + "Dist", + Dist, + addendum="Use `conda.models.dist.Dist` instead.", +) +del Dist +deprecated.constant( + "25.9", + "26.3", + "LinkType", + LinkType, + addendum="Use `conda.models.enums.LinkType` instead.", +) +del LinkType +deprecated.constant( + "25.9", + "26.3", + "MatchSpec", + MatchSpec, + addendum="Use `conda.models.match_spec.MatchSpec` instead.", +) +del MatchSpec +deprecated.constant( + "25.9", + "26.3", + "PackageRecord", + PackageRecord, + addendum="Use `conda.models.records.PackageRecord` instead.", +) +del PackageRecord +deprecated.constant( + "25.9", + "26.3", + "normalized_version", + normalized_version, + addendum="Use `conda.models.version.normalized_version` instead.", +) +del normalized_version +deprecated.constant( + "25.9", + "26.3", + "human_bytes", + human_bytes, + addendum="Use `conda.utils.human_bytes` instead.", +) +del human_bytes diff --git a/data/miniconda3/lib/python3.13/site-packages/conda/py.typed b/data/miniconda3/lib/python3.13/site-packages/conda/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/lib/python3.13/site-packages/conda/reporters.py b/data/miniconda3/lib/python3.13/site-packages/conda/reporters.py new file mode 100644 index 0000000000000000000000000000000000000000..34e02d881084e66a3e471aebf4f6d077129da594 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda/reporters.py @@ -0,0 +1,103 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +""" +Holds functions for output rendering in conda +""" + +from __future__ import annotations + +import logging +import sys +from functools import cache +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from contextlib import AbstractContextManager + +from .base.context import context +from .exceptions import CondaSystemExit, DryRunExit + +if TYPE_CHECKING: + from collections.abc import Callable + + from .plugins.types import ProgressBarBase, SpinnerBase + +logger = logging.getLogger(__name__) + + +@cache +def _get_render_func(style: str | None = None) -> Callable: + """ + Retrieves the render function to use + """ + backend = context.console + reporter = context.plugin_manager.get_reporter_backend(backend) + + renderer = reporter.renderer() + + if style is not None: + render_func = getattr(renderer, style, None) + if render_func is None: + raise AttributeError(f"'{style}' is not a valid reporter backend style") + else: + render_func = getattr(renderer, "render") + + return render_func + + +def render(data, style: str | None = None, **kwargs) -> None: + """ + Used to render output in conda + + The output will either be rendered as "json" or normal "console" output to stdout. + This function allows us to configure different reporter backends for these two types + of output. + """ + render_func = _get_render_func(style) + data_str = render_func(data, **kwargs) + sys.stdout.write(data_str) + + +def get_progress_bar(description: str, **kwargs) -> ProgressBarBase: + """ + Retrieve the progress bar for the currently configured reporter backend + """ + return _get_render_func("progress_bar")(description, **kwargs) + + +def get_progress_bar_context_manager() -> AbstractContextManager: + """ + Retrieve progress bar context manager to use with registered reporter + """ + return _get_render_func("progress_bar_context_manager")() + + +def get_spinner(message: str, fail_message: str = "failed\n") -> SpinnerBase: + """ + Retrieve spinner to use with registered reporter + """ + return _get_render_func("spinner")(message, fail_message) + + +def confirm_yn(message: str = "Proceed", default="yes", dry_run=None) -> bool: + """ + Display a "yes/no" confirmation input + """ + if (dry_run is None and context.dry_run) or dry_run: + raise DryRunExit() + + if context.always_yes: + return True + + try: + choice = _get_render_func("prompt")( + message, choices=("yes", "no"), default=default + ) + + except KeyboardInterrupt: # pragma: no cover + raise CondaSystemExit("\nOperation aborted. Exiting.") + + if choice == "no": + raise CondaSystemExit("Exiting.") + + return True diff --git a/data/miniconda3/lib/python3.13/site-packages/conda/resolve.py b/data/miniconda3/lib/python3.13/site-packages/conda/resolve.py new file mode 100644 index 0000000000000000000000000000000000000000..42ee26e0c77a75b45d6c8db2450137234a8039e6 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda/resolve.py @@ -0,0 +1,1677 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Low-level SAT solver wrapper/interface for the classic solver. + +See conda.core.solver.Solver for the high-level API. +""" + +from __future__ import annotations + +import copy +import itertools +from collections import defaultdict, deque +from functools import cache +from logging import DEBUG, getLogger +from typing import TYPE_CHECKING + +from frozendict import frozendict +from tqdm import tqdm + +from .auxlib.decorators import memoizemethod +from .base.constants import MAX_CHANNEL_PRIORITY, ChannelPriority, SatSolverChoice +from .base.context import context +from .common.compat import on_win +from .common.io import dashlist, time_recorder +from .common.iterators import groupby_to_dict as groupby +from .common.logic import ( + TRUE, + Clauses, + PycoSatSolver, + PyCryptoSatSolver, + PySatSolver, + minimal_unsatisfiable_subset, +) +from .common.toposort import toposort +from .exceptions import ( + CondaDependencyError, + InvalidSpec, + ResolvePackageNotFound, + UnsatisfiableError, +) +from .models.channel import Channel +from .models.enums import NoarchType, PackageType +from .models.match_spec import MatchSpec +from .models.records import PackageRecord +from .models.version import VersionOrder + +if TYPE_CHECKING: + from collections.abc import Iterable + +log = getLogger(__name__) +stdoutlog = getLogger("conda.stdoutlog") + +# used in conda build +Unsatisfiable = UnsatisfiableError +ResolvePackageNotFound = ResolvePackageNotFound + +_sat_solvers = { + SatSolverChoice.PYCOSAT: PycoSatSolver, + SatSolverChoice.PYCRYPTOSAT: PyCryptoSatSolver, + SatSolverChoice.PYSAT: PySatSolver, +} + + +@cache +def _get_sat_solver_cls(sat_solver_choice=SatSolverChoice.PYCOSAT): + def try_out_solver(sat_solver): + c = Clauses(sat_solver=sat_solver) + required = {c.new_var(), c.new_var()} + c.Require(c.And, *required) + solution = set(c.sat()) + if not required.issubset(solution): + raise RuntimeError(f"Wrong SAT solution: {solution}. Required: {required}") + + sat_solver = _sat_solvers[sat_solver_choice] + try: + try_out_solver(sat_solver) + except Exception as e: + log.warning( + "Could not run SAT solver through interface '%s'.", sat_solver_choice + ) + log.debug("SAT interface error due to: %s", e, exc_info=True) + else: + log.debug("Using SAT solver interface '%s'.", sat_solver_choice) + return sat_solver + for sat_solver in _sat_solvers.values(): + try: + try_out_solver(sat_solver) + except Exception as e: + log.debug( + "Attempted SAT interface '%s' but unavailable due to: %s", + sat_solver_choice, + e, + ) + else: + log.debug("Falling back to SAT solver interface '%s'.", sat_solver_choice) + return sat_solver + raise CondaDependencyError( + "Cannot run solver. No functioning SAT implementations available." + ) + + +def exactness_and_number_of_deps(resolve_obj, ms): + """Sorting key to emphasize packages that have more strict + requirements. More strict means the reduced index can be reduced + more, so we want to consider these more constrained deps earlier in + reducing the index. + """ + if ms.strictness == 3: + prec = resolve_obj.find_matches(ms) + value = 3 + if prec: + for dep in prec[0].depends: + value += MatchSpec(dep).strictness + else: + value = ms.strictness + return value + + +class Resolve: + def __init__(self, index, processed=False, channels=()): + self.index = index + + self.channels = channels + self._channel_priorities_map = ( + self._make_channel_priorities(channels) if channels else {} + ) + self._channel_priority = context.channel_priority + self._solver_ignore_timestamps = context.solver_ignore_timestamps + + groups = groupby(lambda x: x.name, index.values()) + trackers = defaultdict(list) + + for name in groups: + unmanageable_precs = [prec for prec in groups[name] if prec.is_unmanageable] + if unmanageable_precs: + log.debug("restricting to unmanageable packages: %s", name) + groups[name] = unmanageable_precs + tf_precs = (prec for prec in groups[name] if prec.track_features) + for prec in tf_precs: + for feature_name in prec.track_features: + trackers[feature_name].append(prec) + + self.groups = groups # dict[package_name, list[PackageRecord]] + self.trackers = trackers # dict[track_feature, set[PackageRecord]] + self._cached_find_matches = {} # dict[MatchSpec, set[PackageRecord]] + self.ms_depends_ = {} # dict[PackageRecord, list[MatchSpec]] + self._reduced_index_cache = {} + self._pool_cache = {} + self._strict_channel_cache = {} + + self._system_precs = { + _ + for _ in index + if ( + hasattr(_, "package_type") + and _.package_type == PackageType.VIRTUAL_SYSTEM + ) + } + + # sorting these in reverse order is effectively prioritizing + # constraint behavior from newer packages. It is applying broadening + # reduction based on the latest packages, which may reduce the space + # more, because more modern packages utilize constraints in more sane + # ways (for example, using run_exports in conda-build 3) + for name, group in self.groups.items(): + self.groups[name] = sorted(group, key=self.version_key, reverse=True) + + def __hash__(self): + return ( + super().__hash__() + ^ hash(frozenset(self.channels)) + ^ hash(frozendict(self._channel_priorities_map)) + ^ hash(self._channel_priority) + ^ hash(self._solver_ignore_timestamps) + ^ hash(frozendict((k, tuple(v)) for k, v in self.groups.items())) + ^ hash(frozendict((k, tuple(v)) for k, v in self.trackers.items())) + ^ hash(frozendict((k, tuple(v)) for k, v in self.ms_depends_.items())) + ) + + def default_filter(self, features=None, filter=None): + if filter is None: + filter = {} + else: + filter.clear() + + filter.update( + {PackageRecord.feature(name): False for name in self.trackers.keys()} + ) + if features: + filter.update({PackageRecord.feature(name): True for name in features}) + return filter + + def valid(self, spec_or_prec, filter, optional=True): + """Tests if a package, MatchSpec, or a list of both has satisfiable + dependencies, assuming cyclic dependencies are always valid. + + Args: + spec_or_prec: a package record, a MatchSpec, or an iterable of these. + filter: a dictionary of (fkey,valid) pairs, used to consider a subset + of dependencies, and to eliminate repeated searches. + optional: if True (default), do not enforce optional specifications + when considering validity. If False, enforce them. + + Returns: + True if the full set of dependencies can be satisfied; False otherwise. + If filter is supplied and update is True, it will be updated with the + search results. + """ + + def v_(spec): + return v_ms_(spec) if isinstance(spec, MatchSpec) else v_fkey_(spec) + + def v_ms_(ms): + return ( + optional + and ms.optional + or any(v_fkey_(fkey) for fkey in self.find_matches(ms)) + ) + + def v_fkey_(prec): + val = filter.get(prec) + if val is None: + filter[prec] = True + try: + depends = self.ms_depends(prec) + except InvalidSpec: + val = filter[prec] = False + else: + val = filter[prec] = all(v_ms_(ms) for ms in depends) + return val + + result = v_(spec_or_prec) + return result + + def valid2(self, spec_or_prec, filter_out, optional=True): + def is_valid(_spec_or_prec): + if isinstance(_spec_or_prec, MatchSpec): + return is_valid_spec(_spec_or_prec) + else: + return is_valid_prec(_spec_or_prec) + + @memoizemethod + def is_valid_spec(_spec): + return ( + optional + and _spec.optional + or any(is_valid_prec(_prec) for _prec in self.find_matches(_spec)) + ) + + def is_valid_prec(prec): + val = filter_out.get(prec) + if val is None: + filter_out[prec] = False + try: + has_valid_deps = all( + is_valid_spec(ms) for ms in self.ms_depends(prec) + ) + except InvalidSpec: + val = filter_out[prec] = "invalid dep specs" + else: + val = filter_out[prec] = ( + False if has_valid_deps else "invalid depends specs" + ) + return not val + + return is_valid(spec_or_prec) + + def invalid_chains(self, spec, filter, optional=True): + """Constructs a set of 'dependency chains' for invalid specs. + + A dependency chain is a tuple of MatchSpec objects, starting with + the requested spec, proceeding down the dependency tree, ending at + a specification that cannot be satisfied. + + Args: + spec: a package key or MatchSpec + filter: a dictionary of (prec, valid) pairs to be used when + testing for package validity. + + Returns: + A tuple of tuples, empty if the MatchSpec is valid. + """ + + def chains_(spec, names): + if spec.name in names: + return + names.add(spec.name) + if self.valid(spec, filter, optional): + return + precs = self.find_matches(spec) + found = False + + conflict_deps = set() + for prec in precs: + for m2 in self.ms_depends(prec): + for x in chains_(m2, names): + found = True + yield (spec,) + x + else: + conflict_deps.add(m2) + if not found: + conflict_groups = groupby(lambda x: x.name, conflict_deps) + for group in conflict_groups.values(): + yield (spec,) + MatchSpec.union(group) + + return chains_(spec, set()) + + def verify_specs(self, specs): + """Perform a quick verification that specs and dependencies are reasonable. + + Args: + specs: An iterable of strings or MatchSpec objects to be tested. + + Returns: + Nothing, but if there is a conflict, an error is thrown. + + Note that this does not attempt to resolve circular dependencies. + """ + non_tf_specs = [] + bad_deps = [] + feature_names = set() + for ms in specs: + _feature_names = ms.get_exact_value("track_features") + if _feature_names: + feature_names.update(_feature_names) + else: + non_tf_specs.append(ms) + bad_deps.extend( + (spec,) + for spec in non_tf_specs + if (not spec.optional and not self.find_matches(spec)) + ) + if bad_deps: + raise ResolvePackageNotFound(bad_deps) + return tuple(non_tf_specs), feature_names + + def _classify_bad_deps( + self, bad_deps, specs_to_add, history_specs, strict_channel_priority + ): + classes = { + "python": set(), + "request_conflict_with_history": set(), + "direct": set(), + "virtual_package": set(), + } + specs_to_add = {MatchSpec(_) for _ in specs_to_add or []} + history_specs = {MatchSpec(_) for _ in history_specs or []} + for chain in bad_deps: + # sometimes chains come in as strings + if ( + len(chain) > 1 + and chain[-1].name == "python" + and not any(_.name == "python" for _ in specs_to_add) + and any(_[0] for _ in bad_deps if _[0].name == "python") + ): + python_first_specs = [_[0] for _ in bad_deps if _[0].name == "python"] + if python_first_specs: + python_spec = python_first_specs[0] + if not ( + set(self.find_matches(python_spec)) + & set(self.find_matches(chain[-1])) + ): + classes["python"].add( + ( + tuple([chain[0], chain[-1]]), + str(MatchSpec(python_spec, target=None)), + ) + ) + elif chain[-1].name.startswith("__"): + version = [_ for _ in self._system_precs if _.name == chain[-1].name] + virtual_package_version = ( + version[0].version if version else "not available" + ) + classes["virtual_package"].add((tuple(chain), virtual_package_version)) + elif chain[0] in specs_to_add: + match = False + for spec in history_specs: + if spec.name == chain[-1].name: + classes["request_conflict_with_history"].add( + (tuple(chain), str(MatchSpec(spec, target=None))) + ) + match = True + + if not match: + classes["direct"].add( + (tuple(chain), str(MatchSpec(chain[0], target=None))) + ) + else: + if len(chain) > 1 or any( + len(c) >= 1 and c[0] == chain[0] for c in bad_deps + ): + classes["direct"].add( + (tuple(chain), str(MatchSpec(chain[0], target=None))) + ) + + if classes["python"]: + # filter out plain single-entry python conflicts. The python section explains these. + classes["direct"] = [ + _ + for _ in classes["direct"] + if _[1].startswith("python ") or len(_[0]) > 1 + ] + return classes + + def find_matches_with_strict(self, ms, strict_channel_priority): + matches = self.find_matches(ms) + if not strict_channel_priority: + return matches + sole_source_channel_name = self._get_strict_channel(ms.name) + return tuple(f for f in matches if f.channel.name == sole_source_channel_name) + + def find_conflicts(self, specs, specs_to_add=None, history_specs=None): + if context.unsatisfiable_hints: + if not context.json: + print( + "\nFound conflicts! Looking for incompatible packages.\n" + "This can take several minutes. Press CTRL-C to abort." + ) + bad_deps = self.build_conflict_map(specs, specs_to_add, history_specs) + else: + bad_deps = {} + strict_channel_priority = context.channel_priority == ChannelPriority.STRICT + raise UnsatisfiableError(bad_deps, strict=strict_channel_priority) + + def breadth_first_search_for_dep_graph( + self, root_spec, target_name, dep_graph, num_targets=1 + ): + """Return shorted path from root_spec to target_name""" + queue = [] + queue.append([root_spec]) + visited = [] + target_paths = [] + while queue: + path = queue.pop(0) + node = path[-1] + if node in visited: + continue + visited.append(node) + if node.name == target_name: + if len(target_paths) == 0: + target_paths.append(path) + if len(target_paths[-1]) == len(path): + last_spec = MatchSpec.union((path[-1], target_paths[-1][-1]))[0] + target_paths[-1][-1] = last_spec + else: + target_paths.append(path) + + found_all_targets = len(target_paths) == num_targets and any( + len(_) != len(path) for _ in queue + ) + if len(queue) == 0 or found_all_targets: + return target_paths + sub_graph = dep_graph + for p in path[0:-1]: + sub_graph = sub_graph[p] + children = [_ for _ in sub_graph.get(node, {})] + if children is None: + continue + for adj in children: + if len(target_paths) < num_targets: + new_path = list(path) + new_path.append(adj) + queue.append(new_path) + return target_paths + + def build_graph_of_deps(self, spec): + dep_graph = {spec: {}} + all_deps = set() + queue = [[spec]] + while queue: + path = queue.pop(0) + sub_graph = dep_graph + for p in path: + sub_graph = sub_graph[p] + parent_node = path[-1] + matches = self.find_matches(parent_node) + for mat in matches: + if len(mat.depends) > 0: + for i in mat.depends: + new_node = MatchSpec(i) + sub_graph.update({new_node: {}}) + all_deps.add(new_node) + new_path = list(path) + new_path.append(new_node) + if len(new_path) <= context.unsatisfiable_hints_check_depth: + queue.append(new_path) + return dep_graph, all_deps + + def build_conflict_map(self, specs, specs_to_add=None, history_specs=None): + """Perform a deeper analysis on conflicting specifications, by attempting + to find the common dependencies that might be the cause of conflicts. + + Args: + specs: An iterable of strings or MatchSpec objects to be tested. + It is assumed that the specs conflict. + + Returns: + bad_deps: A list of lists of bad deps + + Strategy: + If we're here, we know that the specs conflict. This could be because: + - One spec conflicts with another; e.g. + ['numpy 1.5*', 'numpy >=1.6'] + - One spec conflicts with a dependency of another; e.g. + ['numpy 1.5*', 'scipy 0.12.0b1'] + - Each spec depends on *the same package* but in a different way; e.g., + ['A', 'B'] where A depends on numpy 1.5, and B on numpy 1.6. + Technically, all three of these cases can be boiled down to the last + one if we treat the spec itself as one of the "dependencies". There + might be more complex reasons for a conflict, but this code only + considers the ones above. + + The purpose of this code, then, is to identify packages (like numpy + above) that all of the specs depend on *but in different ways*. We + then identify the dependency chains that lead to those packages. + """ + # if only a single package matches the spec use the packages depends + # rather than the spec itself + strict_channel_priority = context.channel_priority == ChannelPriority.STRICT + + specs = set(specs) | (specs_to_add or set()) + # Remove virtual packages + specs = {spec for spec in specs if not spec.name.startswith("__")} + if len(specs) == 1: + matches = self.find_matches(next(iter(specs))) + if len(matches) == 1: + specs = set(self.ms_depends(matches[0])) + specs.update({_.to_match_spec() for _ in self._system_precs}) + for spec in specs: + self._get_package_pool((spec,)) + + dep_graph = {} + dep_list = {} + with tqdm( + total=len(specs), + desc="Building graph of deps", + leave=False, + disable=context.json, + ) as t: + for spec in specs: + t.set_description(f"Examining {spec}") + t.update() + dep_graph_for_spec, all_deps_for_spec = self.build_graph_of_deps(spec) + dep_graph.update(dep_graph_for_spec) + if dep_list.get(spec.name): + dep_list[spec.name].append(spec) + else: + dep_list[spec.name] = [spec] + for dep in all_deps_for_spec: + if dep_list.get(dep.name): + dep_list[dep.name].append(spec) + else: + dep_list[dep.name] = [spec] + + chains = [] + conflicting_pkgs_pkgs = {} + for k, v in dep_list.items(): + set_v = frozenset(v) + # Packages probably conflicts if many specs depend on it + if len(set_v) > 1: + if conflicting_pkgs_pkgs.get(set_v) is None: + conflicting_pkgs_pkgs[set_v] = [k] + else: + conflicting_pkgs_pkgs[set_v].append(k) + # Conflict if required virtual package is not present + elif k.startswith("__") and any(s for s in set_v if s.name != k): + conflicting_pkgs_pkgs[set_v] = [k] + + with tqdm( + total=len(specs), + desc="Determining conflicts", + leave=False, + disable=context.json, + ) as t: + for roots, nodes in conflicting_pkgs_pkgs.items(): + t.set_description( + "Examining conflict for {}".format(" ".join(_.name for _ in roots)) + ) + t.update() + lroots = [_ for _ in roots] + current_shortest_chain = [] + shortest_node = None + requested_spec_unsat = frozenset(nodes).intersection( + {_.name for _ in roots} + ) + if requested_spec_unsat: + chains.append([_ for _ in roots if _.name in requested_spec_unsat]) + shortest_node = chains[-1][0] + for root in roots: + if root != chains[0][0]: + search_node = shortest_node.name + num_occurances = dep_list[search_node].count(root) + c = self.breadth_first_search_for_dep_graph( + root, search_node, dep_graph, num_occurances + ) + chains.extend(c) + else: + for node in nodes: + num_occurances = dep_list[node].count(lroots[0]) + chain = self.breadth_first_search_for_dep_graph( + lroots[0], node, dep_graph, num_occurances + ) + chains.extend(chain) + if len(current_shortest_chain) == 0 or len(chain) < len( + current_shortest_chain + ): + current_shortest_chain = chain + shortest_node = node + for root in lroots[1:]: + num_occurances = dep_list[shortest_node].count(root) + c = self.breadth_first_search_for_dep_graph( + root, shortest_node, dep_graph, num_occurances + ) + chains.extend(c) + + bad_deps = self._classify_bad_deps( + chains, specs_to_add, history_specs, strict_channel_priority + ) + return bad_deps + + def _get_strict_channel(self, package_name): + channel_name = None + try: + channel_name = self._strict_channel_cache[package_name] + except KeyError: + if package_name in self.groups: + all_channel_names = { + prec.channel.name for prec in self.groups[package_name] + } + by_cp = { + self._channel_priorities_map.get(cn, 1): cn + for cn in all_channel_names + } + highest_priority = sorted(by_cp)[ + 0 + ] # highest priority is the lowest number + channel_name = self._strict_channel_cache[package_name] = by_cp[ + highest_priority + ] + return channel_name + + @memoizemethod + def _broader(self, ms, specs_by_name): + """Prevent introduction of matchspecs that broaden our selection of choices.""" + if not specs_by_name: + return False + return ms.strictness < specs_by_name[0].strictness + + def _get_package_pool(self, specs): + specs = frozenset(specs) + if specs in self._pool_cache: + pool = self._pool_cache[specs] + else: + pool = self.get_reduced_index(specs) + grouped_pool = groupby(lambda x: x.name, pool) + pool = {k: set(v) for k, v in grouped_pool.items()} + self._pool_cache[specs] = pool + return pool + + @time_recorder(module_name=__name__) + def get_reduced_index( + self, explicit_specs, sort_by_exactness=True, exit_on_conflict=False + ): + strict_channel_priority = context.channel_priority == ChannelPriority.STRICT + + cache_key = strict_channel_priority, tuple(explicit_specs) + if cache_key in self._reduced_index_cache: + return self._reduced_index_cache[cache_key] + + if log.isEnabledFor(DEBUG): + log.debug( + "Retrieving packages for: %s", + dashlist(sorted(str(s) for s in explicit_specs)), + ) + + explicit_specs, features = self.verify_specs(explicit_specs) + filter_out = { + prec: False if val else "feature not enabled" + for prec, val in self.default_filter(features).items() + } + snames = set() + top_level_spec = None + cp_filter_applied = set() # values are package names + if sort_by_exactness: + # prioritize specs that are more exact. Exact specs will evaluate to 3, + # constrained specs will evaluate to 2, and name only will be 1 + explicit_specs = sorted( + list(explicit_specs), + key=lambda x: (exactness_and_number_of_deps(self, x), x.dist_str()), + reverse=True, + ) + # tuple because it needs to be hashable + explicit_specs = tuple(explicit_specs) + + explicit_spec_package_pool = {} + for s in explicit_specs: + explicit_spec_package_pool[s.name] = explicit_spec_package_pool.get( + s.name, set() + ) | set(self.find_matches(s)) + + def filter_group(_specs): + # all _specs should be for the same package name + name = next(iter(_specs)).name + group = self.groups.get(name, ()) + + # implement strict channel priority + if group and strict_channel_priority and name not in cp_filter_applied: + sole_source_channel_name = self._get_strict_channel(name) + for prec in group: + if prec.channel.name != sole_source_channel_name: + filter_out[prec] = "removed due to strict channel priority" + cp_filter_applied.add(name) + + # Prune packages that don't match any of the patterns, + # have unsatisfiable dependencies, or conflict with the explicit specs + nold = nnew = 0 + for prec in group: + if not filter_out.setdefault(prec, False): + nold += 1 + if (not self.match_any(_specs, prec)) or ( + explicit_spec_package_pool.get(name) + and prec not in explicit_spec_package_pool[name] + ): + filter_out[prec] = ( + f"incompatible with required spec {top_level_spec}" + ) + continue + unsatisfiable_dep_specs = set() + for ms in self.ms_depends(prec): + if not ms.optional and not any( + rec + for rec in self.find_matches(ms) + if not filter_out.get(rec, False) + ): + unsatisfiable_dep_specs.add(ms) + if unsatisfiable_dep_specs: + filter_out[prec] = "unsatisfiable dependencies {}".format( + " ".join(str(s) for s in unsatisfiable_dep_specs) + ) + continue + filter_out[prec] = False + nnew += 1 + + reduced = nnew < nold + if reduced: + log.debug("%s: pruned from %d -> %d" % (name, nold, nnew)) + if any(ms.optional for ms in _specs): + return reduced + elif nnew == 0: + # Indicates that a conflict was found; we can exit early + return None + + # Perform the same filtering steps on any dependencies shared across + # *all* packages in the group. Even if just one of the packages does + # not have a particular dependency, it must be ignored in this pass. + # Otherwise, we might do more filtering than we should---and it is + # better to have extra packages here than missing ones. + if reduced or name not in snames: + snames.add(name) + + _dep_specs = groupby( + lambda s: s.name, + ( + dep_spec + for prec in group + if not filter_out.get(prec, False) + for dep_spec in self.ms_depends(prec) + if not dep_spec.optional + ), + ) + _dep_specs.pop("*", None) # discard track_features specs + + for deps_name, deps in sorted( + _dep_specs.items(), key=lambda x: any(_.optional for _ in x[1]) + ): + if len(deps) >= nnew: + res = filter_group(set(deps)) + if res: + reduced = True + elif res is None: + # Indicates that a conflict was found; we can exit early + return None + + return reduced + + # Iterate on pruning until no progress is made. We've implemented + # what amounts to "double-elimination" here; packages get one additional + # chance after their first "False" reduction. This catches more instances + # where one package's filter affects another. But we don't have to be + # perfect about this, so performance matters. + pruned_to_zero = set() + for _ in range(2): + snames.clear() + slist = deque(explicit_specs) + while slist: + s = slist.popleft() + if filter_group([s]): + slist.append(s) + else: + pruned_to_zero.add(s) + + if pruned_to_zero and exit_on_conflict: + return {} + + # Determine all valid packages in the dependency graph + reduced_index2 = { + prec: prec for prec in (PackageRecord.feature(name) for name in features) + } + specs_by_name_seed = {} + for s in explicit_specs: + specs_by_name_seed[s.name] = specs_by_name_seed.get(s.name, []) + [s] + for explicit_spec in explicit_specs: + add_these_precs2 = tuple( + prec + for prec in self.find_matches(explicit_spec) + if prec not in reduced_index2 and self.valid2(prec, filter_out) + ) + + if strict_channel_priority and add_these_precs2: + strict_channel_name = self._get_strict_channel(add_these_precs2[0].name) + + add_these_precs2 = tuple( + prec + for prec in add_these_precs2 + if prec.channel.name == strict_channel_name + ) + reduced_index2.update((prec, prec) for prec in add_these_precs2) + + for pkg in add_these_precs2: + # what we have seen is only relevant within the context of a single package + # that is picked up because of an explicit spec. We don't want the + # broadening check to apply across packages at the explicit level; only + # at the level of deps below that explicit package. + seen_specs = set() + specs_by_name = copy.deepcopy(specs_by_name_seed) + + dep_specs = set(self.ms_depends(pkg)) + for dep in dep_specs: + specs = specs_by_name.get(dep.name, []) + if dep not in specs and ( + not specs or dep.strictness >= specs[0].strictness + ): + specs.insert(0, dep) + specs_by_name[dep.name] = specs + + while dep_specs: + # used for debugging + # size_index = len(reduced_index2) + # specs_added = [] + ms = dep_specs.pop() + seen_specs.add(ms) + for dep_pkg in ( + _ for _ in self.find_matches(ms) if _ not in reduced_index2 + ): + if not self.valid2(dep_pkg, filter_out): + continue + + # expand the reduced index if not using strict channel priority, + # or if using it and this package is in the appropriate channel + if not strict_channel_priority or ( + self._get_strict_channel(dep_pkg.name) + == dep_pkg.channel.name + ): + reduced_index2[dep_pkg] = dep_pkg + + # recurse to deps of this dep + new_specs = set(self.ms_depends(dep_pkg)) - seen_specs + for new_ms in new_specs: + # We do not pull packages into the reduced index due + # to a track_features dependency. Remember, a feature + # specifies a "soft" dependency: it must be in the + # environment, but it is not _pulled_ in. The SAT + # logic doesn't do a perfect job of capturing this + # behavior, but keeping these packags out of the + # reduced index helps. Of course, if _another_ + # package pulls it in by dependency, that's fine. + if "track_features" not in new_ms and not self._broader( + new_ms, + tuple(specs_by_name.get(new_ms.name, ())), + ): + dep_specs.add(new_ms) + # if new_ms not in dep_specs: + # specs_added.append(new_ms) + else: + seen_specs.add(new_ms) + # debugging info - see what specs are bringing in the largest blobs + # if size_index != len(reduced_index2): + # print("MS {} added {} pkgs to index".format(ms, + # len(reduced_index2) - size_index)) + # if specs_added: + # print("MS {} added {} specs to further examination".format(ms, + # specs_added)) + + reduced_index2 = frozendict(reduced_index2) + self._reduced_index_cache[cache_key] = reduced_index2 + return reduced_index2 + + def match_any(self, mss, prec): + return any(ms.match(prec) for ms in mss) + + def find_matches(self, spec: MatchSpec) -> tuple[PackageRecord]: + res = self._cached_find_matches.get(spec, None) + if res is not None: + return res + + spec_name = spec.get_exact_value("name") + if spec_name: + candidate_precs = self.groups.get(spec_name, ()) + elif spec.get_exact_value("track_features"): + feature_names = spec.get_exact_value("track_features") + candidate_precs = itertools.chain.from_iterable( + self.trackers.get(feature_name, ()) for feature_name in feature_names + ) + else: + candidate_precs = self.index.values() + + res = tuple(p for p in candidate_precs if spec.match(p)) + self._cached_find_matches[spec] = res + return res + + def ms_depends(self, prec: PackageRecord) -> list[MatchSpec]: + deps = self.ms_depends_.get(prec) + if deps is None: + deps = [MatchSpec(d) for d in prec.combined_depends] + deps.extend(MatchSpec(track_features=feat) for feat in prec.features) + self.ms_depends_[prec] = deps + return deps + + def version_key(self, prec, vtype=None): + channel = prec.channel + channel_priority = self._channel_priorities_map.get( + channel.name, 1 + ) # TODO: ask @mcg1969 why the default value is 1 here + valid = 1 if channel_priority < MAX_CHANNEL_PRIORITY else 0 + version_comparator = VersionOrder(prec.get("version", "")) + build_number = prec.get("build_number", 0) + build_string = prec.get("build") + noarch = -int(prec.subdir == "noarch") + if self._channel_priority != ChannelPriority.DISABLED: + vkey = [valid, -channel_priority, version_comparator, build_number, noarch] + else: + vkey = [valid, version_comparator, -channel_priority, build_number, noarch] + if self._solver_ignore_timestamps: + vkey.append(build_string) + else: + vkey.extend((prec.get("timestamp", 0), build_string)) + return vkey + + @staticmethod + def _make_channel_priorities(channels: Iterable[Channel | str]) -> dict[str, int]: + priorities_map = {} + """Make a dictionary of channel priorities. + + Maps channel names to priorities, e.g.: + + .. code-block:: pycon + + >>> Resolve._make_channel_priorities(["conda-canary", "defaults", "conda-forge"]) + { + 'conda-canary': 0, + 'pkgs/main': 1, + 'pkgs/r': 2, + 'conda-forge': 3, + } + + Compare with ``conda.models.channel.prioritize_channels``. + """ + channel_names = ( + channel.name for name in channels for channel in Channel(name).channels + ) + for priority_counter, channel_name in enumerate(channel_names): + if channel_name in priorities_map: + continue + priorities_map[channel_name] = min( + priority_counter, MAX_CHANNEL_PRIORITY - 1 + ) + return priorities_map + + def get_pkgs(self, ms, emptyok=False): # pragma: no cover + # legacy method for conda-build + ms = MatchSpec(ms) + precs = self.find_matches(ms) + if not precs and not emptyok: + raise ResolvePackageNotFound([(ms,)]) + return sorted(precs, key=self.version_key) + + @staticmethod + def to_sat_name(val): + # val can be a PackageRecord or MatchSpec + if isinstance(val, PackageRecord): + return val.dist_str() + elif isinstance(val, MatchSpec): + return "@s@" + str(val) + ("?" if val.optional else "") + else: + raise NotImplementedError() + + @staticmethod + def to_feature_metric_id(prec_dist_str, feat): + return f"@fm@{prec_dist_str}@{feat}" + + def push_MatchSpec(self, C, spec): + spec = MatchSpec(spec) + sat_name = self.to_sat_name(spec) + m = C.from_name(sat_name) + if m is not None: + # the spec has already been pushed onto the clauses stack + return sat_name + + simple = spec._is_single() + nm = spec.get_exact_value("name") + tf = frozenset( + _tf + for _tf in (f.strip() for f in spec.get_exact_value("track_features") or ()) + if _tf + ) + + if nm: + tgroup = libs = self.groups.get(nm, []) + elif tf: + if len(tf) != 1: + raise RuntimeError + k = next(iter(tf)) + tgroup = libs = self.trackers.get(k, []) + else: + tgroup = libs = self.index.keys() + simple = False + if not simple: + libs = [fkey for fkey in tgroup if spec.match(fkey)] + if len(libs) == len(tgroup): + if spec.optional: + m = TRUE + elif not simple: + ms2 = MatchSpec(track_features=tf) if tf else MatchSpec(nm) + m = C.from_name(self.push_MatchSpec(C, ms2)) + if m is None: + sat_names = [self.to_sat_name(prec) for prec in libs] + if spec.optional: + ms2 = MatchSpec(track_features=tf) if tf else MatchSpec(nm) + sat_names.append("!" + self.to_sat_name(ms2)) + m = C.Any(sat_names) + C.name_var(m, sat_name) + return sat_name + + @time_recorder(module_name=__name__) + def gen_clauses(self): + C = Clauses(sat_solver=_get_sat_solver_cls(context.sat_solver)) + for name, group in self.groups.items(): + group = [self.to_sat_name(prec) for prec in group] + # Create one variable for each package + for sat_name in group: + C.new_var(sat_name) + # Create one variable for the group + m = C.new_var(self.to_sat_name(MatchSpec(name))) + + # Exactly one of the package variables, OR + # the negation of the group variable, is true + C.Require(C.ExactlyOne, group + [C.Not(m)]) + + # If a package is installed, its dependencies must be as well + for prec in self.index.values(): + nkey = C.Not(self.to_sat_name(prec)) + for ms in self.ms_depends(prec): + # Virtual packages can't be installed, we ignore them + if not ms.name.startswith("__"): + C.Require(C.Or, nkey, self.push_MatchSpec(C, ms)) + + if log.isEnabledFor(DEBUG): + log.debug( + "gen_clauses returning with clause count: %d", C.get_clause_count() + ) + return C + + def generate_spec_constraints(self, C, specs): + result = [(self.push_MatchSpec(C, ms),) for ms in specs] + if log.isEnabledFor(DEBUG): + log.debug( + "generate_spec_constraints returning with clause count: %d", + C.get_clause_count(), + ) + return result + + def generate_feature_count(self, C): + result = { + self.push_MatchSpec(C, MatchSpec(track_features=name)): 1 + for name in self.trackers.keys() + } + if log.isEnabledFor(DEBUG): + log.debug( + "generate_feature_count returning with clause count: %d", + C.get_clause_count(), + ) + return result + + def generate_update_count(self, C, specs): + return { + "!" + ms.target: 1 for ms in specs if ms.target and C.from_name(ms.target) + } + + def generate_feature_metric(self, C): + eq = {} # a C.minimize() objective: dict[varname, coeff] + # Given a pair (prec, feature), assign a "1" score IF: + # - The prec is installed + # - The prec does NOT require the feature + # - At least one package in the group DOES require the feature + # - A package that tracks the feature is installed + for name, group in self.groups.items(): + prec_feats = {self.to_sat_name(prec): set(prec.features) for prec in group} + active_feats = set.union(*prec_feats.values()).intersection(self.trackers) + for feat in active_feats: + clause_id_for_feature = self.push_MatchSpec( + C, MatchSpec(track_features=feat) + ) + for prec_sat_name, features in prec_feats.items(): + if feat not in features: + feature_metric_id = self.to_feature_metric_id( + prec_sat_name, feat + ) + C.name_var( + C.And(prec_sat_name, clause_id_for_feature), + feature_metric_id, + ) + eq[feature_metric_id] = 1 + return eq + + def generate_removal_count(self, C, specs): + return {"!" + self.push_MatchSpec(C, ms.name): 1 for ms in specs} + + def generate_install_count(self, C, specs): + return {self.push_MatchSpec(C, ms.name): 1 for ms in specs if ms.optional} + + def generate_package_count(self, C, missing): + return {self.push_MatchSpec(C, nm): 1 for nm in missing} + + def generate_version_metrics(self, C, specs, include0=False): + # each of these are weights saying how well packages match the specs + # format for each: a C.minimize() objective: dict[varname, coeff] + eqc = {} # channel + eqv = {} # version + eqb = {} # build number + eqa = {} # arch/noarch + eqt = {} # timestamp + + sdict = {} # dict[package_name, PackageRecord] + + for s in specs: + s = MatchSpec(s) # needed for testing + sdict.setdefault(s.name, []) + # # TODO: this block is important! can't leave it commented out + # rec = sdict.setdefault(s.name, []) + # if s.target: + # dist = Dist(s.target) + # if dist in self.index: + # if self.index[dist].get('priority', 0) < MAX_CHANNEL_PRIORITY: + # rec.append(dist) + + for name, targets in sdict.items(): + pkgs = [(self.version_key(p), p) for p in self.groups.get(name, [])] + pkey = None + # keep in mind that pkgs is already sorted according to version_key (a tuple, + # so composite sort key). Later entries in the list are, by definition, + # greater in some way, so simply comparing with != suffices. + for version_key, prec in pkgs: + if targets and any(prec == t for t in targets): + continue + if pkey is None: + ic = iv = ib = it = ia = 0 + # valid package, channel priority + elif pkey[0] != version_key[0] or pkey[1] != version_key[1]: + ic += 1 + iv = ib = it = ia = 0 + # version + elif pkey[2] != version_key[2]: + iv += 1 + ib = it = ia = 0 + # build number + elif pkey[3] != version_key[3]: + ib += 1 + it = ia = 0 + # arch/noarch + elif pkey[4] != version_key[4]: + ia += 1 + it = 0 + elif not self._solver_ignore_timestamps and pkey[5] != version_key[5]: + it += 1 + + prec_sat_name = self.to_sat_name(prec) + if ic or include0: + eqc[prec_sat_name] = ic + if iv or include0: + eqv[prec_sat_name] = iv + if ib or include0: + eqb[prec_sat_name] = ib + if ia or include0: + eqa[prec_sat_name] = ia + if it or include0: + eqt[prec_sat_name] = it + pkey = version_key + + return eqc, eqv, eqb, eqa, eqt + + def dependency_sort( + self, + must_have: dict[str, PackageRecord], + ) -> list[PackageRecord]: + if not isinstance(must_have, dict): + raise TypeError("'must_have' must be a dict.") + + digraph = {} # dict[str, set[dependent_package_names]] + for package_name, prec in must_have.items(): + if prec in self.index: + digraph[package_name] = {ms.name for ms in self.ms_depends(prec)} + + # There are currently at least three special cases to be aware of. + # 1. The `toposort()` function, called below, contains special case code to remove + # any circular dependency between python and pip. + # 2. conda/plan.py has special case code for menuinst + # Always link/unlink menuinst first/last on windows in case a subsequent + # package tries to import it to create/remove a shortcut + # 3. On windows, python noarch packages need an implicit dependency on conda added, if + # conda is in the list of packages for the environment. Python noarch packages + # that have entry points use conda's own conda.exe python entry point binary. If conda + # is going to be updated during an operation, the unlink / link order matters. + # See issue #6057. + + if on_win and "conda" in digraph: + for package_name, dist in must_have.items(): + record = self.index.get(prec) + if hasattr(record, "noarch") and record.noarch == NoarchType.python: + digraph[package_name].add("conda") + + sorted_keys = toposort(digraph) + must_have = must_have.copy() + # Take all of the items in the sorted keys + # Don't fail if the key does not exist + result = [must_have.pop(key) for key in sorted_keys if key in must_have] + # Take any key that were not sorted + result.extend(must_have.values()) + return result + + def environment_is_consistent(self, installed): + log.debug("Checking if the current environment is consistent") + if not installed: + return None, [] + sat_name_map = {} # dict[sat_name, PackageRecord] + specs = [] + for prec in installed: + sat_name_map[self.to_sat_name(prec)] = prec + specs.append(MatchSpec(f"{prec.name} {prec.version} {prec.build}")) + r2 = Resolve({prec: prec for prec in installed}, True, channels=self.channels) + C = r2.gen_clauses() + constraints = r2.generate_spec_constraints(C, specs) + solution = C.sat(constraints) + return bool(solution) + + def get_conflicting_specs(self, specs, explicit_specs): + if not specs: + return () + + all_specs = set(specs) | set(explicit_specs) + reduced_index = self.get_reduced_index(all_specs) + + # Check if satisfiable + def mysat(specs, add_if=False): + constraints = r2.generate_spec_constraints(C, specs) + return C.sat(constraints, add_if) + + if reduced_index: + r2 = Resolve(reduced_index, True, channels=self.channels) + C = r2.gen_clauses() + solution = mysat(all_specs, True) + else: + solution = None + + if solution: + final_unsat_specs = () + elif context.unsatisfiable_hints: + r2 = Resolve(self.index, True, channels=self.channels) + C = r2.gen_clauses() + # This first result is just a single unsatisfiable core. There may be several. + final_unsat_specs = tuple( + minimal_unsatisfiable_subset( + specs, sat=mysat, explicit_specs=explicit_specs + ) + ) + else: + final_unsat_specs = None + return final_unsat_specs + + def bad_installed(self, installed, new_specs): + log.debug("Checking if the current environment is consistent") + if not installed: + return None, [] + sat_name_map = {} # dict[sat_name, PackageRecord] + specs = [] + for prec in installed: + sat_name_map[self.to_sat_name(prec)] = prec + specs.append(MatchSpec(f"{prec.name} {prec.version} {prec.build}")) + new_index = {prec: prec for prec in sat_name_map.values()} + name_map = {p.name: p for p in new_index} + if "python" in name_map and "pip" not in name_map: + python_prec = new_index[name_map["python"]] + if "pip" in python_prec.depends: + # strip pip dependency from python if not installed in environment + new_deps = [d for d in python_prec.depends if d != "pip"] + python_prec.depends = new_deps + r2 = Resolve(new_index, True, channels=self.channels) + C = r2.gen_clauses() + constraints = r2.generate_spec_constraints(C, specs) + solution = C.sat(constraints) + limit = xtra = None + if not solution or xtra: + + def get_(name, snames): + if name not in snames: + snames.add(name) + for fn in self.groups.get(name, []): + for ms in self.ms_depends(fn): + get_(ms.name, snames) + + # New addition: find the largest set of installed packages that + # are consistent with each other, and include those in the + # list of packages to maintain consistency with + snames = set() + eq_optional_c = r2.generate_removal_count(C, specs) + solution, _ = C.minimize(eq_optional_c, C.sat()) + snames.update( + sat_name_map[sat_name]["name"] + for sat_name in (C.from_index(s) for s in solution) + if sat_name and sat_name[0] != "!" and "@" not in sat_name + ) + # Existing behavior: keep all specs and their dependencies + for spec in new_specs: + get_(MatchSpec(spec).name, snames) + if len(snames) < len(sat_name_map): + limit = snames + xtra = [ + rec + for sat_name, rec in sat_name_map.items() + if rec["name"] not in snames + ] + log.debug( + "Limiting solver to the following packages: %s", ", ".join(limit) + ) + if xtra: + log.debug("Packages to be preserved: %s", xtra) + return limit, xtra + + def restore_bad(self, pkgs, preserve): + if preserve: + sdict = {prec.name: prec for prec in pkgs} + pkgs.extend(p for p in preserve if p.name not in sdict) + + def install_specs(self, specs, installed, update_deps=True): + specs = list(map(MatchSpec, specs)) + snames = {s.name for s in specs} + log.debug("Checking satisfiability of current install") + limit, preserve = self.bad_installed(installed, specs) + for prec in installed: + if prec not in self.index: + continue + name, version, build = prec.name, prec.version, prec.build + schannel = prec.channel.canonical_name + if name in snames or limit is not None and name not in limit: + continue + # If update_deps=True, set the target package in MatchSpec so that + # the solver can minimize the version change. If update_deps=False, + # fix the version and build so that no change is possible. + if update_deps: + # TODO: fix target here + spec = MatchSpec(name=name, target=prec.dist_str()) + else: + spec = MatchSpec( + name=name, version=version, build=build, channel=schannel + ) + specs.insert(0, spec) + return tuple(specs), preserve + + def install(self, specs, installed=None, update_deps=True, returnall=False): + specs, preserve = self.install_specs(specs, installed or [], update_deps) + pkgs = [] + if specs: + pkgs = self.solve(specs, returnall=returnall, _remove=False) + self.restore_bad(pkgs, preserve) + return pkgs + + def remove_specs(self, specs, installed): + nspecs = [] + # There's an imperfect thing happening here. "specs" nominally contains + # a list of package names or track_feature values to be removed. But + # because of add_defaults_to_specs it may also contain version constraints + # like "python 2.7*", which are *not* asking for python to be removed. + # We need to separate these two kinds of specs here. + for s in map(MatchSpec, specs): + # Since '@' is an illegal version number, this ensures that all of + # these matches will never match an actual package. Combined with + # optional=True, this has the effect of forcing their removal. + if s._is_single(): + nspecs.append(MatchSpec(s, version="@", optional=True)) + else: + nspecs.append(MatchSpec(s, optional=True)) + snames = {s.name for s in nspecs if s.name} + limit, _ = self.bad_installed(installed, nspecs) + preserve = [] + for prec in installed: + nm, ver = prec.name, prec.version + if nm in snames: + continue + elif limit is not None: + preserve.append(prec) + else: + # TODO: fix target here + nspecs.append( + MatchSpec( + name=nm, + version=">=" + ver if ver else None, + optional=True, + target=prec.dist_str(), + ) + ) + return nspecs, preserve + + def remove(self, specs, installed): + specs, preserve = self.remove_specs(specs, installed) + pkgs = self.solve(specs, _remove=True) + self.restore_bad(pkgs, preserve) + return pkgs + + @time_recorder(module_name=__name__) + def solve( + self, + specs: list, + returnall: bool = False, + _remove=False, + specs_to_add=None, + history_specs=None, + should_retry_solve=False, + ) -> list[PackageRecord]: + if specs and not isinstance(specs[0], MatchSpec): + specs = tuple(MatchSpec(_) for _ in specs) + + specs = set(specs) + if log.isEnabledFor(DEBUG): + dlist = dashlist( + str("%i: %s target=%s optional=%s" % (i, s, s.target, s.optional)) + for i, s in enumerate(specs) + ) + log.debug("Solving for: %s", dlist) + + if not specs: + return () + + # Find the compliant packages + log.debug("Solve: Getting reduced index of compliant packages") + len0 = len(specs) + + reduced_index = self.get_reduced_index( + specs, exit_on_conflict=not context.unsatisfiable_hints + ) + if not reduced_index: + # something is intrinsically unsatisfiable - either not found or + # not the right version + not_found_packages = set() + wrong_version_packages = set() + for s in specs: + if not self.find_matches(s): + if s.name in self.groups: + wrong_version_packages.add(s) + else: + not_found_packages.add(s) + if not_found_packages: + raise ResolvePackageNotFound(not_found_packages) + elif wrong_version_packages: + raise UnsatisfiableError( + [[d] for d in wrong_version_packages], chains=False + ) + if should_retry_solve: + # We don't want to call find_conflicts until our last try. + # This jumps back out to conda/cli/install.py, where the + # retries happen + raise UnsatisfiableError({}) + else: + self.find_conflicts(specs, specs_to_add, history_specs) + + # Check if satisfiable + log.debug("Solve: determining satisfiability") + + def mysat(specs, add_if=False): + constraints = r2.generate_spec_constraints(C, specs) + return C.sat(constraints, add_if) + + # Return a solution of packages + def clean(sol): + return [ + q + for q in (C.from_index(s) for s in sol) + if q and q[0] != "!" and "@" not in q + ] + + def is_converged(solution): + """Determine if the SAT problem has converged to a single solution. + + This is determined by testing for a SAT solution with the current + clause set and a clause in which at least one of the packages in + the current solution is excluded. If a solution exists the problem + has not converged as multiple solutions still exist. + """ + psolution = clean(solution) + nclause = tuple(C.Not(C.from_name(q)) for q in psolution) + if C.sat((nclause,), includeIf=False) is None: + return True + return False + + r2 = Resolve(reduced_index, True, channels=self.channels) + C = r2.gen_clauses() + solution = mysat(specs, True) + if not solution: + if should_retry_solve: + # we don't want to call find_conflicts until our last try + raise UnsatisfiableError({}) + else: + self.find_conflicts(specs, specs_to_add, history_specs) + + speco = [] # optional packages + specr = [] # requested packages + speca = [] # all other packages + specm = set(r2.groups) # missing from specs + for k, s in enumerate(specs): + if s.name in specm: + specm.remove(s.name) + if not s.optional: + (speca if s.target or k >= len0 else specr).append(s) + elif any(r2.find_matches(s)): + s = MatchSpec(s.name, optional=True, target=s.target) + speco.append(s) + speca.append(s) + speca.extend(MatchSpec(s) for s in specm) + + if log.isEnabledFor(DEBUG): + log.debug("Requested specs: %s", dashlist(sorted(str(s) for s in specr))) + log.debug("Optional specs: %s", dashlist(sorted(str(s) for s in speco))) + log.debug("All other specs: %s", dashlist(sorted(str(s) for s in speca))) + log.debug("missing specs: %s", dashlist(sorted(str(s) for s in specm))) + + # Removed packages: minimize count + log.debug("Solve: minimize removed packages") + if _remove: + eq_optional_c = r2.generate_removal_count(C, speco) + solution, obj7 = C.minimize(eq_optional_c, solution) + log.debug("Package removal metric: %d", obj7) + + # Requested packages: maximize versions + log.debug("Solve: maximize versions of requested packages") + eq_req_c, eq_req_v, eq_req_b, eq_req_a, eq_req_t = r2.generate_version_metrics( + C, specr + ) + solution, obj3a = C.minimize(eq_req_c, solution) + solution, obj3 = C.minimize(eq_req_v, solution) + log.debug("Initial package channel/version metric: %d/%d", obj3a, obj3) + + # Track features: minimize feature count + log.debug("Solve: minimize track_feature count") + eq_feature_count = r2.generate_feature_count(C) + solution, obj1 = C.minimize(eq_feature_count, solution) + log.debug("Track feature count: %d", obj1) + + # Featured packages: minimize number of featureless packages + # installed when a featured alternative is feasible. + # For example, package name foo exists with two built packages. One with + # 'track_features: 'feat1', and one with 'track_features': 'feat2'. + # The previous "Track features" minimization pass has chosen 'feat1' for the + # environment, but not 'feat2'. In this case, the 'feat2' version of foo is + # considered "featureless." + eq_feature_metric = r2.generate_feature_metric(C) + solution, obj2 = C.minimize(eq_feature_metric, solution) + log.debug("Package misfeature count: %d", obj2) + + # Requested packages: maximize builds + log.debug("Solve: maximize build numbers of requested packages") + solution, obj4 = C.minimize(eq_req_b, solution) + log.debug("Initial package build metric: %d", obj4) + + # prefer arch packages where available for requested specs + log.debug("Solve: prefer arch over noarch for requested packages") + solution, noarch_obj = C.minimize(eq_req_a, solution) + log.debug("Noarch metric: %d", noarch_obj) + + # Optional installations: minimize count + if not _remove: + log.debug("Solve: minimize number of optional installations") + eq_optional_install = r2.generate_install_count(C, speco) + solution, obj49 = C.minimize(eq_optional_install, solution) + log.debug("Optional package install metric: %d", obj49) + + # Dependencies: minimize the number of packages that need upgrading + log.debug("Solve: minimize number of necessary upgrades") + eq_u = r2.generate_update_count(C, speca) + solution, obj50 = C.minimize(eq_u, solution) + log.debug("Dependency update count: %d", obj50) + + # Remaining packages: maximize versions, then builds + log.debug( + "Solve: maximize versions and builds of indirect dependencies. " + "Prefer arch over noarch where equivalent." + ) + eq_c, eq_v, eq_b, eq_a, eq_t = r2.generate_version_metrics(C, speca) + solution, obj5a = C.minimize(eq_c, solution) + solution, obj5 = C.minimize(eq_v, solution) + solution, obj6 = C.minimize(eq_b, solution) + solution, obj6a = C.minimize(eq_a, solution) + log.debug( + "Additional package channel/version/build/noarch metrics: %d/%d/%d/%d", + obj5a, + obj5, + obj6, + obj6a, + ) + + # Prune unnecessary packages + log.debug("Solve: prune unnecessary packages") + eq_c = r2.generate_package_count(C, specm) + solution, obj7 = C.minimize(eq_c, solution, trymax=True) + log.debug("Weak dependency count: %d", obj7) + + if not is_converged(solution): + # Maximize timestamps + eq_t.update(eq_req_t) + solution, obj6t = C.minimize(eq_t, solution) + log.debug("Timestamp metric: %d", obj6t) + + log.debug("Looking for alternate solutions") + nsol = 1 + psolutions = [] + psolution = clean(solution) + psolutions.append(psolution) + while True: + nclause = tuple(C.Not(C.from_name(q)) for q in psolution) + solution = C.sat((nclause,), True) + if solution is None: + break + nsol += 1 + if nsol > 10: + log.debug("Too many solutions; terminating") + break + psolution = clean(solution) + psolutions.append(psolution) + + if nsol > 1: + psols2 = list(map(set, psolutions)) + common = set.intersection(*psols2) + diffs = [sorted(set(sol) - common) for sol in psols2] + if not context.json: + stdoutlog.info( + "\nWarning: {} possible package resolutions " + "(only showing differing packages):{}{}".format( + ">10" if nsol > 10 else nsol, + dashlist(", ".join(diff) for diff in diffs), + "\n ... and others" if nsol > 10 else "", + ) + ) + + # def stripfeat(sol): + # return sol.split('[')[0] + + new_index = {self.to_sat_name(prec): prec for prec in self.index.values()} + + if returnall: + if len(psolutions) > 1: + raise RuntimeError() + # TODO: clean up this mess + # return [sorted(Dist(stripfeat(dname)) for dname in psol) for psol in psolutions] + # return [sorted((new_index[sat_name] for sat_name in psol), key=lambda x: x.name) + # for psol in psolutions] + + # return sorted(Dist(stripfeat(dname)) for dname in psolutions[0]) + return sorted( + (new_index[sat_name] for sat_name in psolutions[0]), key=lambda x: x.name + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/conda/utils.py b/data/miniconda3/lib/python3.13/site-packages/conda/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8667a07aa3152264d6fd97e08f9af4abf4c1435a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda/utils.py @@ -0,0 +1,442 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Utility functions.""" + +from __future__ import annotations + +import logging +import re +import sys +from functools import cache, wraps +from os import environ +from os.path import abspath, basename, dirname, isfile, join +from pathlib import Path +from shutil import which +from typing import TYPE_CHECKING + +from . import CondaError +from .activate import _build_activator_cls +from .auxlib.compat import Utf8NamedTemporaryFile, shlex_split_unicode +from .common.compat import isiterable, on_win +from .common.url import path_to_url +from .deprecations import deprecated + +if TYPE_CHECKING: + from collections.abc import Sequence + +log = logging.getLogger(__name__) + + +@deprecated( + "25.3", + "26.3", + addendum="Use `conda.common.path.unix_path_to_win` instead.", +) +def unix_path_to_win(path, root_prefix=""): + """Convert a path or :-separated string of paths into a Windows representation + Does not add cygdrive. If you need that, set root_prefix to "/cygdrive" + """ + if len(path) > 1 and (";" in path or (path[1] == ":" and path.count(":") == 1)): + # already a windows path + return path.replace("/", "\\") + path_re = root_prefix + r'(/[a-zA-Z]/(?:(?![:\s]/)[^:*?"<>])*)' + + def _translation(found_path): + group = found_path.group(0) + return "{}:{}".format( + group[len(root_prefix) + 1], + group[len(root_prefix) + 2 :].replace("/", "\\"), + ) + + translation = re.sub(path_re, _translation, path) + translation = re.sub( + ":([a-zA-Z]):\\\\", lambda match: ";" + match.group(0)[1] + ":\\", translation + ) + return translation + + +deprecated.constant("25.3", "26.3", "unix_path_to_win", unix_path_to_win) +del unix_path_to_win + + +def human_bytes(n): + """ + Return the number of bytes n in more human readable form. + + Note: Uses SI prefixes (KB, MB, GB) instead of binary prefixes (KiB, MiB, GiB). + + Examples: + >>> human_bytes(42) + '42 B' + >>> human_bytes(1042) + '1 KB' + >>> human_bytes(10004242) + '9.5 MB' + >>> human_bytes(100000004242) + '93.13 GB' + """ + if n < 1024: + return "%d B" % n + k = n / 1024 + if k < 1024: + return "%d KB" % round(k) + m = k / 1024 + if m < 1024: + return f"{m:.1f} MB" + g = m / 1024 + return f"{g:.2f} GB" + + +# ########################################## +# put back because of conda build +# ########################################## + +urlpath = url_path = path_to_url + + +@cache +def sys_prefix_unfollowed(): + """Since conda is installed into non-root environments as a symlink only + and because sys.prefix follows symlinks, this function can be used to + get the 'unfollowed' sys.prefix. + + This value is usually the same as the prefix of the environment into + which conda has been symlinked. An example of when this is necessary + is when conda looks for external sub-commands in find_commands.py + """ + try: + frame = next(iter(sys._current_frames().values())) + while frame.f_back: + frame = frame.f_back + code = frame.f_code + filename = code.co_filename + unfollowed = dirname(dirname(filename)) + except Exception: + return sys.prefix + return unfollowed + + +def quote_for_shell(*arguments): + """Properly quote arguments for command line passing. + + For POSIX uses `shlex.join`, for Windows uses a custom implementation to properly escape + metacharacters. + + :param arguments: Arguments to quote. + :type arguments: list of str + :return: Quoted arguments. + :rtype: str + """ + # [backport] Support passing in a list of strings or args of string. + if len(arguments) == 1 and isiterable(arguments[0]): + arguments = arguments[0] + + return _args_join(arguments) + + +if on_win: + # https://ss64.com/nt/syntax-esc.html + # https://docs.microsoft.com/en-us/archive/blogs/twistylittlepassagesallalike/everyone-quotes-command-line-arguments-the-wrong-way + + _RE_UNSAFE = re.compile(r'["%\s^<>&|]') + _RE_DBL = re.compile(r'(["%])') + + def _args_join(args): + """Return a shell-escaped string from *args*.""" + + def quote(s): + # derived from shlex.quote + if not s: + return '""' + # if any unsafe chars are present we must quote + if not _RE_UNSAFE.search(s): + return s + # double escape (" -> "") + s = _RE_DBL.sub(r"\1\1", s) + # quote entire string + return f'"{s}"' + + return " ".join(quote(arg) for arg in args) + +else: + from shlex import join as _args_join + + +# Ensures arguments are a tuple or a list. Strings are converted +# by shlex_split_unicode() which is bad; we warn about it or else +# we assert (and fix the code). +@deprecated("26.9", "27.3") +def massage_arguments(arguments, errors="assert"): + # For reference and in-case anything breaks .. + # .. one of the places (run_command in conda_env/utils.py) this + # gets called from used to do this too: + # + # def escape_for_winpath(p): + # return p.replace('\\', '\\\\') + # + # if not isinstance(arguments, list): + # arguments = list(map(escape_for_winpath, arguments)) + + if isinstance(arguments, str): + if errors == "assert": + # This should be something like 'conda programming bug' + raise RuntimeError("Please ensure arguments are not strings") + else: + arguments = shlex_split_unicode(arguments) + log.warning( + "Please ensure arguments is not a string; " + "used `shlex_split_unicode()` on it" + ) + + if not isiterable(arguments): + arguments = (arguments,) + + if any(isiterable(arg) for arg in arguments): + raise ValueError("Individual arguments must not be iterable") + arguments = list(arguments) + + return arguments + + +@deprecated.argument( + "26.9", + "27.3", + "use_system_tmp_path", + addendum="Use the TMPDIR, TEMP, or TMP environment variables to set the system temporary directory location.", +) +def wrap_subprocess_call( + root_prefix, + prefix, + dev_mode, + debug_wrapper_scripts, + arguments: Sequence[str], +): + # Ensure arguments is a tuple of strings + if not isiterable(arguments): + raise TypeError("`arguments` must be iterable") + arguments = tuple(map(str, arguments)) + + script_caller = None + multiline = False + if len(arguments) == 1 and "\n" in arguments[0]: + multiline = True + if on_win: + comspec = get_comspec() # fail early with KeyError if undefined + + with Utf8NamedTemporaryFile(mode="w", suffix=".bat", delete=False) as fh: + silencer = "" if debug_wrapper_scripts else "@" + fh.write(f"{silencer}ECHO OFF\n") + fh.write(f"{silencer}SET PYTHONIOENCODING=utf-8\n") + fh.write(f"{silencer}SET PYTHONUTF8=1\n") + fh.write( + f'{silencer}FOR /F "tokens=2 delims=:." %%A in (\'chcp\') do for %%B in (%%A) do set "_CONDA_OLD_CHCP=%%B"\n' + ) + fh.write(f"{silencer}chcp 65001 > NUL\n") + if dev_mode: + from . import CONDA_SOURCE_ROOT + + fh.write(f"{silencer}SET CONDA_DEV=1\n") + # In dev mode, conda is really: + # 'python -m conda' + # *with* PYTHONPATH set. + fh.write(f"{silencer}SET PYTHONPATH={CONDA_SOURCE_ROOT}\n") + fh.write(f"{silencer}SET CONDA_EXE={sys.executable}\n") + fh.write(f"{silencer}SET _CE_M=-m\n") + fh.write(f"{silencer}SET _CE_CONDA=conda\n") + if debug_wrapper_scripts: + fh.write("echo *** environment before *** 1>&2\n") + fh.write("SET 1>&2\n") + # Not sure there is any point in backing this up, nothing will get called with it reset + # after all! + # fh.write("@FOR /F \"tokens=100\" %%F IN ('chcp') DO @SET CONDA_OLD_CHCP=%%F\n") + # fh.write('@chcp 65001>NUL\n') + + # We pursue activation inline here, which allows us to avoid + # spawning a `conda activate` process at wrapper runtime. + activator_cls = _build_activator_cls("cmd.exe.run") + activator_args = ["activate"] + if dev_mode: + activator_args.append("--dev") + activator_args.append(prefix) + + activator = activator_cls(activator_args) + activator._parse_and_set_args() + activate_script = activator.activate() + + for line in activate_script.splitlines(): + fh.write(f"{silencer}{line}\n") + + fh.write(f"{silencer}IF %ERRORLEVEL% NEQ 0 EXIT /b %ERRORLEVEL%\n") + if debug_wrapper_scripts: + fh.write("echo *** environment after *** 1>&2\n") + fh.write("SET 1>&2\n") + if multiline: + # No point silencing the first line. If that's what's wanted then + # it needs doing for each line and the caller may as well do that. + fh.write(f"{arguments[0]}\n") + else: + if any("\n" in arg for arg in arguments): + raise NotImplementedError( + "Support for scripts where arguments contain newlines not implemented.\n" + ".. requires writing the script to an external file and knowing how to " + "transform the command-line (e.g. `python -c args` => `python file`) " + "in a tool dependent way, or attempting something like:\n" + ".. https://stackoverflow.com/a/15032476 (adds unacceptable escaping" + "requirements)" + ) + fh.write(f"{silencer}{quote_for_shell(*arguments)}\n") + # Capture the user's command exit code before deactivation, and + # run the deactivate.d hooks for the active environment, if any, + # sorted in reverse alphabetical order. + fh.write(f'{silencer}SET "_CONDA_EXE_RC=%ERRORLEVEL%"\n') + deactivate_d = Path(prefix) / "etc" / "conda" / "deactivate.d" + if deactivate_d.is_dir(): + deactivate_scripts = sorted( + deactivate_d.glob("*.bat"), + key=lambda p: p.name, + reverse=True, + ) + for script in deactivate_scripts: + if script.is_file(): + fh.write(f'{silencer}CALL "{script}"\n') + + fh.write(f"{silencer}chcp %_CONDA_OLD_CHCP%>NUL\n") + # Always exit with the user's original exit code, not + # whatever the last deactivate script or chcp returned. + fh.write(f"{silencer}EXIT /B %_CONDA_EXE_RC%\n") + script_caller = fh.name + command_args = [comspec, "/d", "/c", script_caller] + else: + shell_path = which("bash") or which("sh") + if shell_path is None: + raise Exception("No compatible shell found!") + + # During tests, we sometimes like to have a temp env with e.g. an old python in it + # and have it run tests against the very latest development sources. For that to + # work we need extra smarts here, we want it to be instead: + if dev_mode: + conda_exe = [abspath(join(root_prefix, "bin", "python")), "-m", "conda"] + dev_arg = "--dev" + dev_args = [dev_arg] + else: + conda_exe = [ + environ.get("CONDA_EXE", abspath(join(root_prefix, "bin", "conda"))) + ] + dev_arg = "" + dev_args = [] + with Utf8NamedTemporaryFile(mode="w", delete=False) as fh: + # If any of these calls to the activation hook scripts fail, we want + # to exit the wrapper immediately and abort `conda run` right away. + fh.write("set -e\n") + if dev_mode: + from . import CONDA_SOURCE_ROOT + + fh.write(">&2 export PYTHONPATH=" + CONDA_SOURCE_ROOT + "\n") + hook_quoted = quote_for_shell(*conda_exe, "shell.posix", "hook", *dev_args) + if debug_wrapper_scripts: + fh.write(">&2 echo '*** environment before ***'\n>&2 env\n") + fh.write(f'>&2 echo "$({hook_quoted})"\n') + fh.write(f'eval "$({hook_quoted})"\n') + + # We pursue activation inline here, which allows us to avoid + # spawning a `conda activate` process at wrapper runtime. + activator_cls = _build_activator_cls("posix") + activator_args = ["activate"] + if dev_mode: + activator_args.append("--dev") + activator_args.append(prefix) + + activator = activator_cls(activator_args) + activator._parse_and_set_args() + activate_code = activator.activate() + + fh.write(activate_code) + + if debug_wrapper_scripts: + fh.write(">&2 echo '*** environment after ***'\n>&2 env\n") + # Disable exit-on-error for the user's command so we can capture its exit code. + fh.write("set +e\n") + if multiline: + # The ' '.join() is pointless since mutliline is only True when there's 1 arg + # still, if that were to change this would prevent breakage. + fh.write("{}\n".format(" ".join(arguments))) + else: + fh.write(f"{quote_for_shell(*arguments)}\n") + # Capture the return code of the user's command in a variable + # before deactivating. We don't need to unset this per se, because + # the shell process will terminate and clean it up afterwards. + fh.write("_CONDA_EXE_RC=$?\n") + deactivate_d = Path(prefix) / "etc" / "conda" / "deactivate.d" + if deactivate_d.is_dir(): + deactivate_scripts = sorted( + deactivate_d.glob("*.sh"), + key=lambda p: p.name, + reverse=True, + ) + for script in deactivate_scripts: + if script.is_file(): + fh.write(f'. "{script}"\n') + + # Exit with this captured return code from the user's command. + fh.write("exit $_CONDA_EXE_RC\n") + script_caller = fh.name + if debug_wrapper_scripts: + command_args = [shell_path, "-x", script_caller] + else: + command_args = [shell_path, script_caller] + + return script_caller, command_args + + +def get_comspec(): + """Returns COMSPEC from envvars. + + Ensures COMSPEC envvar is set to cmd.exe, if not attempt to find it. + + :raises KeyError: COMSPEC is undefined and cannot be found. + :returns: COMSPEC value. + :rtype: str + """ + if basename(environ.get("COMSPEC", "")).lower() != "cmd.exe": + for comspec in ( + # %SystemRoot%\System32\cmd.exe + environ.get("SystemRoot") + and join(environ["SystemRoot"], "System32", "cmd.exe"), + # %windir%\System32\cmd.exe + environ.get("windir") and join(environ["windir"], "System32", "cmd.exe"), + ): + if comspec and isfile(comspec): + environ["COMSPEC"] = comspec + break + else: + log.warning( + "cmd.exe could not be found. Looked in SystemRoot and windir env vars.\n" + ) + + # fails with KeyError if still undefined + return environ["COMSPEC"] + + +def ensure_dir_exists(func): + """ + Ensures that the directory exists for functions returning + a Path object containing a directory + """ + + @wraps(func) + def wrapper(*args, **kwargs): + result = func(*args, **kwargs) + + if isinstance(result, Path): + try: + result.mkdir(parents=True, exist_ok=True) + except OSError as exc: + raise CondaError( + "Error encountered while attempting to create cache directory." + f"\n Directory: {result}" + f"\n Exception: {exc}" + ) + + return result + + return wrapper diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry/__init__.py b/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8c97011ee44a7deee086bc1a5e7f243e1c70bf12 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry/__init__.py @@ -0,0 +1,32 @@ +# Copyright (C) 2024 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""A conda plugin for Anaconda Telemetry.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from typing import Final + +#: Application name. +APP_NAME: Final = "conda-anaconda-telemetry" + +try: + from ._version import __version__ +except ImportError: + # _version.py is only created after running `pip install` + try: + from setuptools_scm import get_version + + __version__ = get_version(root="..", relative_to=__file__) + except (ImportError, OSError, LookupError): + # ImportError: setuptools_scm isn't installed + # OSError: git isn't installed + # LookupError: setuptools_scm unable to detect version + # conda-anaconda-telemetry follows SemVer, so the dev version is: + # MJ.MN.MICRO.devN+gHASH[.dirty] + __version__ = "0.0.0.dev0+placeholder" + +#: Application version. +APP_VERSION: Final = __version__ diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry/_version.py b/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..ac8d8d494d79bd19c708ea69e224679485cf1b37 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry/_version.py @@ -0,0 +1,21 @@ +# file generated by setuptools-scm +# don't change, don't track in version control + +__all__ = ["__version__", "__version_tuple__", "version", "version_tuple"] + +TYPE_CHECKING = False +if TYPE_CHECKING: + from typing import Tuple + from typing import Union + + VERSION_TUPLE = Tuple[Union[int, str], ...] +else: + VERSION_TUPLE = object + +version: str +__version__: str +__version_tuple__: VERSION_TUPLE +version_tuple: VERSION_TUPLE + +__version__ = version = '0.3.0' +__version_tuple__ = version_tuple = (0, 3, 0) diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry/hooks.py b/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry/hooks.py new file mode 100644 index 0000000000000000000000000000000000000000..d0f44f089e9f17224fee7987f88096fee0ef1aae --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry/hooks.py @@ -0,0 +1,289 @@ +# Copyright (C) 2024 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Conda plugin that adds telemetry headers to requests made by conda.""" + +from __future__ import annotations + +import functools +import logging +import re +import time +import typing + +from conda.base.context import context +from conda.cli.main_list import list_packages +from conda.common.configuration import PrimitiveParameter +from conda.common.url import mask_anaconda_token +from conda.models.channel import all_channel_urls +from conda.plugins import CondaRequestHeader, CondaSetting, hookimpl + +try: + from conda_build import __version__ as conda_build_version +except ImportError: + conda_build_version = "n/a" + +if typing.TYPE_CHECKING: + from collections.abc import Iterator, Sequence + from typing import Callable + +logger = logging.getLogger(__name__) + +#: Field separator for request header +FIELD_SEPARATOR = ";" + +#: Size limit in bytes for the payload in the request header +SIZE_LIMIT = 7_000 + +#: Prefix for all custom headers submitted via this plugin +# Note: header names are normalized to lowercase by the HTTP layer, so keep +# the prefix lowercased to match the actual header names emitted at runtime. +HEADER_PREFIX = "anaconda-telemetry" + +#: Name of the virtual package header +HEADER_VIRTUAL_PACKAGES = f"{HEADER_PREFIX}-virtual-packages" + +#: Name of the channels header +HEADER_CHANNELS = f"{HEADER_PREFIX}-channels" + +#: Name of the packages header +HEADER_PACKAGES = f"{HEADER_PREFIX}-packages" + +#: Name of the search header +HEADER_SEARCH = f"{HEADER_PREFIX}-search" + +#: Name of the install header +HEADER_INSTALL = f"{HEADER_PREFIX}-install" + +#: Name of the sys info header +HEADER_SYS_INFO = f"{HEADER_PREFIX}-sys-info" + +#: Regex pattern for hosts and paths we want to submit request headers to +REQUEST_HEADER_PATTERN = re.compile( + r""" + ^ # Start of string + (?: # Non-capturing group for host patterns + repo\.anaconda\. # repo.anaconda. (literal dots) + (?:com|cloud) # Either "com" or "cloud" + (?:/.*)? # Optional path starting with forward slash + | # OR + conda\.anaconda\.org/ # conda.anaconda.org/ (literal dots and slash) + (?: # Non-capturing group for channel paths + anaconda| # anaconda channel + conda-forge| # conda-forge channel + main| # main channel + msys2| # msys2 channel + r # r channel + ) + /.* # Forward slash followed by any characters + ) + $ # End of string + """, + re.VERBOSE, +) + + +def timer(func: Callable) -> Callable: + """Log the duration of a function call.""" + + @functools.wraps(func) + def wrapper_timer(*args: tuple, **kwargs: dict) -> Callable: + """Wrap the given function.""" + if logger.getEffectiveLevel() <= logging.INFO: + tic = time.perf_counter() + value = func(*args, **kwargs) + toc = time.perf_counter() + elapsed_time = toc - tic + logger.info( + "function: %s; duration (seconds): %0.4f", + func.__name__, + elapsed_time, + ) + return value + + return func(*args, **kwargs) + + return wrapper_timer + + +def get_virtual_packages() -> tuple[str, ...]: + """Retrieve the registered virtual packages from conda's context.""" + return tuple( + f"{package.name}={package.version}={package.build}" + for package in context.plugin_manager.get_virtual_package_records() + ) + + +def get_channel_urls() -> tuple[str, ...]: + """Return a list of currently configured channel URLs with tokens masked.""" + channels = list(all_channel_urls(context.channels)) + return tuple(mask_anaconda_token(c) for c in channels) + + +def get_conda_command() -> str: + """Use ``sys.argv`` to determine the conda command that is current being run.""" + return context._argparse_args.cmd + + +def get_package_list() -> tuple[str, ...]: + """Retrieve the list of packages in the current environment.""" + prefix = context.active_prefix or context.root_prefix + _, packages = list_packages(prefix, format="canonical") + + return packages + + +def get_search_term() -> str: + """Retrieve the search term being used when search command is run.""" + return context._argparse_args.match_spec + + +def get_install_arguments() -> tuple[str, ...]: + """Get the parsed position argument.""" + return context._argparse_args.packages + + +@timer +@functools.lru_cache(None) +def get_sys_info_header_value() -> str: + """Return ``;`` delimited string of extra system information.""" + telemetry_data = { + "conda_build_version": conda_build_version, + "conda_command": get_conda_command(), + } + + return FIELD_SEPARATOR.join( + f"{key}:{value}" for key, value in telemetry_data.items() + ) + + +@timer +@functools.lru_cache(None) +def get_channel_urls_header_value() -> str: + """Return ``FIELD_SEPARATOR`` delimited string of channel URLs.""" + return FIELD_SEPARATOR.join(get_channel_urls()) + + +@timer +@functools.lru_cache(None) +def get_virtual_packages_header_value() -> str: + """Return ``FIELD_SEPARATOR`` delimited string of virtual packages.""" + return FIELD_SEPARATOR.join(get_virtual_packages()) + + +@timer +@functools.lru_cache(None) +def get_install_arguments_header_value() -> str: + """Return ``FIELD_SEPARATOR`` delimited string of channel URLs.""" + return FIELD_SEPARATOR.join(get_install_arguments()) + + +@timer +@functools.lru_cache(None) +def get_installed_packages_header_value() -> str: + """Return ``FIELD_SEPARATOR`` delimited string of install arguments.""" + return FIELD_SEPARATOR.join(get_package_list()) + + +class HeaderWrapper(typing.NamedTuple): + """Object that wraps ``CondaRequestHeader`` and adds a ``size_limit`` field.""" + + header: CondaRequestHeader + size_limit: int + + +def validate_headers( + header_wrappers: Sequence[HeaderWrapper], +) -> Iterator[CondaRequestHeader]: + """Make sure that all headers combined are not larger than ``SIZE_LIMIT``. + + Any headers over their individual limits will be truncated. + """ + for wrapper in header_wrappers: + wrapper.header.value = wrapper.header.value[: wrapper.size_limit] + yield wrapper.header + + +def _conda_request_headers() -> Sequence[HeaderWrapper]: + custom_headers = [ + HeaderWrapper( + header=CondaRequestHeader( + name=HEADER_SYS_INFO, + value=get_sys_info_header_value(), + ), + size_limit=500, + ), + HeaderWrapper( + header=CondaRequestHeader( + name=HEADER_CHANNELS, + value=get_channel_urls_header_value(), + ), + size_limit=500, + ), + HeaderWrapper( + header=CondaRequestHeader( + name=HEADER_VIRTUAL_PACKAGES, + value=get_virtual_packages_header_value(), + ), + size_limit=500, + ), + HeaderWrapper( + header=CondaRequestHeader( + name=HEADER_PACKAGES, + value=get_installed_packages_header_value(), + ), + size_limit=5_000, + ), + ] + + command = get_conda_command() + + if command == "search": + custom_headers.append( + HeaderWrapper( + header=CondaRequestHeader( + name=HEADER_SEARCH, + value=get_search_term(), + ), + size_limit=500, + ) + ) + + elif command in {"install", "create"}: + custom_headers.append( + HeaderWrapper( + header=CondaRequestHeader( + name=HEADER_INSTALL, + value=get_install_arguments_header_value(), + ), + size_limit=500, + ) + ) + + return custom_headers + + +def should_submit_request_headers(host: str, path: str) -> bool: + """Return whether we should submit request headers to the given host and path.""" + return REQUEST_HEADER_PATTERN.match(f"{host}{path}") is not None + + +@hookimpl +def conda_request_headers(host: str, path: str) -> Iterator[CondaRequestHeader]: + """Return a list of custom headers to be included in the request.""" + try: + if context.plugins.anaconda_telemetry and should_submit_request_headers( + host, path + ): + yield from validate_headers(_conda_request_headers()) + except Exception as exc: + logger.debug("Failed to collect telemetry data", exc_info=exc) + + +@hookimpl +def conda_settings() -> Iterator[CondaSetting]: + """Return a list of settings that can be configured by the user.""" + yield CondaSetting( + name="anaconda_telemetry", + description="Whether Anaconda Telemetry is enabled", + parameter=PrimitiveParameter(True, element_type=bool), + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry/py.typed b/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/__init__.py b/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d86b0941639c68a9d4b027d92f667cc598433585 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/__init__.py @@ -0,0 +1,32 @@ +# Copyright (C) 2024 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Conda channel's Terms of Service management plugin.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from typing import Final + +#: Application name. +APP_NAME: Final = "conda-anaconda-tos" + +try: + from ._version import __version__ +except ImportError: + # _version.py is only created after running `pip install` + try: + from setuptools_scm import get_version + + __version__ = get_version(root="..", relative_to=__file__) + except (ImportError, OSError, LookupError): + # ImportError: setuptools_scm isn't installed + # OSError: git isn't installed + # LookupError: setuptools_scm unable to detect version + # conda-anaconda-tos follows SemVer, so the dev version is: + # MJ.MN.MICRO.devN+gHASH[.dirty] + __version__ = "0.0.0.dev0+placeholder" + +#: Application version. +APP_VERSION: Final = __version__ diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/_version.py b/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..e38f676dc504b9efb2253f6b65ae06b9ef3e6ec6 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/_version.py @@ -0,0 +1,21 @@ +# file generated by setuptools-scm +# don't change, don't track in version control + +__all__ = ["__version__", "__version_tuple__", "version", "version_tuple"] + +TYPE_CHECKING = False +if TYPE_CHECKING: + from typing import Tuple + from typing import Union + + VERSION_TUPLE = Tuple[Union[int, str], ...] +else: + VERSION_TUPLE = object + +version: str +__version__: str +__version_tuple__: VERSION_TUPLE +version_tuple: VERSION_TUPLE + +__version__ = version = '0.2.2' +__version_tuple__ = version_tuple = (0, 2, 2) diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/api.py b/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/api.py new file mode 100644 index 0000000000000000000000000000000000000000..6033f471e0082f75c1ff42e2ed9fd33946f5e8ff --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/api.py @@ -0,0 +1,327 @@ +# Copyright (C) 2024 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""High-level API functions for interacting with a channel's Terms of Service.""" + +from __future__ import annotations + +import os +from pathlib import Path +from typing import TYPE_CHECKING + +from conda.auxlib.type_coercion import boolify +from conda.models.channel import Channel + +from .exceptions import CondaToSMissingError +from .local import get_local_metadata, get_local_metadatas, write_metadata +from .models import LocalPair, RemotePair +from .path import get_all_channel_paths, get_cache_paths +from .remote import get_remote_metadata + +if TYPE_CHECKING: + from collections.abc import Iterable, Iterator + from typing import Final + + +#: Boolean CI environment variables (checked with boolify) +#: Sources: Official CI platform documentation and community knowledge base +CI_BOOLEAN_VARS: Final = ( + "APPVEYOR", # AppVeyor CI (https://www.appveyor.com/docs/environment-variables/) + "BITRISE_IO", # Bitrise (https://devcenter.bitrise.io/en/references/available-environment-variables.html) + "BUDDY", # Buddy CI/CD (https://buddy.works/docs/pipelines/environment-variables) + "BUILDKITE", # Buildkite (https://buildkite.com/docs/pipelines/environment-variables) + "CI", # Generic CI indicator (many platforms) + "CIRCLECI", # CircleCI (https://circleci.com/docs/variables/#built-in-environment-variables) + "CIRRUS_CI", # Cirrus CI (https://cirrus-ci.org/guide/environment-variables/) + "CONCOURSE_CI", # Concourse CI (https://concourse-ci.org/implementing-resource-types.html#environment) + "DRONE", # Drone CI (https://docs.drone.io/pipeline/environment/reference/) + "GITHUB_ACTIONS", # GitHub Actions (https://docs.github.com/en/actions/learn-github-actions/variables#default-environment-variables) + "GITLAB_CI", # GitLab CI/CD (https://docs.gitlab.com/ee/ci/variables/predefined_variables.html) + "SAIL_CI", # Sail CI + "SEMAPHORE", # Semaphore CI (https://docs.semaphoreci.com/ci-cd-environment/environment-variables/) + "TF_BUILD", # Azure DevOps (Team Foundation) (https://docs.microsoft.com/en-us/azure/devops/pipelines/build/variables) + "TRAVIS", # Travis CI (https://docs.travis-ci.com/user/environment-variables/#default-environment-variables) + "WERCKER", # Wercker (deprecated) + "WOODPECKER_CI", # Woodpecker CI (https://woodpecker-ci.org/docs/usage/environment) +) + +#: Presence-based CI environment variables (checked for existence) +#: Sources: Official CI platform documentation +CI_PRESENCE_VARS: Final = ( + "BAMBOO_BUILDKEY", # Atlassian Bamboo (https://confluence.atlassian.com/bamboo/bamboo-variables-289277087.html) + "CODEBUILD_BUILD_ID", # AWS CodeBuild (https://docs.aws.amazon.com/codebuild/latest/userguide/build-env-ref-env-vars.html) + "HEROKU_TEST_RUN_ID", # Heroku CI (https://devcenter.heroku.com/articles/heroku-ci#environment-variables) + "JENKINS_URL", # Jenkins (https://www.jenkins.io/doc/book/pipeline/jenkinsfile/#using-environment-variables) + "TEAMCITY_VERSION", # JetBrains TeamCity (https://www.jetbrains.com/help/teamcity/predefined-build-parameters.html) +) + + +#: Container indicators for cgroup detection +#: Reference: https://github.com/containers/podman/issues/3586, +#: Docker/containerd documentation +CONTAINER_INDICATORS: Final = ( + "containerd", # containerd runtime + "docker", # Docker containers + "kubepods", # Kubernetes pods (https://kubernetes.io/docs/tasks/administer-cluster/migrating-from-dockershim/find-out-runtime-you-use/) + "lxc", # Linux Containers + "podman", # Podman containers +) + +#: Partial CI environment variables (used with container detection) +#: These variables may be present in containerized CI environments that don't +#: set full CI variables +PARTIAL_CI_VARS: Final = ( + "AZURE_HTTP_USER_AGENT", # Azure DevOps user agent + "BUILD_ID", # Generic build identifier (Jenkins, etc.) + "BUILD_NUMBER", # Generic build number (Jenkins, etc.) + "BUILD_URL", # Generic build URL (Jenkins, etc.) + "BUILDKITE_BUILD_ID", # Buildkite build identifier + "CIRCLE_BUILD_NUM", # CircleCI build number + "CIRCLE_PROJECT_REPONAME", # CircleCI repository name + "GITHUB_JOB", # GitHub Actions job name + "GITHUB_REPOSITORY", # GitHub repository name + "GITHUB_WORKFLOW", # GitHub Actions workflow name + "GITLAB_PROJECT_ID", # GitLab project identifier + "GITLAB_USER_ID", # GitLab user identifier + "JOB_NAME", # Generic job name (Jenkins, etc.) + "RUNNER_ARCH", # GitHub Actions runner architecture + "RUNNER_OS", # GitHub Actions runner OS + "WORKSPACE", # Generic workspace path (Jenkins, etc.) +) + + +def _in_ci_container() -> bool: + """Detect if running in a containerized CI environment. + + This function combines container detection with partial CI environment variables + to address cases where CI systems run jobs in containers but don't set complete + CI environment variables (see GitHub issue #232). This is a workaround for + https://github.com/anaconda/conda-anaconda-tos/issues/232. + + Returns: + bool: True if both container indicators and partial CI variables are present + + """ + # Check documented container indicators + container_checks = [ + os.getpid() == 1, # Process ID 1 (init process in containers) + bool(os.environ.get("CONTAINER")), # Generic container environment variable + ] + + # Check cgroup for container runtime identifiers (Docker official method) + # Reference: https://docs.docker.com/engine/containers/runmetrics/#find-the-cgroup-for-a-given-container + try: + with Path("/proc/self/cgroup").open() as f: + cgroup_content = f.read() + # Container runtime signatures in cgroups (documented by Docker): + # - "docker": Docker containers + # - "containerd": containerd runtime + # - "kubepods": Kubernetes pods + # - "lxc": Linux Containers + # - "podman": Podman containers + if any(indicator in cgroup_content for indicator in CONTAINER_INDICATORS): + container_checks.append(True) + except OSError: + # Ignore errors (e.g., on non-Linux systems or restricted access) + pass + + # Return True only if we detect container AND partial CI indicators + # This prevents false positives from containers without CI context + return any(container_checks) and any(os.getenv(var) for var in PARTIAL_CI_VARS) + + +def _is_ci() -> bool: + """Determine if running in a CI environment. + + This function uses a multi-layered approach to detect CI environments: + 1. First checks if any CI variables are explicitly set to false + (respects user override) + 2. Then checks boolean CI variables for true values + 3. Finally checks presence-based variables and container environments + + Returns: + bool: True if running in a detected CI environment + + """ + # Check all boolean CI variables for explicit false values first + # If any CI variable is explicitly set to false, respect that + for var_value in map(os.getenv, CI_BOOLEAN_VARS): + if var_value and not boolify(var_value): + return False + + # Check boolean CI environment variables for true values + for var_value in map(os.getenv, CI_BOOLEAN_VARS): + if boolify(var_value): + return True + + # Check presence-based CI environment variables + return any(os.getenv(var) for var in CI_PRESENCE_VARS) or _in_ci_container() + + +#: Whether the current environment is a CI environment +CI: Final = _is_ci() + +#: Whether the current environment is a Jupyter environment +JUPYTER: Final = os.getenv("JPY_SESSION_NAME") and os.getenv("JPY_PARENT_PID") + + +def get_channels(*channels: str | Channel) -> Iterable[Channel]: + """Yield all unique channels from the given channels.""" + # expand every multichannel into its individual channels + # and remove any duplicates + seen: set[Channel] = set() + for multichannel in map(Channel, channels): + for channel in map(Channel, multichannel.urls()): + channel = Channel(channel.base_url) + if channel not in seen: + yield channel + seen.add(channel) + + +def get_one_tos( + channel: str | Channel, + *, + tos_root: str | os.PathLike[str] | Path, + cache_timeout: int | float | None, +) -> LocalPair | RemotePair: + """Get the Terms of Service metadata for the given channel.""" + # fetch remote metadata + remote_metadata = remote_exc = None + try: + remote_metadata = get_remote_metadata(channel, cache_timeout=cache_timeout) + except CondaToSMissingError as exc: + # CondaToSMissingError: no remote metadata + remote_exc = exc + + # fetch local metadata + try: + local_pair = get_local_metadata(channel, extend_search_path=[tos_root]) + except CondaToSMissingError as exc: + # CondaToSMissingError: no local metadata + if remote_exc: + raise remote_exc from exc + # no local ToS metadata + return RemotePair(metadata=remote_metadata) + else: + # return local metadata, include remote metadata if newer + if not remote_metadata or local_pair.metadata >= remote_metadata: + return local_pair + return LocalPair( + metadata=local_pair.metadata, + path=local_pair.path, + remote=remote_metadata, + ) + + +def get_stored_tos( + *, + tos_root: str | os.PathLike[str] | Path, + cache_timeout: int | float | None, +) -> Iterator[tuple[Channel, LocalPair]]: + """Yield metadata of all stored Terms of Service.""" + for channel, local_pair in get_local_metadatas(extend_search_path=[tos_root]): + try: + remote_metadata = get_remote_metadata(channel, cache_timeout=cache_timeout) + except CondaToSMissingError: + # CondaToSMissingError: no remote metadata + continue + + # yield local metadata, include remote metadata if newer + if local_pair.metadata >= remote_metadata: + yield channel, local_pair + else: + yield ( + channel, + LocalPair( + metadata=local_pair.metadata, + path=local_pair.path, + remote=remote_metadata, + ), + ) + + +def accept_tos( + channel: str | Channel, + *, + tos_root: str | os.PathLike[str] | Path, + cache_timeout: int | float | None, +) -> LocalPair: + """Accept the Terms of Service for the given channel.""" + pair = get_one_tos( + channel, + tos_root=tos_root, + cache_timeout=cache_timeout, + ) + metadata = pair.remote or pair.metadata + return write_metadata(tos_root, channel, metadata, tos_accepted=True) + + +def reject_tos( + channel: str | Channel, + *, + tos_root: str | os.PathLike[str] | Path, + cache_timeout: int | float | None, +) -> LocalPair: + """Reject the Terms of Service for the given channel.""" + pair = get_one_tos( + channel, + tos_root=tos_root, + cache_timeout=cache_timeout, + ) + metadata = pair.remote or pair.metadata + return write_metadata(tos_root, channel, metadata, tos_accepted=False) + + +def get_all_tos( + *channels: str | Channel, + tos_root: str | os.PathLike | Path, + cache_timeout: int | float | None, +) -> Iterator[tuple[Channel, LocalPair | RemotePair | None]]: + """List all channels and whether their Terms of Service have been accepted.""" + # list all active channels + seen: set[Channel] = set() + for channel in get_channels(*channels): + try: + yield ( + channel, + get_one_tos(channel, tos_root=tos_root, cache_timeout=cache_timeout), + ) + except CondaToSMissingError: + yield channel, None + seen.add(channel) + + # list all other channels whose Terms of Service have been accepted/rejected + for channel, metadata_pair in get_stored_tos( + tos_root=tos_root, + cache_timeout=cache_timeout, + ): + if channel not in seen: + yield channel, metadata_pair + seen.add(channel) + + +def clean_cache() -> Iterator[Path]: + """Clean all metadata cache files.""" + for path in get_cache_paths(): + try: + path.unlink() + except (PermissionError, FileNotFoundError, IsADirectoryError): + # PermissionError: no permission to delete the file + # FileNotFoundError: the file doesn't exist + # IsADirectoryError: the path is a directory + pass + else: + yield path + + +def clean_tos(tos_root: str | os.PathLike[str] | Path) -> Iterator[Path]: + """Clean all metadata directories.""" + for path in get_all_channel_paths(extend_search_path=[tos_root]): + try: + path.unlink() + except (PermissionError, FileNotFoundError, IsADirectoryError): + # PermissionError: no permission to delete the file + # FileNotFoundError: the file doesn't exist + # IsADirectoryError: the path is a directory + pass + else: + yield path diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/exceptions.py b/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..46b2394c3c73e3f3fd06fdbc1b8480ba0533a55b --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/exceptions.py @@ -0,0 +1,115 @@ +# Copyright (C) 2024 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Custom exceptions.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from conda.exceptions import CondaError +from conda.models.channel import Channel + +if TYPE_CHECKING: + import os + from collections.abc import Iterable + from pathlib import Path + from typing import Self + + +class CondaToSError(CondaError): + """Base exception.""" + + +class CondaToSMissingError(CondaToSError): + """Error class for when the metadata is missing for a channel.""" + + def __init__(self: Self, channel: str | Channel) -> None: + """Format error message with channel base URL.""" + super().__init__(f"No Terms of Service for {_url(channel)}.") + + +class CondaToSInvalidError(CondaToSMissingError): + """Error class for when the metadata is invalid for a channel.""" + + def __init__(self: Self, channel: str | Channel) -> None: + """Format error message with channel base URL.""" + super().__init__(f"Invalid Terms of Service for {_url(channel)}.") + + +class CondaToSPermissionError(PermissionError, CondaToSError): + """Error class for when the metadata file cannot be written.""" + + def __init__( + self: Self, + path: str | os.PathLike[str] | Path, + channel: str | Channel | None = None, + ) -> None: + """Format error message with channel base URL and path.""" + addendum = f" for {_url(channel)}" if channel else "" + super().__init__( + f"Unable to read/write path ({path}){addendum}. Please check permissions." + ) + + +class CondaToSRejectedError(CondaToSError): + """Error class for when the Terms of Service are rejected for a channel.""" + + def __init__(self: Self, *channels: str | Channel) -> None: + """Format error message with channel base URL.""" + channel_urls = [_url(channel) for channel in channels] + accept_commands = [ + f"conda tos accept --override-channels --channel {url}" + for url in channel_urls + ] + + super().__init__( + f"Terms of Service has been rejected for the following channels. " + f"Please remove or accept them before proceeding:\n" + f"{_bullet(channel_urls)}\n" + f"\n" + f"To accept these channels' Terms of Service, run the following commands:\n" + f"{_bullet(accept_commands, prefix=' ')}\n" + f"\n" + f"{_get_removal_guidance()}" + ) + + +class CondaToSNonInteractiveError(CondaToSError): + """Error class when Terms of Service are not actionable in non-interactive mode.""" + + def __init__(self: Self, *channels: str | Channel) -> None: + """Format error message with channel base URL.""" + channel_urls = [_url(channel) for channel in channels] + accept_commands = [ + f"conda tos accept --override-channels --channel {url}" + for url in channel_urls + ] + + super().__init__( + f"Terms of Service have not been accepted for the following channels. " + f"Please accept or remove them before proceeding:\n" + f"{_bullet(channel_urls)}\n" + f"\n" + f"To accept these channels' Terms of Service, run the following commands:\n" + f"{_bullet(accept_commands, prefix=' ')}\n" + f"\n" + f"{_get_removal_guidance()}" + ) + + +def _url(channel: str | Channel) -> str: + _channel = channel if isinstance(channel, Channel) else Channel(str(channel)) + return str(_channel.base_url or channel) + + +def _bullet(args: Iterable[str], *, prefix: str = " - ") -> str: + return prefix + f"\n{prefix}".join(args) + + +def _get_removal_guidance() -> str: + """Generate removal guidance based on channel types.""" + return ( + "For information on safely removing channels from your conda configuration,\n" + "please see the official documentation:\n\n" + " https://www.anaconda.com/docs/tools/working-with-conda/channels" + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/local.py b/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/local.py new file mode 100644 index 0000000000000000000000000000000000000000..3e715e21d18c0658082a3a1096575934a718213e --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/local.py @@ -0,0 +1,120 @@ +# Copyright (C) 2024 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Low-level local (acceptance & rejection) Terms of Service metadata management.""" + +from __future__ import annotations + +from datetime import datetime, timezone +from typing import TYPE_CHECKING + +from conda.models.channel import Channel +from pydantic import ValidationError + +from .exceptions import CondaToSMissingError, CondaToSPermissionError +from .models import LocalPair, LocalToSMetadata, RemoteToSMetadata +from .path import get_all_channel_paths, get_channel_paths, get_metadata_path, get_path + +if TYPE_CHECKING: + import os + from collections.abc import Iterable, Iterator + from pathlib import Path + from typing import Any + + +def write_metadata( + tos_root: str | os.PathLike[str] | Path, + channel: str | Channel, + metadata: LocalToSMetadata | RemoteToSMetadata, + # kwargs extends/overrides metadata fields + **kwargs: Any, # noqa: ANN401 +) -> LocalPair: + """Write the metadata to file.""" + # argument validation/coercion + channel = Channel(channel) + if not channel.base_url: + raise ValueError("`channel` must have a base URL.") + if not isinstance(metadata, (LocalToSMetadata, RemoteToSMetadata)): + raise TypeError("`metadata` must be a LocalToSMetadata or RemoteToSMetadata.") + + # create/update ToSMetadata object + metadata = LocalToSMetadata( + **{ + **metadata.model_dump(), + **kwargs, + # override the following fields with the current time and channel base URL + "acceptance_timestamp": datetime.now(tz=timezone.utc), + "base_url": channel.base_url, + } + ) + + # write metadata to file + path = get_metadata_path(tos_root, channel, metadata.version) + try: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(metadata.model_dump_json()) + except PermissionError as exc: + # PermissionError: can't write metadata path + raise CondaToSPermissionError(path, channel) from exc + + return LocalPair(metadata=metadata, path=path) + + +def read_metadata(path: str | os.PathLike[str] | Path) -> LocalPair | None: + """Load the metadata from file.""" + try: + return LocalPair( + metadata=LocalToSMetadata.model_validate_json(get_path(path).read_text()), + path=path, + ) + except (FileNotFoundError, ValidationError): + # FileNotFoundError: metadata path doesn't exist + # ValidationError: invalid JSON schema, treat it as missing + return None + except PermissionError as exc: + # PermissionError: can't read metadata path + raise CondaToSPermissionError(path) from exc + + +def get_local_metadata( + channel: str | Channel, + *, + extend_search_path: Iterable[str | os.PathLike[str] | Path] | None = None, +) -> LocalPair: + """Get the latest metadata for the given channel.""" + # find all metadata files for the given channel + metadata_pairs = [ + metadata_pair + for path in get_channel_paths(channel, extend_search_path=extend_search_path) + if (metadata_pair := read_metadata(path)) + ] + + # return if no metadata found + if not metadata_pairs: + raise CondaToSMissingError(f"No Terms of Service metadata found for {channel}") + + # reverse to order from lowest to highest priority + metadata_pairs.reverse() + + # return newest (and highest priority) metadata for channel + return sorted(metadata_pairs)[-1] + + +def get_local_metadatas( + *, + extend_search_path: Iterable[str | os.PathLike[str] | Path] | None = None, +) -> Iterator[tuple[Channel, LocalPair]]: + """Yield all metadata.""" + # group metadata by channel + grouped_metadatas: dict[Channel, list[LocalPair]] = {} + for path in get_all_channel_paths(extend_search_path=extend_search_path): + if metadata_pair := read_metadata(path): + channel = Channel(metadata_pair.metadata.base_url) + grouped_metadatas.setdefault(channel, []).append(metadata_pair) + + # return the newest (and highest priority) metadata for each channel + for channel, metadata_pairs in grouped_metadatas.items(): + # reverse to order from lowest to highest priority + metadata_pairs.reverse() + + # yield newest (and highest priority) metadata for channel + yield channel, sorted(metadata_pairs)[-1] diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/models.py b/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/models.py new file mode 100644 index 0000000000000000000000000000000000000000..cae06ce4df993bfc1b6f866bd9e4a46e133fe2df --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/models.py @@ -0,0 +1,77 @@ +# Copyright (C) 2024 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Models to encapsulate Terms of Service metadata.""" + +from __future__ import annotations + +from datetime import datetime # noqa: TC003 # needed for Pydantic model +from pathlib import Path # noqa: TC003 # needed for Pydantic model +from typing import TYPE_CHECKING, Optional + +from pydantic import BaseModel, ConfigDict + +if TYPE_CHECKING: + from typing import Self + + +class _ToSMetadata(BaseModel): + model_config = ConfigDict(extra="allow", frozen=True) + version: datetime + text: str + support: str + + def __ge__(self: Self, other: _ToSMetadata) -> bool: + """Compare the ToS metadata version.""" + if not isinstance(other, _ToSMetadata): + return NotImplemented + return self.version >= other.version + + +class RemoteToSMetadata(_ToSMetadata): + """Metadata schema for the remote endpoint.""" + + +class LocalToSMetadata(_ToSMetadata): + """Metadata schema with acceptance fields.""" + + base_url: str + tos_accepted: bool + acceptance_timestamp: datetime + + +class _MetadataPathPair(BaseModel): + model_config = ConfigDict(frozen=True) + metadata: _ToSMetadata + # FUTURE: Python 3.10+, switch to `Path | None` + path: Optional[Path] # noqa: UP045 + # FUTURE: Python 3.10+, switch to `_ToSMetadata | None` + remote: Optional[RemoteToSMetadata] = None # noqa: UP045 + + def __lt__(self: Self, other: _MetadataPathPair) -> bool: + """Compare the metadata version. + + Critical for sorting a list of metadata path pairs. + """ + if not isinstance(other, _MetadataPathPair): + return NotImplemented + return self.metadata.version < other.metadata.version + + @property + def latest_text(self: Self) -> str: + """Get the latest text of the Terms of Service.""" + return (self.remote or self.metadata).text + + +class RemotePair(_MetadataPathPair): + """Tuple of remote metadata and no path.""" + + metadata: RemoteToSMetadata + path: None = None + remote: None = None + + +class LocalPair(_MetadataPathPair): + """Tuple of local metadata and path.""" + + metadata: LocalToSMetadata + path: Path diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/path.py b/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/path.py new file mode 100644 index 0000000000000000000000000000000000000000..6e7c346ea850a6162de1d84d7c07ee25497cd01d --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/path.py @@ -0,0 +1,140 @@ +# Copyright (C) 2024 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Low-level path helpers.""" + +from __future__ import annotations + +import hashlib +import os +from functools import cache +from pathlib import Path +from typing import TYPE_CHECKING + +from conda.common.compat import on_win +from conda.common.configuration import custom_expandvars +from conda.models.channel import Channel +from platformdirs import user_cache_dir + +from . import APP_NAME + +if TYPE_CHECKING: + from collections.abc import Iterable, Iterator + from datetime import datetime + from typing import Final + +#: Site metadata directory. This is the highest priority location. +SITE_TOS_ROOT: Final = "C:/ProgramData/conda/tos" if on_win else "/etc/conda/tos" + +#: System metadata directory. Located in the conda installation. +SYSTEM_TOS_ROOT: Final = "$CONDA_ROOT/conda-meta/tos" + +#: User metadata directory. Located in the user home directory. +USER_TOS_ROOT: Final = "~/.conda/tos" + +#: Environment metadata directory. Located in the current conda environment. +ENV_TOS_ROOT: Final = "$CONDA_PREFIX/conda-meta/tos" + +#: Search path for metadata directories. +SEARCH_PATH: Final = tuple( + filter( + None, + ( + SITE_TOS_ROOT, + "/var/lib/conda/tos" if not on_win else None, + SYSTEM_TOS_ROOT, + "$XDG_CONFIG_HOME/conda/tos", + "~/.config/conda/tos", + USER_TOS_ROOT, + ENV_TOS_ROOT, + # mirrors $CONDARC + "$CONDATOS", + ), + ), +) + +#: Metadata file glob pattern. +TOS_GLOB: Final = "*.json" + +#: OS and user specific metadata cache directory. +CACHE_DIR: Final = Path(user_cache_dir(APP_NAME, appauthor=APP_NAME)) + + +@cache +def hash_channel(channel: str | Channel) -> str: + """Hash the channel to remove problematic characters (e.g. /).""" + channel = Channel(channel) + if not channel.base_url: + raise ValueError( + "`channel` must have a base URL. " + "(hint: `conda.models.channel.MultiChannel` cannot be hashed)" + ) + + hasher = hashlib.new("sha256") + hasher.update(channel.channel_location.encode("utf-8")) + hasher.update(channel.channel_name.encode("utf-8")) + return hasher.hexdigest() + + +def get_path(path: str | os.PathLike[str] | Path) -> Path: + """Expand environment variables and user home in the path.""" + if isinstance(path, str): + path = custom_expandvars(path, os.environ) + elif not isinstance(path, Path): + raise TypeError("`path` must be a string or `pathlib.Path`.") + return Path(path).expanduser() + + +def get_search_path( + extend_search_path: Iterable[str | os.PathLike[str] | Path] | None = None, +) -> Iterator[Path]: + """Get all root metadata paths ordered from highest to lowest priority.""" + seen: set[Path] = set() + for tos_root in (*SEARCH_PATH, *(extend_search_path or ())): + if (path := get_path(tos_root)).is_dir() and path not in seen: + yield path + seen.add(path) + + +def get_tos_dir( + tos_root: str | os.PathLike[str] | Path, + channel: str | Channel, +) -> Path: + """Get the metadata directory for the given channel.""" + return get_path(tos_root) / hash_channel(channel) + + +def get_metadata_path( + tos_root: str | os.PathLike[str] | Path, + channel: str | Channel, + version: datetime, +) -> Path: + """Get the metadata file path for the given channel and version.""" + return get_tos_dir(tos_root, channel) / f"{version.timestamp()}.json" + + +def get_all_channel_paths( + extend_search_path: Iterable[str | os.PathLike[str] | Path] | None = None, +) -> Iterator[Path]: + """Get all local metadata file paths.""" + for path in get_search_path(extend_search_path): + yield from sorted(get_path(path).glob(f"*/{TOS_GLOB}")) + + +def get_channel_paths( + channel: str | Channel, + *, + extend_search_path: Iterable[str | os.PathLike[str] | Path] | None = None, +) -> Iterator[Path]: + """Get all local metadata file paths for the given channel.""" + for path in get_search_path(extend_search_path): + yield from sorted(get_tos_dir(path, channel).glob(TOS_GLOB)) + + +def get_cache_path(channel: str | Channel) -> Path: + """Get the metadata cache file path for the given channel.""" + return CACHE_DIR / f"{hash_channel(channel)}.cache" + + +def get_cache_paths() -> Iterator[Path]: + """Get all local metadata cache file paths.""" + yield from sorted(CACHE_DIR.glob("*.cache")) diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/plugin.py b/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/plugin.py new file mode 100644 index 0000000000000000000000000000000000000000..6c81d1cb42a4bdca3152f190f379eb28540ce6f8 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/plugin.py @@ -0,0 +1,411 @@ +# Copyright (C) 2024 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""High-level conda plugin registration.""" + +from __future__ import annotations + +from datetime import timedelta +from functools import cache +from typing import TYPE_CHECKING + +from conda.base.context import context +from conda.cli.helpers import add_parser_prefix, add_parser_verbose +from conda.common.configuration import PrimitiveParameter +from conda.common.constants import NULL +from conda.plugins import ( + CondaPreCommand, + CondaRequestHeader, + CondaSetting, + CondaSubcommand, + hookimpl, +) +from rich.console import Console + +from . import APP_NAME, APP_VERSION +from .api import CI, get_channels +from .console import ( + noop_printer, + render_accept, + render_clean, + render_info, + render_interactive, + render_list, + render_reject, + render_view, +) +from .exceptions import CondaToSMissingError +from .local import get_local_metadata +from .path import ENV_TOS_ROOT, SITE_TOS_ROOT, SYSTEM_TOS_ROOT, USER_TOS_ROOT +from .remote import ENDPOINT + +if TYPE_CHECKING: + from argparse import ArgumentParser, Namespace + from collections.abc import Iterator + from typing import Callable + + +#: Default metadata storage location. +DEFAULT_TOS_ROOT = USER_TOS_ROOT + +#: Default cache timeout in seconds. +DEFAULT_CACHE_TIMEOUT = timedelta(hours=1).total_seconds() + +#: Field separator for request header +FIELD_SEPARATOR = ";" + +#: Key-value separator for request header +KEY_SEPARATOR = "=" + +#: Terms of Service acceptance request header +TOS_ACCEPT_HEADER = "Anaconda-ToS-Accept" + +#: Hosts to which the Terms of Service header is added +HOSTS = {"repo.anaconda.com"} + + +def _add_channel(parser: ArgumentParser) -> None: + channel_group = parser.add_argument_group("Channel Customization") + channel_group.add_argument( + "-c", + "--channel", + action="append", + help="Additional channels to search for Terms of Service.", + ) + channel_group.add_argument( + "--override-channels", + action="store_true", + help="Do not search default or .condarc channels. Requires --channel.", + ) + + +def _add_location(parser: ArgumentParser) -> None: + location_group = parser.add_argument_group("Local Metadata Storage Location") + location_mutex = location_group.add_mutually_exclusive_group() + for flag, value, text in ( + ("--site", SITE_TOS_ROOT, "System-wide storage location."), + ("--system", SYSTEM_TOS_ROOT, "Conda installation storage location."), + ("--user", USER_TOS_ROOT, "User storage location."), + ("--env", ENV_TOS_ROOT, "Conda environment storage location."), + ): + location_mutex.add_argument( + flag, + dest="tos_root", + action="store_const", + const=value, + help=text, + ) + location_mutex.add_argument( + "--tos-root", + action="store", + help="Custom storage location.", + ) + parser.set_defaults(tos_root=DEFAULT_TOS_ROOT) + + +def _add_cache(parser: ArgumentParser) -> None: + cache_group = parser.add_argument_group("Cache Control") + cache_mutex = cache_group.add_mutually_exclusive_group() + cache_mutex.add_argument( + "--cache-timeout", + action="store", + type=int, + help="Cache timeout (in seconds) to check for Terms of Service updates.", + ) + cache_mutex.add_argument( + "--ignore-cache", + dest="cache_timeout", + action="store_const", + const=0, + help="Ignore the cache and always check for Terms of Service updates.", + ) + parser.set_defaults(cache_timeout=DEFAULT_CACHE_TIMEOUT) + + +def _add_json(parser: ArgumentParser) -> None: + # TODO: replace with conda.cli.helpers.add_parser_json + parser.add_argument( + "--json", + action="store_true", + default=NULL, + help="Report all output as json. Suitable for using conda programmatically.", + ) + + +def configure_parser(parser: ArgumentParser) -> None: + """Configure the parser for the `tos` subcommand.""" + # conda tos --version + parser.add_argument( + "-V", + "--version", + action="version", + version=f"{APP_NAME} {APP_VERSION}", + help=f"Show the {APP_NAME} version number and exit.", + ) + + # conda tos (default behavior) + _add_channel(parser) + add_parser_prefix(parser) + _add_cache(parser) + _add_json(parser) + add_parser_verbose(parser) + parser.set_defaults(tos_root=DEFAULT_TOS_ROOT) + + # conda tos + subparsers = parser.add_subparsers( + title="subcommand", + description="The following subcommands are available.", + dest="cmd", + required=False, + ) + + # conda tos accept + accept_parser = subparsers.add_parser( + "accept", + help=( + "Accept the Terms of Service for all active channels " + "(default, .condarc, and/or those specified via --channel)." + ), + ) + _add_channel(accept_parser) + add_parser_prefix(accept_parser) + _add_location(accept_parser) + _add_cache(accept_parser) + _add_json(accept_parser) + + # conda tos reject + reject_parser = subparsers.add_parser( + "reject", + help=( + "Reject the Terms of Service for all active channels " + "(default, .condarc, and/or those specified via --channel)." + ), + ) + _add_channel(reject_parser) + add_parser_prefix(reject_parser) + _add_location(reject_parser) + _add_cache(reject_parser) + _add_json(reject_parser) + + # conda tos view + view_parser = subparsers.add_parser( + "view", + help=( + "View the Terms of Service for all active channels " + "(default, .condarc, and/or those specified via --channel)." + ), + ) + _add_channel(view_parser) + add_parser_prefix(view_parser) + _add_location(view_parser) + _add_cache(view_parser) + _add_json(view_parser) + + # conda tos interactive + interactive_parser = subparsers.add_parser( + "interactive", + help=( + "Interactively accept/reject/view Terms of Service for all active channels " + "(default, .condarc, and/or those specified via --channel)." + ), + ) + _add_channel(interactive_parser) + add_parser_prefix(interactive_parser) + _add_location(interactive_parser) + _add_cache(interactive_parser) + _add_json(interactive_parser) + add_parser_verbose(interactive_parser) + + # conda tos info + info_parser = subparsers.add_parser( + "info", + help=( + "Display information about the plugin " + "(e.g., search path and cache directory)." + ), + ) + _add_json(info_parser) + + # conda tos clean + clean_parser = subparsers.add_parser( + "clean", + help="Clean the cache directories.", + ) + clean_parser.add_argument( + "--cache", + action="store_true", + help="Remove all cache files.", + ) + clean_parser.add_argument( + "--tos", + action="store_true", + help="Remove all acceptances/rejections.", + ) + clean_parser.add_argument( + "--all", + action="store_true", + help="Invoke both `--cache` and `--tos`.", + ) + _add_json(clean_parser) + + +def execute(args: Namespace) -> int: + """Execute the `tos` subcommand.""" + try: + # FUTURE: update once we only support conda 25.5+ + from conda.core.prefix_data import PrefixData + + PrefixData(context.target_prefix).assert_exists() + except AttributeError: + # AttributeError: PrefixData.assert_exists isn't defined + from pathlib import Path + + from conda.exceptions import EnvironmentLocationNotFound + + if not (prefix := Path(context.target_prefix).exists()): + raise EnvironmentLocationNotFound(prefix) from None + + console = Console() + action: Callable + kwargs = {} + if args.cmd == "accept": + action = render_accept + elif args.cmd == "reject": + action = render_reject + elif args.cmd == "view": + action = render_view + elif args.cmd == "interactive": + action = render_interactive + kwargs["auto_accept_tos"] = context.plugins.auto_accept_tos + kwargs["always_yes"] = context.always_yes + kwargs["verbose"] = context.verbose + elif args.cmd == "info": + # refactor into `conda info` plugin (when possible) + return render_info(json=context.json, console=console) + elif args.cmd == "clean": + # refactor into `conda clean` plugin (when possible) + return render_clean( + cache=args.cache, + tos=args.tos, + all=args.all, + tos_root=args.tos_root, + json=context.json, + console=console, + ) + else: + # default + action = render_list + kwargs["verbose"] = context.verbose + + return action( + *context.channels, + tos_root=args.tos_root, + cache_timeout=args.cache_timeout, + json=context.json, + console=console, + **kwargs, + ) + + +@hookimpl +def conda_subcommands() -> Iterator[CondaSubcommand]: + """Return a list of subcommands for the plugin.""" + yield CondaSubcommand( + name="tos", + action=execute, + summary=( + "A subcommand for viewing, accepting, rejecting, and otherwise interacting " + "with a channel's Terms of Service (ToS). This plugin periodically checks " + "for updated Terms of Service for the active/selected channels. " + "Channels with a Terms of Service will need to be accepted or rejected " + "prior to use. Conda will only allow package installation from channels " + "without a Terms of Service or with an accepted Terms of Service. " + "Attempting to use a channel with a rejected Terms of Service will result " + "in an error." + ), + configure_parser=configure_parser, + ) + + +@hookimpl +def conda_settings() -> Iterator[CondaSetting]: + """Return a list of settings for the plugin.""" + yield CondaSetting( + name="auto_accept_tos", + description="Automatically accept Terms of Service (ToS) for all channels.", + parameter=PrimitiveParameter(False, element_type=bool), + ) + + +def _pre_command_check_tos(_command: str) -> None: + render_interactive( + *context.channels, + tos_root=DEFAULT_TOS_ROOT, + cache_timeout=DEFAULT_CACHE_TIMEOUT, + json=context.json, + verbose=context.verbose, + auto_accept_tos=context.plugins.auto_accept_tos, + always_yes=context.always_yes, + json_printer=noop_printer, # no JSON output even if --json + ) + + +@hookimpl(tryfirst=True) +def conda_pre_commands() -> Iterator[CondaPreCommand]: + """Return a list of pre-commands for the plugin.""" + yield CondaPreCommand( + name="check_tos", + action=_pre_command_check_tos, + run_for={ + "create", + "env_create", + "env_remove", + "env_update", + "install", + "remove", + "rename", + "search", + "update", + }, + ) + + +@cache +def _get_tos_acceptance_header() -> str: + values = [] + for channel in get_channels(*context.channels): + try: + local_pair = get_local_metadata( + channel, + extend_search_path=[DEFAULT_TOS_ROOT], + ) + except CondaToSMissingError: + pass + else: + values.append( + KEY_SEPARATOR.join( + ( + channel.base_url, + str(int(local_pair.metadata.version.timestamp())), + "accepted" if local_pair.metadata.tos_accepted else "rejected", + str(int(local_pair.metadata.acceptance_timestamp.timestamp())), + ) + ) + ) + if CI: + values.append("CI=true") + return FIELD_SEPARATOR.join(values) + + +@hookimpl +def conda_request_headers(host: str, path: str) -> Iterator[CondaRequestHeader]: + """Return a list of request headers for the plugin.""" + if ( + # only add the header to anaconda.com endpoints + host in HOSTS + # only add the Terms of Service header for non-Terms of Service endpoints + and not path.endswith(f"/{ENDPOINT}") + ): + yield CondaRequestHeader( + name=TOS_ACCEPT_HEADER, + value=_get_tos_acceptance_header(), + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/py.typed b/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/remote.py b/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/remote.py new file mode 100644 index 0000000000000000000000000000000000000000..a0b183813b31f8e0fa35840947ac6d83db323839 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/remote.py @@ -0,0 +1,179 @@ +# Copyright (C) 2024 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Low-level remote (the "raw" endpoint JSON) Terms of Service metadata management.""" + +from __future__ import annotations + +from datetime import datetime +from json import JSONDecodeError +from typing import TYPE_CHECKING + +from conda.base.context import context +from conda.common.url import join_url +from conda.gateways.connection.session import get_session +from conda.models.channel import Channel +from pydantic import ValidationError +from requests.exceptions import RequestException + +from .exceptions import ( + CondaToSInvalidError, + CondaToSMissingError, + CondaToSPermissionError, +) +from .models import RemoteToSMetadata +from .path import get_cache_path + +if TYPE_CHECKING: + from pathlib import Path + from typing import Final + + from requests import Response + +ENDPOINT: Final = "terms.json" + + +def get_endpoint(channel: str | Channel) -> Response: + """Get the metadata endpoint for the given channel.""" + channel = Channel(channel) + if not channel.base_url: + raise ValueError( + "`channel` must have a base URL. " + "(hint: `conda.models.channel.MultiChannel` doesn't have an endpoint)" + ) + + session = get_session(channel.base_url) + url = join_url(channel.base_url, ENDPOINT) + + saved_token_setting = context.add_anaconda_token + try: + # do not inject conda/binstar token into URL for two reasons: + # 1. Metadata endpoint shouldn't be a protected endpoint + # 2. CondaHttpAuth.add_binstar_token adds subdir to the URL + # which the metadata endpoint doesn't have + context.add_anaconda_token = False + response = session.get( + url, + headers={"Content-Type": "application/json"}, + timeout=( + context.remote_connect_timeout_secs, + context.remote_read_timeout_secs, + ), + ) + response.raise_for_status() + except RequestException as exc: + # RequestException: failed to get metadata endpoint + raise CondaToSMissingError(channel) from exc + finally: + context.add_anaconda_token = saved_token_setting + return response + + +def get_cached_endpoint( + channel: str | Channel, + *, + cache_timeout: int | float | None = float("inf"), +) -> Path | None: + """Get the path to cached payload for the given channel.""" + # early exit if cache is disabled + if not cache_timeout: + return None + + # argument validation/coercion + path = get_cache_path(channel) + if not isinstance(cache_timeout, (int, float)): + raise TypeError("`cache_timeout` must be an integer, float, or falsy.") + + # get mtime of cache + try: + mtime = path.stat().st_mtime + except FileNotFoundError: + # FileNotFoundError: cache path doesn't exist + return None + + # check if cache is stale + now = datetime.now().timestamp() # noqa: DTZ005 + if (now - mtime) >= cache_timeout: + return None + return path + + +def write_cached_endpoint( + channel: str | Channel, + metadata: RemoteToSMetadata | None, +) -> Path: + """Write the metadata cache for the given channel.""" + # argument validation/coercion + path = get_cache_path(channel) + if metadata and not isinstance(metadata, RemoteToSMetadata): + raise TypeError("`metadata` must be a RemoteToSMetadata.") + + # write to cache + try: + path.parent.mkdir(parents=True, exist_ok=True) + if metadata: + path.write_text(metadata.model_dump_json()) + else: + path.touch() + except PermissionError as exc: + # PermissionError: can't write to cache path + raise CondaToSPermissionError(path, channel) from exc + + return path + + +def get_remote_metadata( # noqa: C901 + channel: str | Channel, + *, + cache_timeout: int | float | None = None, +) -> RemoteToSMetadata: + """Get the metadata metadata for the given channel.""" + # argument validation/coercion + cache = get_cached_endpoint( + channel, + # when in offline mode cache_timeout is ignored + cache_timeout=float("inf") if context.offline else cache_timeout, + ) + + # return cached metadata + if cache: + try: + text = cache.read_text().strip() + if not text: + raise CondaToSMissingError(channel) + except FileNotFoundError as exc: + # FileNotFoundError: cache path doesn't exist + raise CondaToSMissingError(channel) from exc + except PermissionError as exc: + # PermissionError: can't read cache path + raise CondaToSPermissionError(cache, channel) from exc + + try: + return RemoteToSMetadata.model_validate_json(text) + except ValidationError as exc: + # ValidationError: invalid JSON schema + raise CondaToSInvalidError(channel) from exc + + # return remote metadata + try: + metadata = RemoteToSMetadata(**get_endpoint(channel).json()) + except CondaToSMissingError: + # CondaToSMissingError: no Terms of Service for this channel + # create an empty cache to prevent repeated requests + write_cached_endpoint(channel, None) + raise + except RuntimeError as exc: + # RuntimeError: potentially raised by CondaSession due to --offline + if "offline mode" in exc.args[0]: + write_cached_endpoint(channel, None) + raise CondaToSMissingError(channel) from exc + raise + except (AttributeError, TypeError, JSONDecodeError, ValidationError) as exc: + # AttributeError: response has no JSON + # TypeError: invalid JSON + # JSONDecodeError: invalid JSON + # ValidationError: invalid JSON schema + write_cached_endpoint(channel, None) + raise CondaToSInvalidError(channel) from exc + else: + write_cached_endpoint(channel, metadata) + return metadata diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/INSTALLER b/data/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..f79e4cb9aaf0b2d9e8ba78861e2071317b2384b3 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/INSTALLER @@ -0,0 +1 @@ +conda \ No newline at end of file diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/METADATA b/data/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..94a84fe1b86a82ccb244d48f95f8e8ecd5d84ba3 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/METADATA @@ -0,0 +1,120 @@ +Metadata-Version: 2.3 +Name: conda-content-trust +Version: 0.2.0 +Summary: Signing and verification tools, geared toward the conda ecosystem. +Project-URL: repository, https://github.com/conda/conda-content-trust +Project-URL: changelog, https://github.com/conda/conda-content-trust/blob/main/CHANGELOG.md +Author-email: "Anaconda, Inc." +License: BSD License + + Copyright (c) 2019, Anaconda, Inc. + All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, + are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright notice, this + list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + + * Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from this + software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + OF THE POSSIBILITY OF SUCH DAMAGE. +License-File: AUTHORS.md +License-File: LICENSE +Keywords: authentication,compromise,conda,conda-authentication-resources,conda-content-trust,key,secure,signing,verify +Classifier: Development Status :: 4 - Beta +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Requires-Python: >=3.8 +Requires-Dist: cryptography>=41 +Provides-Extra: gpgsigning +Requires-Dist: securesystemslib==0.13.1; extra == 'gpgsigning' +Description-Content-Type: text/markdown + +[ci-tests-badge]: https://github.com/conda/conda-content-trust/actions/workflows/tests.yml/badge.svg +[codecov-badge]: https://img.shields.io/codecov/c/github/conda/conda-content-trust/main.svg?label=coverage +[release-badge]: https://img.shields.io/github/release/conda/conda-content-trust.svg + +# Conda Content Trust: Signing and verification tools for Conda + +[![Tests (GitHub Actions)][ci-tests-badge]](https://github.com/conda/conda-content-trust/actions/workflows/tests.yml) +[![Codecov Status][codecov-badge]](https://codecov.io/gh/conda/conda-content-trust/branch/main) +[![latest release version][release-badge]](https://github.com/conda/conda-content-trust/releases) + +*What:* Based on [The Update Framework (TUF)](https://theupdateframework.io/), conda-content-trust is intended to ensure that when users in the conda ecosystem obtain a package or data about that package, they can know whether or not it is trustworthy (e.g. originally comes from a reliable source and has not been tampered with). A basic library and basic CLI are included to provide signing, verification, and trust delegation functionality. + +*Why:* This exists as an alteration of TUF because of the very particular needs of the conda ecosystem. (Developers are encouraged to *just use TUF* whenever possible!) + +*Where:* This tool is general purpose. It is currently used in conda 4.10.1+ to verify package metadata signatures when they are available ([announcement](https://www.anaconda.com/blog/conda-signature-verification), [instructions](https://docs.anaconda.com/anaconda-commercial/security)). + +## Installation + +Installation can be accomplished via conda: + +``` +conda install conda-content-trust +``` + +Or via pip: + +``` +pip install conda-content-trust +``` + +(If you intend to tinker with the code, feel free to use an editable install: `pip install -e .`) + +### Optional Dependencies for Producing Signatures with GPG Keys / YubiKeys + +If you intend to *create* *GPG* key signatures (as opposed to the typical non-GPG signatures), and/or you intend to use the YubiKey interface, you will need to install two optional dependencies: + +- `GPG` (any gpg client that provides command-line gpg functionality should do) +- `securesystemslib` (`pip install securesystemslib`) + +## Demonstration and Use + +Use of the command-line utility provides help functionality:: + +``` +conda-content-trust --help +``` + +You should be able to run the demo after installing: + +``` +python3 demo.py +``` + +(Portions of the demo may require the optional dependencies above.) + + +## Testing + +Each set of tests is a module in the `tests/` directory. These can all be run with: + +``` +pytest +``` diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/RECORD b/data/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..f50d62ca90856561e9d9ca6cd7dd1f59504a58ab --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/RECORD @@ -0,0 +1,30 @@ +../../../bin/conda-content-trust,sha256=OfC4-yB1uYgSaGN2jMKM2Ple0ZiyrRxG4THIjwPfgIU,503 +conda_content_trust-0.2.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +conda_content_trust-0.2.0.dist-info/METADATA,sha256=eo811VHSYxFaTR77I-T4HdmhWItjO4DDBF_EVr4Yq18,5708 +conda_content_trust-0.2.0.dist-info/RECORD,, +conda_content_trust-0.2.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +conda_content_trust-0.2.0.dist-info/WHEEL,sha256=1yFddiXMmvYK7QYTqtRNtX66WJ0Mz8PYEiEUoOUUxRY,87 +conda_content_trust-0.2.0.dist-info/direct_url.json,sha256=C1jzrre-6wpDEHARV_LvNb0k-oLn2D1CpxsogJF0Y7M,113 +conda_content_trust-0.2.0.dist-info/entry_points.txt,sha256=8kIfTSV2muIUqQV0jZzZU-XWcLOhJebM1VmiODqvSYA,126 +conda_content_trust-0.2.0.dist-info/licenses/AUTHORS.md,sha256=M67rb4QLM9565Na6CHZnKeljEOtcozVchaRP011OG_0,281 +conda_content_trust-0.2.0.dist-info/licenses/LICENSE,sha256=Cd-oJyYTQWtOISHqn9-XCaJeGr8UTkwXyBqXWm_Xcck,1505 +conda_content_trust/__init__.py,sha256=EVu6odFu6gXZj7TD4O2hc9Lc8zkOH_VgOlp2BxvI1eU,126 +conda_content_trust/__main__.py,sha256=2913q-WtZP4QWmmL4HVY6oMURX1oOXvNzXwbpKzC4HA,122 +conda_content_trust/__pycache__/__init__.cpython-313.pyc,, +conda_content_trust/__pycache__/__main__.cpython-313.pyc,, +conda_content_trust/__pycache__/__version__.cpython-313.pyc,, +conda_content_trust/__pycache__/authentication.cpython-313.pyc,, +conda_content_trust/__pycache__/cli.cpython-313.pyc,, +conda_content_trust/__pycache__/common.cpython-313.pyc,, +conda_content_trust/__pycache__/metadata_construction.cpython-313.pyc,, +conda_content_trust/__pycache__/plugin.cpython-313.pyc,, +conda_content_trust/__pycache__/root_signing.cpython-313.pyc,, +conda_content_trust/__pycache__/signing.cpython-313.pyc,, +conda_content_trust/__version__.py,sha256=H-qsvrxCpdhaQzyddR-yajEqI71hPxLa4KxzpP3uS1g,411 +conda_content_trust/authentication.py,sha256=uZD63uParw7Yl41gkxh6IBBgqbH3WOaheQt8xFgfwQE,22695 +conda_content_trust/cli.py,sha256=XG_yINHDWkEeMihUa3Ewxpgoqxse-clkeOmlFEtlzgk,18553 +conda_content_trust/common.py,sha256=w23tDH1DmGcNbO6HVe1daV1tAsEfu92MShlv8SYwd4M,33377 +conda_content_trust/metadata_construction.py,sha256=nlo9NmnyU3MVoGeDXidG0Q6sIw6R4T0JhVbWhjxztH4,10325 +conda_content_trust/plugin.py,sha256=VrFwespayVyRwMPVWxVM4w7DjZ8XUOgR5Ygehnq9k9M,326 +conda_content_trust/root_signing.py,sha256=fwLOo8I8H_nnLtJVLZ3wBrrau_yWT2KAnBPVTOXDKFs,15395 +conda_content_trust/signing.py,sha256=Z23g2W_1WrRLCpKpKbF_YeC3HzclARp5HdvIclrNLKY,8741 diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/REQUESTED b/data/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/WHEEL b/data/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..cdd68a497cdfa8d3f2b837225beacef711b85047 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.25.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/direct_url.json b/data/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..22024d4be5282cde1594db2afe7e8b0f824e221f --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/direct_url.json @@ -0,0 +1 @@ +{"dir_info": {}, "url": "file:///work/perseverance-python-buildout/croot/conda-content-trust_1728487058234/work"} \ No newline at end of file diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/entry_points.txt b/data/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..b26481e6a0ae7224837e33038a4ddb0dfac3af7d --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/entry_points.txt @@ -0,0 +1,5 @@ +[console_scripts] +conda-content-trust = conda_content_trust.cli:cli + +[conda] +conda-content-trust = conda_content_trust.plugin diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_package_handling/__init__.py b/data/miniconda3/lib/python3.13/site-packages/conda_package_handling/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3d67cd6bb497cf0c862b60ff30e8b273aae5d851 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda_package_handling/__init__.py @@ -0,0 +1 @@ +__version__ = "2.4.0" diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_package_handling/__main__.py b/data/miniconda3/lib/python3.13/site-packages/conda_package_handling/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..dde91ff0efe062c13395035b31d275e499d967de --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda_package_handling/__main__.py @@ -0,0 +1,3 @@ +from conda_package_handling import cli + +cli.main(args=None) diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_package_handling/api.py b/data/miniconda3/lib/python3.13/site-packages/conda_package_handling/api.py new file mode 100644 index 0000000000000000000000000000000000000000..47881ce4a1330e1011fc7c241114a77985094034 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda_package_handling/api.py @@ -0,0 +1,236 @@ +from __future__ import annotations + +import functools as _functools +import os as _os +import warnings as _warnings +from glob import glob as _glob + +# expose these two exceptions as part of the API. Everything else should feed into these. +from .exceptions import ConversionError, InvalidArchiveError # NOQA +from .interface import AbstractBaseFormat +from .tarball import CondaTarBZ2 as _CondaTarBZ2 +from .utils import ensure_list, filter_info_files +from .utils import get_executor as _get_executor +from .utils import rm_rf as _rm_rf + +SUPPORTED_EXTENSIONS: dict[str, type[AbstractBaseFormat]] = {".tar.bz2": _CondaTarBZ2} + +libarchive_enabled = False #: Old API meaning "can extract .conda" (now without libarchive) + +try: + from .conda_fmt import ZSTD_COMPRESS_LEVEL, ZSTD_COMPRESS_THREADS + from .conda_fmt import CondaFormat_v2 as _CondaFormat_v2 + + SUPPORTED_EXTENSIONS[".conda"] = _CondaFormat_v2 + + libarchive_enabled = True + +except ImportError: + _warnings.warn("Install zstandard Python bindings for .conda support") + +THREADSAFE_EXTRACT = True #: Not present in conda-package-handling<2.0. + + +def _collect_paths(prefix): + dir_paths, file_paths = [], [] + for dp, dn, filenames in _os.walk(prefix): + for f in filenames: + file_paths.append(_os.path.relpath(_os.path.join(dp, f), prefix)) + dir_paths.extend(_os.path.relpath(_os.path.join(dp, _), prefix) for _ in dn) + file_list = file_paths + [ + dp for dp in dir_paths if not any(f.startswith(dp + _os.sep) for f in file_paths) + ] + return file_list + + +def get_default_extracted_folder(in_file, abspath=True): + dirname = None + for ext in SUPPORTED_EXTENSIONS: + if in_file.endswith(ext): + dirname = in_file[: -len(ext)] + if dirname and not abspath: + dirname = _os.path.basename(dirname) + return dirname + + +def extract(fn, dest_dir=None, components=None, prefix=None): + if dest_dir: + if _os.path.isabs(dest_dir) and prefix: + raise ValueError( + "dest_dir and prefix both provided as abs paths. If providing both, " + "prefix can be abspath, but dest dir must be relative (relative to " + "prefix)" + ) + if not _os.path.isabs(dest_dir): + dest_dir = _os.path.normpath(_os.path.join(prefix or _os.getcwd(), dest_dir)) + else: + dest_dir = _os.path.join( + prefix or _os.path.dirname(fn), + get_default_extracted_folder(fn, abspath=False), + ) + + if not _os.path.isdir(dest_dir): + _os.makedirs(dest_dir) + + for format in SUPPORTED_EXTENSIONS.values(): + if format.supported(fn): + format.extract(fn, dest_dir, components=components) + break + else: + raise ValueError( + "Didn't recognize extension for file '{}'. Supported extensions are: {}".format( + fn, list(SUPPORTED_EXTENSIONS.keys()) + ) + ) + + +def create(prefix, file_list, out_fn, out_folder=None, **kw): + if not out_folder: + out_folder = _os.getcwd() + + # simplify arguments to format.create() + if _os.path.isabs(out_fn): + out_folder = _os.path.dirname(out_fn) + out_fn = _os.path.basename(out_fn) + + if file_list is None: + file_list = _collect_paths(prefix) + elif isinstance(file_list, str): + try: + with open(file_list) as f: + data = f.readlines() + file_list = [_.strip() for _ in data] + except: + raise + + out = None + for format in SUPPORTED_EXTENSIONS.values(): + if format.supported(out_fn): + try: + out = format.create(prefix, file_list, out_fn, out_folder, **kw) + break + except BaseException as err: + # don't leave broken files around + abs_out_fn = _os.path.join(out_folder, out_fn) + if _os.path.isfile(abs_out_fn): + _rm_rf(abs_out_fn) + raise err + else: + raise ValueError( + "Didn't recognize extension for file '{}'. Supported extensions are: {}".format( + out_fn, list(SUPPORTED_EXTENSIONS.keys()) + ) + ) + + return out + + +def _convert( + fn, + out_ext, + out_folder, + force=False, + zstd_compress_level=None, + zstd_compress_threads=None, + **kw, +): + # allow package to work in degraded mode when zstandard is not available + import conda_package_streaming.transmute + import zstandard + + basename = get_default_extracted_folder(fn, abspath=False) + from .validate import validate_converted_files_match_streaming + + if not basename: + return ( + fn, + "", + "Input file %s doesn't have a supported extension (%s), skipping it" + % (fn, SUPPORTED_EXTENSIONS), + ) + out_fn = str(_os.path.join(out_folder, basename + out_ext)) + errors = "" + if not _os.path.lexists(out_fn) or force: + if force and _os.path.lexists(out_fn): + _os.unlink(out_fn) + + if out_ext == ".conda": + # ZSTD_COMPRESS_* constants are only defined if we have zstandard + if zstd_compress_level is None: + zstd_compress_level = ZSTD_COMPRESS_LEVEL + if zstd_compress_threads is None: + zstd_compress_threads = ZSTD_COMPRESS_THREADS + + def compressor(): + return zstandard.ZstdCompressor( + level=zstd_compress_level, threads=zstd_compress_threads + ) + + def is_info(filename): + return filter_info_files([filename], prefix=".") == [] + + transmute = _functools.partial( + conda_package_streaming.transmute.transmute, + fn, + out_folder, + compressor=compressor, + is_info=is_info, + ) + + else: + transmute = _functools.partial( + conda_package_streaming.transmute.transmute_tar_bz2, fn, out_folder + ) + + try: + transmute() + result = validate_converted_files_match_streaming(out_fn, fn) + _, missing_files, mismatching_sizes = result + if missing_files or mismatching_sizes: + errors = str(ConversionError(missing_files, mismatching_sizes)) + except BaseException as e: + # don't leave partial package around + if _os.path.isfile(out_fn): + _rm_rf(out_fn) + if not isinstance(e, Exception): + raise + errors = str(e) + + return fn, out_fn, errors + + +def transmute(in_file, out_ext, out_folder=None, processes=1, **kw): + if not out_folder: + out_folder = _os.path.dirname(in_file) or _os.getcwd() + + flist = set(_glob(in_file)) + for in_ext in SUPPORTED_EXTENSIONS: + if in_file.endswith(in_ext): + replacement = in_file[: -len(in_ext)] + out_ext + flist = flist - set(_glob(replacement)) + break + + failed_files = {} + with _get_executor(processes) as executor: + convert_f = _functools.partial(_convert, out_ext=out_ext, out_folder=out_folder, **kw) + for fn, out_fn, errors in executor.map(convert_f, flist): + if errors: + failed_files[fn] = errors + _rm_rf(out_fn) + return failed_files + + +def get_pkg_details(in_file): + """For the new pkg format, we return the size and hashes of the inner pkg part of the file""" + for format in SUPPORTED_EXTENSIONS.values(): + if format.supported(in_file): + return format.get_pkg_details(in_file) + raise ValueError(f"Don't know what to do with file {in_file}") + + +def list_contents(in_file, verbose=False, components=None): + components = ensure_list(components or ("info", "pkg")) + for format in SUPPORTED_EXTENSIONS.values(): + if format.supported(in_file): + return format.list_contents(in_file, verbose=verbose, components=components) + raise ValueError(f"Don't know what to do with file {in_file}") diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_package_handling/cli.py b/data/miniconda3/lib/python3.13/site-packages/conda_package_handling/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..b1ed3733c53fb2b2ab9d163378a4bdc7b0d1d4f5 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda_package_handling/cli.py @@ -0,0 +1,165 @@ +import argparse +import os +import sys +from pprint import pprint + +from . import __version__, api + + +def parse_args(parse_this=None): + parser = build_parser() + return parser.parse_args(parse_this) + + +def build_parser(): + parser = argparse.ArgumentParser() + parser.add_argument( + "-V", + "--version", + action="version", + help="Show the conda-package-handling version number and exit.", + version=f"conda-package-handling {__version__}", + ) + sp = parser.add_subparsers(title="subcommands", dest="subcommand", required=True) + + extract_parser = sp.add_parser("extract", help="extract package contents", aliases=["x"]) + extract_parser.add_argument("archive_path", help="path to archive to extract") + extract_parser.add_argument( + "--dest", + help="destination folder to extract to. If not set, defaults to" + " package filename minus extension in the same folder as the input archive." + " May be relative path used in tandem with the --prefix flag.", + ) + extract_parser.add_argument( + "--prefix", + help="base directory to extract to. Use this to set the base" + " directory, while allowing the folder name to be automatically determined " + "by the input filename. An abspath --prefix with an unset --dest will " + "achieve this.", + ) + extract_parser.add_argument( + "--info", + help="If the archive supports separate metadata, this" + " flag extracts only the metadata in the info folder from the " + "package. If the archive does not support separate metadata, this " + "flag has no effect and all files are extracted.", + action="store_true", + ) + + create_parser = sp.add_parser("create", help="bundle files into a package", aliases=["c"]) + create_parser.add_argument( + "prefix", + help="folder of files to bundle. Not strictly required to" + " have conda package metadata, but if conda package metadata isn't " + "present, you'll see a warning and your file will not work as a " + "conda package", + ) + create_parser.add_argument( + "out_fn", + help="Filename of archive to be created. Extension determines package type.", + ) + create_parser.add_argument( + "--file-list", + help="Path to file containing one relative path per" + " line that should be included in the archive. If not provided, " + "lists all files in the prefix.", + ) + create_parser.add_argument("--out-folder", help="Folder to dump final archive to") + + convert_parser = sp.add_parser( + "transmute", help="convert from one package type to another", aliases=["t"] + ) + convert_parser.add_argument( + "in_file", help="existing file to convert from. Glob patterns accepted." + ) + convert_parser.add_argument( + "out_ext", + help="extension of file to convert to. Examples: .tar.bz2, .conda", + ) + convert_parser.add_argument("--out-folder", help="Folder to dump final archive to") + convert_parser.add_argument( + "--force", action="store_true", help="Force overwrite existing package" + ) + convert_parser.add_argument( + "--processes", + type=int, + help="Max number of processes to use. If not set, defaults to 1.", + ) + convert_parser.add_argument( + "--zstd-compression-level", + help=( + "When building v2 packages, set the compression level used by " + "conda-package-handling. Defaults to 19." + ), + type=int, + choices=range(1, 23), + default=19, + ) + convert_parser.add_argument( + "--zstd-compression-threads", + help=( + "When building v2 packages, set the compression threads used by " + "conda-package-handling. Defaults to 1. -1=automatic." + ), + type=int, + default=1, + ) + list_parser = sp.add_parser( + "list", + aliases=["l"], + help="List package contents like `python -m tarfile --list ...` would do.", + ) + list_parser.add_argument("archive_path", help="path or URL to archive to inspect") + list_parser.add_argument( + "-v", + "--verbose", + action="store_true", + help="Report more details, similar to 'ls -l'. Otherwise, only the filenames are printed.", + ) + list_parser.add_argument( + "--components", + dest="components", + default="info,pkg", + help="Comma-separated list of components to read (.conda artifacts only; " + "ignored for .tar.bz2). Allowed values: info, pkg.", + ) + + return parser + + +def main(args=None): + args = parse_args(args) + if hasattr(args, "out_folder") and args.out_folder: + args.out_folder = ( + os.path.abspath(os.path.normpath(os.path.expanduser(args.out_folder))) + os.sep + ) + if args.subcommand in ("extract", "x"): + if args.info: + api.extract(args.archive_path, args.dest, components="info", prefix=args.prefix) + else: + api.extract(args.archive_path, args.dest, prefix=args.prefix) + elif args.subcommand in ("create", "c"): + api.create(args.prefix, args.file_list, args.out_fn, args.out_folder) + elif args.subcommand in ("transmute", "t"): + failed_files = api.transmute( + args.in_file, + args.out_ext, + args.out_folder, + args.processes or 1, + force=args.force, + zstd_compress_level=args.zstd_compression_level, + zstd_compress_threads=args.zstd_compression_threads, + ) + if failed_files: + print("failed files:") + pprint(failed_files) + sys.exit(1) + elif args.subcommand in ("list", "l"): + components = [ + component.strip() for component in (args.components or "info,pkg").split(",") + ] + api.list_contents(args.archive_path, verbose=args.verbose, components=components) + + +if __name__ == "__main__": # pragma: no cover + main(args=None) diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_package_handling/conda_fmt.py b/data/miniconda3/lib/python3.13/site-packages/conda_package_handling/conda_fmt.py new file mode 100644 index 0000000000000000000000000000000000000000..c6c45cd37234c682db53e511ecd94bc8c909b089 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda_package_handling/conda_fmt.py @@ -0,0 +1,198 @@ +""" +The 'new' conda format, introduced in late 2018/early 2019. + +https://docs.conda.io/projects/conda/en/latest/user-guide/concepts/packages.html +""" + +from __future__ import annotations + +import json +import os +import stat +import tarfile +import time +from contextlib import closing +from typing import Callable +from zipfile import ZIP_STORED, ZipFile + +import zstandard +from conda_package_streaming.package_streaming import stream_conda_component +from conda_package_streaming.url import conda_reader_for_url + +from . import utils +from .interface import AbstractBaseFormat +from .streaming import _extract, _list + +CONDA_PACKAGE_FORMAT_VERSION = 2 +DEFAULT_COMPRESSION_TUPLE = (".tar.zst", "zstd", "zstd:compression-level=19") + +# increase to reduce speed and increase compression (22 = conda's default) +ZSTD_COMPRESS_LEVEL = 19 +# increase to reduce compression (slightly) and increase speed +ZSTD_COMPRESS_THREADS = 1 + + +class CondaFormat_v2(AbstractBaseFormat): + """If there's another conda format or breaking changes, please create a new class and keep this + one, so that handling of v2 stays working.""" + + @staticmethod + def supported(fn): + return fn.endswith(".conda") + + @staticmethod + def extract(fn, dest_dir, **kw): + components = utils.ensure_list(kw.get("components")) or ("info", "pkg") + if not os.path.isabs(fn): + fn = os.path.normpath(os.path.join(os.getcwd(), fn)) + if not os.path.isdir(dest_dir): + os.makedirs(dest_dir) + + _extract(str(fn), str(dest_dir), components=components) + + @staticmethod + def extract_info(fn, dest_dir=None): + return CondaFormat_v2.extract(fn, dest_dir, components=["info"]) + + @staticmethod + def create( + prefix, + file_list, + out_fn, + out_folder=None, + compressor: Callable[[], zstandard.ZstdCompressor] | None = None, + compression_tuple=(None, None, None), + ): + if out_folder is None: + out_folder = os.getcwd() + if os.path.isabs(out_fn): + out_folder = os.path.dirname(out_fn) + out_fn = os.path.basename(out_fn) + conda_pkg_fn = os.path.join(out_folder, out_fn) + file_id = out_fn[: -len(".conda")] + pkg_files = utils.filter_info_files(file_list, prefix) + # preserve order + pkg_files_set = set(pkg_files) + info_files = list(f for f in file_list if f not in pkg_files_set) + + if compressor and (compression_tuple != (None, None, None)): + raise ValueError("Supply one of compressor= or (deprecated) compression_tuple=") + + if compressor is None: + compressor = lambda: zstandard.ZstdCompressor( + level=ZSTD_COMPRESS_LEVEL, + threads=ZSTD_COMPRESS_THREADS, + ) + + # legacy libarchive-ish compatibility + ext, comp_filter, filter_opts = compression_tuple + if filter_opts and filter_opts.startswith("zstd:compression-level="): + compressor = lambda: zstandard.ZstdCompressor( + level=int(filter_opts.split("=", 1)[-1]), + threads=ZSTD_COMPRESS_THREADS, + ) + + class NullWriter: + """ + zstd uses less memory on extract if size is known. + """ + + def __init__(self): + self.size = 0 + + def write(self, bytes): + self.size += len(bytes) + return len(bytes) + + def tell(self): + return self.size + + with ZipFile(conda_pkg_fn, "w", compression=ZIP_STORED) as conda_file, utils.tmp_chdir( + prefix + ): + pkg_metadata = {"conda_pkg_format_version": CONDA_PACKAGE_FORMAT_VERSION} + conda_file.writestr("metadata.json", json.dumps(pkg_metadata)) + + components_files = ( + (f"pkg-{file_id}.tar.zst", pkg_files), + ( + f"info-{file_id}.tar.zst", + info_files, + ), + ) + + # put the info last, for parity with updated transmute. + compress = compressor() + for component, files in components_files: + # If size is known, the decompressor may be able to allocate less memory. + # The compressor will error if size is not correct. + with tarfile.TarFile(fileobj=NullWriter(), mode="w") as sizer: # type: ignore + for file in files: + sizer.add(file, filter=utils.anonymize_tarinfo) + size = sizer.fileobj.size # type: ignore + + with conda_file.open(component, "w", force_zip64=True) as component_file: + # only one stream_writer() per compressor() must be in use at a time + component_stream = compress.stream_writer( + component_file, size=size, closefd=False + ) + component_tar = tarfile.TarFile(fileobj=component_stream, mode="w") + + for file in files: + component_tar.add(file, filter=utils.anonymize_tarinfo) + + component_tar.close() + component_stream.close() + + return conda_pkg_fn + + @staticmethod + def get_pkg_details(in_file): + stat_result = os.stat(in_file) + size = stat_result.st_size + md5, sha256 = utils.checksums(in_file, ("md5", "sha256")) + return {"size": size, "md5": md5, "sha256": sha256} + + @classmethod + def list_contents(cls, fn, verbose=False, **kw): + components = utils.ensure_list(kw.get("components")) or ("info", "pkg") + if "://" in fn: + return cls._list_remote_contents(fn, components=components, verbose=verbose) + # local resource + if not os.path.isabs(fn): + fn = os.path.abspath(fn) + _list(fn, components=components, verbose=verbose) + + @staticmethod + def _list_remote_contents(url, verbose=False, components=("info", "pkg")): + """ + List contents of a remote .conda artifact (by URL). It only fetches the 'info' component + and uses the metadata to infer details of the 'pkg' component. Some fields like + modification time or permissions will be missing in verbose mode. + """ + components = utils.ensure_list(components or ("info", "pkg")) + lines = {} + filename, conda = conda_reader_for_url(url) + with closing(conda): + for tar, member in stream_conda_component(filename, conda, component="info"): + path = member.name + ("/" if member.isdir() else "") + if "info" in components: + line = "" + if verbose: + line = ( + f"{stat.filemode(member.mode)} " + f"{member.uname or member.uid}/{member.gname or member.gid} " + f"{member.size:10d} " + ) + line += "%d-%02d-%02d %02d:%02d:%02d " % time.localtime(member.mtime)[:6] + lines[path] = line + path + if "pkg" in components and member.name == "info/paths.json": + data = json.loads(tar.extractfile(member).read().decode()) + assert data.get("paths_version", 1) == 1, data + for path in data.get("paths", ()): + line = "" + if verbose: + size = path["size_in_bytes"] + line = f"?????????? ?/? {size:10d} ????-??-?? ??:??:?? " + lines[path["_path"]] = line + path["_path"] + print(*[line for _, line in sorted(lines.items())], sep="\n") diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_package_handling/exceptions.py b/data/miniconda3/lib/python3.13/site-packages/conda_package_handling/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..00e820c63b072448b432e258a34a1d8f73c80126 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda_package_handling/exceptions.py @@ -0,0 +1,53 @@ +from errno import ENOENT + + +class InvalidArchiveError(Exception): + """Raised when libarchive can't open a file""" + + def __init__(self, fn, msg, *args, **kw): + msg = ( + "Error with archive %s. You probably need to delete and re-download " + "or re-create this file. Message was:\n\n%s" % (fn, msg) + ) + self.errno = ENOENT + super().__init__(msg) + + +class ArchiveCreationError(Exception): + """Raised when an archive fails during creation""" + + pass + + +class CaseInsensitiveFileSystemError(InvalidArchiveError): + def __init__(self, package_location, extract_location, **kwargs): + message = """ + Cannot extract package to a case-insensitive file system. Your install + destination does not differentiate between upper and lowercase + characters, and this breaks things. Try installing to a location that + is case-sensitive. Windows drives are usually the culprit here - can + you install to a native Unix drive, or turn on case sensitivity for + this (Windows) location? + + package location: %(package_location)s + extract location: %(extract_location)s + """ + self.package_location = package_location + self.extract_location = extract_location + super().__init__(package_location, message, **kwargs) + + +class ConversionError(Exception): + def __init__(self, missing_files, mismatching_sizes, *args, **kw): + self.missing_files = missing_files + self.mismatching_sizes = mismatching_sizes + errors = "" + if self.missing_files: + errors = "Missing files in converted package: %s\n" % self.missing_files + errors = ( + errors + + "Mismatching sizes (corruption) in converted package: %s" # noqa + % self.mismatching_sizes + ) + + super().__init__(errors, *args, **kw) diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_package_handling/interface.py b/data/miniconda3/lib/python3.13/site-packages/conda_package_handling/interface.py new file mode 100644 index 0000000000000000000000000000000000000000..390cffdc77ed4fc668f0ebd070f641855f4f1447 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda_package_handling/interface.py @@ -0,0 +1,30 @@ +from __future__ import annotations + +import abc + + +class AbstractBaseFormat(metaclass=abc.ABCMeta): + @staticmethod + @abc.abstractmethod + def supported(fn): # pragma: no cover + return False + + @staticmethod + @abc.abstractmethod + def extract(fn, dest_dir, **kw): # pragma: no cover + raise NotImplementedError + + @staticmethod + @abc.abstractmethod + def create(prefix, file_list, out_fn, out_folder: str | None = None, **kw): # pragma: no cover + raise NotImplementedError + + @staticmethod + @abc.abstractmethod + def get_pkg_details(in_file): # pragma: no cover + raise NotImplementedError + + @staticmethod + @abc.abstractmethod + def list_contents(in_file, verbose=False, **kw): # pragma: no cover + raise NotImplementedError diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_package_handling/streaming.py b/data/miniconda3/lib/python3.13/site-packages/conda_package_handling/streaming.py new file mode 100644 index 0000000000000000000000000000000000000000..f05f981ae70e215ea89fdba9c1366b575284756c --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda_package_handling/streaming.py @@ -0,0 +1,82 @@ +""" +Exception-compatible adapter from conda_package_streaming. +""" + +from __future__ import annotations + +import io +import tarfile +from contextlib import redirect_stdout +from tarfile import TarError +from typing import Generator +from zipfile import BadZipFile + +from conda_package_streaming.extract import exceptions as cps_exceptions +from conda_package_streaming.extract import extract_stream, package_streaming + +from . import exceptions + + +def _stream_components( + filename: str, + components: list[str], + dest_dir: str = "", +) -> Generator[Generator[tuple[tarfile.TarFile, tarfile.TarInfo]]]: + if str(filename).endswith(".tar.bz2"): + assert components == ["pkg"] + + try: + with open(filename, "rb") as fileobj: + for component in components: + # will parse zipfile twice + yield package_streaming.stream_conda_component( + filename, fileobj, component=component + ) + except cps_exceptions.CaseInsensitiveFileSystemError as e: + raise exceptions.CaseInsensitiveFileSystemError(filename, dest_dir) from e + except (OSError, TarError, BadZipFile) as e: + raise exceptions.InvalidArchiveError(filename, f"failed with error: {str(e)}") from e + + +def _extract(filename: str, dest_dir: str, components: list[str]): + """ + Extract .conda or .tar.bz2 package to dest_dir. + + If it's a conda package, components may be ["pkg", "info"] + + If it's a .tar.bz2 package, components must equal ["pkg"] + + Internal. Skip directly to conda-package-streaming if you don't need + exception compatibility. + """ + for stream in _stream_components(filename, components, dest_dir=dest_dir): + try: + extract_stream(stream, dest_dir) + except cps_exceptions.CaseInsensitiveFileSystemError as e: + raise exceptions.CaseInsensitiveFileSystemError(filename, dest_dir) from e + except (OSError, TarError, BadZipFile) as e: + raise exceptions.InvalidArchiveError(filename, f"failed with error: {str(e)}") from e + + +def _list(filename: str, components: list[str], verbose=True): + memfile = io.StringIO() + for component in _stream_components(filename, components): + for tar, _ in component: + with redirect_stdout(memfile): + tar.list(verbose=verbose) + # next iteraton of for loop raises GeneratorExit in stream + # see comments in conda_package_streaming.extract:extract_stream + # and docstring in conda_package_streaming.package_streaming:stream_conda_info + component.close() + memfile.seek(0) + if verbose: + lines = sorted( + memfile.readlines(), + # verbose Tarfile.list() produces lines like: + # ?rw-r--r-- 502/20 2342 2018-10-04 14:02:00 info/about.json + # We only want the last part but we need to be mindful of paths containing spaces + key=lambda line: line.split(None, 5)[-1], + ) + else: + lines = sorted(memfile.readlines()) + print("".join(lines), end="") diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_package_handling/tarball.py b/data/miniconda3/lib/python3.13/site-packages/conda_package_handling/tarball.py new file mode 100644 index 0000000000000000000000000000000000000000..506a3e0ba5c0f8ea99b1210d11b5dd6e255bc222 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda_package_handling/tarball.py @@ -0,0 +1,101 @@ +import logging +import os +import re +import tarfile + +from . import streaming, utils +from .interface import AbstractBaseFormat + +LOG = logging.getLogger(__name__) + + +def _sort_file_order(prefix, files): + """Sort by filesize, to optimize compression?""" + info_slash = "info" + os.path.sep + + def order(f): + # we don't care about empty files so send them back via 100000 + fsize = os.lstat(os.path.join(prefix, f)).st_size or 100000 + # info/* records will be False == 0, others will be 1. + info_order = int(not f.startswith(info_slash)) + if info_order: + _, ext = os.path.splitext(f) + # Strip any .dylib.* and .so.* and rename .dylib to .so + ext = re.sub(r"(\.dylib|\.so).*$", r".so", ext) + if not ext: + # Files without extensions should be sorted by dirname + info_order = 1 + hash(os.path.dirname(f)) % (10**8) + else: + info_order = 1 + abs(hash(ext)) % (10**8) + return info_order, fsize + + files_list = list(sorted(files, key=order)) + + return files_list + + +def _create_no_libarchive(fullpath, files): + with tarfile.open(fullpath, "w:bz2") as t: + for f in files: + t.add(f, filter=utils.anonymize_tarinfo) + + +def create_compressed_tarball( + prefix, files, tmpdir, basename, ext, compression_filter, filter_opts="" +): + tmp_path = os.path.join(tmpdir, basename) + files = _sort_file_order(prefix, files) + + # add files in order of a) in info directory, b) increasing size so + # we can access small manifest or json files without decompressing + # possible large binary or data files + fullpath = tmp_path + ext + with utils.tmp_chdir(prefix): + _create_no_libarchive(fullpath, files) + return fullpath + + +class CondaTarBZ2(AbstractBaseFormat): + @staticmethod + def supported(fn): + return fn.endswith(".tar.bz2") + + @staticmethod + def extract(fn, dest_dir, **kw): + if not os.path.isdir(dest_dir): + os.makedirs(dest_dir) + if not os.path.isabs(fn): + fn = os.path.normpath(os.path.join(os.getcwd(), fn)) + + streaming._extract(str(fn), str(dest_dir), components=["pkg"]) + + @staticmethod + def create(prefix, file_list, out_fn, out_folder=None, **kw): + if out_folder is None: + out_folder = os.getcwd() + if os.path.isabs(out_fn): + out_folder = os.path.dirname(out_fn) + out_file = create_compressed_tarball( + prefix, + file_list, + out_folder, + os.path.basename(out_fn).replace(".tar.bz2", ""), + ".tar.bz2", + "bzip2", + ) + return out_file + + @staticmethod + def get_pkg_details(in_file): + stat_result = os.stat(in_file) + size = stat_result.st_size + md5, sha256 = utils.checksums(in_file, ("md5", "sha256")) + return {"size": size, "md5": md5, "sha256": sha256} + + @staticmethod + def list_contents(fn, verbose=False, **kw): + if "://" in fn: + raise ValueError("Remote .tar.bz2 artifact listing is not supported.") + if not os.path.isabs(fn): + fn = os.path.abspath(fn) + streaming._list(str(fn), components=["pkg"], verbose=verbose) diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_package_handling/utils.py b/data/miniconda3/lib/python3.13/site-packages/conda_package_handling/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..699a2dbe4d31c495a04205c200376a22714be26c --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda_package_handling/utils.py @@ -0,0 +1,493 @@ +import contextlib +import fnmatch +import hashlib +import logging +import os +import re +import shutil +import sys +import warnings as _warnings +from concurrent.futures import Executor, ProcessPoolExecutor, ThreadPoolExecutor +from errno import EACCES, ENOENT, EPERM, EROFS +from itertools import chain +from os.path import ( + abspath, + basename, + dirname, + isdir, + isfile, + islink, + join, + lexists, + normpath, + split, +) +from stat import S_IEXEC, S_IMODE, S_ISDIR, S_ISREG, S_IWRITE +from subprocess import STDOUT, CalledProcessError, check_output, list2cmdline +from tempfile import NamedTemporaryFile, mkdtemp + +on_win = sys.platform == "win32" +log = logging.getLogger(__name__) +CONDA_TEMP_EXTENSION = ".c~" + + +def which(executable): + from distutils.spawn import find_executable + + return find_executable(executable) + + +def make_writable(path): + try: + mode = os.lstat(path).st_mode + if S_ISDIR(mode): + os.chmod(path, S_IMODE(mode) | S_IWRITE | S_IEXEC) + elif S_ISREG(mode) or islink(path): + os.chmod(path, S_IMODE(mode) | S_IWRITE) + else: + log.debug("path cannot be made writable: %s", path) + return True + except Exception as e: + eno = getattr(e, "errno", None) + if eno in (ENOENT,): + log.debug("tried to make writable, but didn't exist: %s", path) + raise + elif eno in (EACCES, EPERM, EROFS): + log.debug("tried make writable but failed: %s\n%r", path, e) + return False + else: + log.warn("Error making path writable: %s\n%r", path, e) + raise + + +class DummyExecutor(Executor): + def map(self, func, *iterables): + for iterable in iterables: + for thing in iterable: + yield func(thing) + + +def get_executor(processes): + return DummyExecutor() if processes == 1 else ProcessPoolExecutor(max_workers=processes) + + +def recursive_make_writable(path): + # The need for this function was pointed out at + # https://github.com/conda/conda/issues/3266#issuecomment-239241915 + # Especially on windows, file removal will often fail because it is marked read-only + if isdir(path): + for root, dirs, files in os.walk(path): + for path in chain.from_iterable((files, dirs)): + try: + make_writable(join(root, path)) + except: + pass + else: + try: + make_writable(path) + except: + pass + + +def quote_for_shell(arguments, shell=None): + if not shell: + shell = "cmd.exe" if on_win else "bash" + if shell == "cmd.exe": + return list2cmdline(arguments) + else: + # If any multiline argument gets mixed with any other argument (which is true if we've + # arrived in this function) then we just quote it. This assumes something like: + # ['python', '-c', 'a\nmultiline\nprogram\n'] + # It may make sense to allow specifying a replacement character for '\n' too? e.g. ';' + quoted = [] + # This could all be replaced with some regex wizardry but that is less readable and + # for code like this, readability is very important. + for arg in arguments: + if '"' in arg: + quote = "'" + elif "'" in arg: + quote = '"' + elif not any(_ in arg for _ in (" ", "\n")): + quote = "" + else: + quote = '"' + quoted.append(quote + arg + quote) + return " ".join(quoted) + + +def rmtree(path, *args, **kwargs): + # subprocessing to delete large folders can be quite a bit faster + path = normpath(path) + if on_win: + try: + # the fastest way seems to be using DEL to recursively delete files + # https://www.ghacks.net/2017/07/18/how-to-delete-large-folders-in-windows-super-fast/ + # However, this is not entirely safe, as it can end up following symlinks to folders + # https://superuser.com/a/306618/184799 + # so, we stick with the slower, but hopefully safer way. Maybe if we figured out how + # to scan for any possible symlinks, we could do the faster way. + # out = check_output('DEL /F/Q/S *.* > NUL 2> NUL'.format(path), shell=True, + # stderr=STDOUT, cwd=path) + + out = check_output(f'RD /S /Q "{path}" > NUL 2> NUL', shell=True, stderr=STDOUT) + except: + try: + # Try to delete in Unicode + name = None + + with NamedTemporaryFile(suffix=".bat", delete=False) as batch_file: + batch_file.write(f"RD /S {quote_for_shell([path])}\n") + batch_file.write("chcp 65001\n") + batch_file.write(f"RD /S {quote_for_shell([path])}\n") + batch_file.write("EXIT 0\n") + name = batch_file.name + # If the above is bugged we can end up deleting hard-drives, so we check + # that 'path' appears in it. This is not bulletproof but it could save you (me). + with open(name) as contents: + content = contents.read() + assert path in content + comspec = os.environ["COMSPEC"] + CREATE_NO_WINDOW = 0x08000000 + # It is essential that we `pass stdout=None, stderr=None, stdin=None` here because + # if we do not, then the standard console handles get attached and chcp affects the + # parent process (and any which share those console handles!) + out = check_output( + [comspec, "/d", "/c", name], + shell=False, + stdout=None, + stderr=None, + stdin=None, + creationflags=CREATE_NO_WINDOW, + ) + + except CalledProcessError as e: + if e.returncode != 5: + log.error(f"Removing folder {path} the fast way failed. Output was: {out}") + raise + else: + log.debug(f"removing dir contents the fast way failed. Output was: {out}") + else: + try: + os.makedirs(".empty") + except: + pass + # yes, this looks strange. See + # https://unix.stackexchange.com/a/79656/34459 + # https://web.archive.org/web/20130929001850/http://linuxnote.net/jianingy/en/linux/a-fast-way-to-remove-huge-number-of-files.html # NOQA + rsync = which("rsync") + if rsync and isdir(".empty"): + try: + out = check_output( + [ + rsync, + "-a", + "--force", + "--delete", + join(os.getcwd(), ".empty") + "/", + path + "/", + ], + stderr=STDOUT, + ) + except CalledProcessError: + log.debug(f"removing dir contents the fast way failed. Output was: {out}") + shutil.rmtree(".empty") + shutil.rmtree(path) + + +def unlink_or_rename_to_trash(path): + """If files are in use, especially on windows, we can't remove them. + The fallback path is to rename them (but keep their folder the same), + which maintains the file handle validity. See comments at: + https://serverfault.com/a/503769 + """ + try: + make_writable(path) + os.unlink(path) + except OSError: + try: + os.rename(path, path + ".conda_trash") + except OSError: + if on_win: + # on windows, it is important to use the rename program, as just using python's + # rename leads to permission errors when files are in use. + with NamedTemporaryFile(suffix=".bat") as trash_script: + with open(trash_script, "w") as f: + f.write('@pushd "%1"\n') + f.write("@REM Rename src to dest") + f.write('@ren "%2" "%3" > NUL 2> NUL")') + + _dirname, _fn = split(path) + dest_fn = path + ".conda_trash" + counter = 1 + while isfile(dest_fn): + dest_fn = dest_fn.splitext[0] + f".conda_trash_{counter}" + counter += 1 + out = "< empty >" + try: + out = check_output( + [ + "cmd.exe", + "/C", + trash_script, + _dirname, + _fn, + basename(dest_fn), + ], + stderr=STDOUT, + ) + except CalledProcessError: + log.warn( + "renaming file path {} to trash failed. Output was: {}".format( + path, out + ) + ) + + log.warn( + "Could not remove or rename {}. Please remove this file manually (you " + "may need to reboot to free file handles)".format(path) + ) + + +def remove_empty_parent_paths(path): + # recurse to clean up empty folders that were created to have a nested hierarchy + parent_path = dirname(path) + while isdir(parent_path) and not os.listdir(parent_path): + rmdir(parent_path) + parent_path = dirname(parent_path) + + +def rm_rf(path, clean_empty_parents=False, *args, **kw): + """ + Completely delete path + max_retries is the number of times to retry on failure. The default is 5. This only applies + to deleting a directory. + If removing path fails and trash is True, files will be moved to the trash directory. + """ + recursive_make_writable(path) + try: + path = abspath(path) + if isdir(path) and not islink(path): + rmdir(path) + elif lexists(path): + unlink_or_rename_to_trash(path) + else: + log.debug("rm_rf failed. Not a link, file, or directory: %s", path) + finally: + if lexists(path): + log.info("rm_rf failed for %s", path) + return False + if isdir(path): + delete_trash(path) + if clean_empty_parents: + remove_empty_parent_paths(path) + return True + + +# aliases that all do the same thing (legacy compat) +try_rmdir_all_empty = move_to_trash = move_path_to_trash = rm_rf + + +def delete_trash(prefix): + if not prefix: + prefix = sys.prefix + exclude = {"envs"} + for root, dirs, files in os.walk(prefix, topdown=True): + dirs[:] = [d for d in dirs if d not in exclude] + for fn in files: + if fnmatch.fnmatch(fn, "*.conda_trash*") or fnmatch.fnmatch( + fn, "*" + CONDA_TEMP_EXTENSION + ): + filename = join(root, fn) + try: + os.unlink(filename) + remove_empty_parent_paths(filename) + except OSError as e: + log.debug("%r errno %d\nCannot unlink %s.", e, e.errno, filename) + + +def rmdir(dirpath): + if not isdir(dirpath): + return + try: + rmtree(dirpath) + # we don't really care about errors that much. We'll catch remaining files + # with slower python logic. + except: + pass + + for root, dirs, files in os.walk(dirpath, topdown=False): + for f in files: + unlink_or_rename_to_trash(join(root, f)) + + +# we have our own TemporaryDirectory class because it's faster and handles disk issues better. +class TemporaryDirectory: + """Create and return a temporary directory. This has the same + behavior as mkdtemp but can be used as a context manager. For + example: + + with TemporaryDirectory() as tmpdir: + ... + + Upon exiting the context, the directory and everything contained + in it are removed. + """ + + # Handle mkdtemp raising an exception + name = None + _closed = False + + def __init__(self, suffix="", prefix=".cph_tmp", dir=os.getcwd()): + self.name = mkdtemp(suffix, prefix, dir) + + def __repr__(self): + return f"<{self.__class__.__name__} {self.name!r}>" + + def __enter__(self): + return self.name + + def cleanup(self, _warn=False, _warnings=_warnings): + if self.name and not self._closed: + try: + rm_rf(self.name) + except: + _warnings.warn( + 'Conda-package-handling says: "I tried to clean up, ' + "but I could not. There is a mess in %s that you might " + 'want to clean up yourself. Sorry..."' % self.name + ) + self._closed = True + if _warn and _warnings.warn: + _warnings.warn( + f"Implicitly cleaning up {self!r}", + _warnings.ResourceWarning, + ) + + def __exit__(self, exc, value, tb): + self.cleanup() + + def __del__(self): + # Issue a ResourceWarning if implicit cleanup needed + self.cleanup(_warn=True) + + +@contextlib.contextmanager +def tmp_chdir(dest): + curdir = os.getcwd() + try: + os.chdir(dest) + yield + finally: + os.chdir(curdir) + + +def ensure_list(arg): + if isinstance(arg, str) or not hasattr(arg, "__iter__"): + if arg is not None: + arg = [arg] + else: + arg = [] + return arg + + +def filter_files( + files_list, + prefix, + filter_patterns=( + r"(.*[\\\\/])?\.git[\\\\/].*", + r"(.*[\\\\/])?\.git$", + r"(.*)?\.DS_Store.*", + r".*\.la$", + r"conda-meta.*", + ), +): + """Remove things like the .git directory from the list of files to be copied""" + for pattern in filter_patterns: + r = re.compile(pattern) + files_list = set(files_list) - set(filter(r.match, files_list)) + return [ + f + for f in files_list + if + # `islink` prevents symlinks to directories from being removed + os.path.islink(os.path.join(prefix, f)) or not os.path.isdir(os.path.join(prefix, f)) + ] + + +def filter_info_files(files_list, prefix): + return filter_files( + files_list, + prefix, + filter_patterns=( + "info[\\\\/]index\\.json", + "info[\\\\/]files", + "info[\\\\/]paths\\.json", + "info[\\\\/]about\\.json", + "info[\\\\/]has_prefix", + "info[\\\\/]hash_input_files", # legacy, not used anymore + "info[\\\\/]hash_input\\.json", + "info[\\\\/]run_exports\\.yaml", # legacy + "info[\\\\/]run_exports\\.json", # current + "info[\\\\/]git", + "info[\\\\/]recipe[\\\\/].*", + "info[\\\\/]recipe_log.json", + "info[\\\\/]recipe.tar", + "info[\\\\/]test[\\\\/].*", + "info[\\\\/]LICENSE.*", + "info[\\\\/]requires", + "info[\\\\/]meta", + "info[\\\\/]platform", + "info[\\\\/]no_link", + "info[\\\\/]link\\.json", + "info[\\\\/]icon\\.png", + ), + ) + + +def _checksum(fd, algorithm, buffersize=65536): + hash_impl = getattr(hashlib, algorithm) + if not hash_impl: + raise ValueError(f"Unrecognized hash algorithm: {algorithm}") + else: + hash_impl = hash_impl() + for block in iter(lambda: fd.read(buffersize), b""): + hash_impl.update(block) + return hash_impl.hexdigest() + + +def sha256_checksum(fd): + return _checksum(fd, "sha256") + + +def md5_checksum(fd): + return _checksum(fd, "md5") + + +def checksum(fn, algorithm, buffersize=1 << 18): + """ + Calculate a checksum for a filename (not an open file). + """ + with open(fn, "rb") as fd: + return _checksum(fd, algorithm, buffersize) + + +def checksums(fn, algorithms, buffersize=1 << 18): + """ + Calculate multiple checksums for a filename in parallel. + """ + with ThreadPoolExecutor(max_workers=len(algorithms)) as e: + # take care not to share hash_impl between threads + results = [e.submit(checksum, fn, algorithm, buffersize) for algorithm in algorithms] + return [result.result() for result in results] + + +def anonymize_tarinfo(tarinfo): + """ + Remove user id, name from tarinfo. + """ + # also remove timestamps? + tarinfo.uid = 0 + tarinfo.uname = "" + tarinfo.gid = 0 + tarinfo.gname = "" + return tarinfo diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_package_handling/validate.py b/data/miniconda3/lib/python3.13/site-packages/conda_package_handling/validate.py new file mode 100644 index 0000000000000000000000000000000000000000..024d71af293153b500a273fe2f45ba641eb48945 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda_package_handling/validate.py @@ -0,0 +1,112 @@ +from __future__ import annotations + +import hashlib +import os +from itertools import chain +from pathlib import Path + +from conda_package_streaming import package_streaming + +from .utils import TemporaryDirectory + + +def validate_converted_files_match( + src_file_or_folder, subject, reference_ext="" +): # pragma: nocover + # No longer used by conda-package-handling + from .api import extract + + with TemporaryDirectory() as tmpdir: + assert tmpdir is not None + if os.path.isdir(src_file_or_folder): + src_folder = src_file_or_folder + else: + extract(src_file_or_folder + reference_ext, dest_dir=os.path.join(tmpdir, "src")) + src_folder = os.path.join(tmpdir, "src") + + converted_folder = os.path.join(tmpdir, "converted") + extract(subject, dest_dir=converted_folder) + + missing_files = set() + mismatch_size = set() + for root, dirs, files in os.walk(src_folder): + for f in files: + absfile = os.path.join(root, f) + rp = os.path.relpath(absfile, src_folder) + destpath = os.path.join(converted_folder, rp) + if not os.path.islink(destpath): + if not os.path.isfile(destpath): + missing_files.add(rp) + elif os.stat(absfile).st_size != os.stat(destpath).st_size: + mismatch_size.add(rp) + return src_file_or_folder, missing_files, mismatch_size + + +def hash_fn(): + return hashlib.blake2b() + + +IGNORE_FIELDS = { + "uid", + "gid", + "mtime", + "uname", + "gname", + "chksum", +} #: ignore if not strict + + +def validate_converted_files_match_streaming( + src: str | Path, reference: str | Path, *, strict=True +): + """ + Check that two .tar.bz2 or .conda files (either of src_file and + reference_file can be either format) match exactly, down to the timestamps + etc. + + Does not check outside of the info- and pkg- components of a .conda. + (conda's metadata.json, which gives the version "2" of the format) + + If strict = True, also check for matching uid, gid, mtime, uname, gname. + """ + source_set = {} + reference_set = {} + ignore_fields = {"chksum"} if strict else IGNORE_FIELDS + + def get_fileset(filename: str | Path): + fileset = {} + components = ["info", "pkg"] if os.fspath(filename).endswith(".conda") else ["pkg"] + with open(filename, "rb") as conda_file: + for component in components: + for tar, member in package_streaming.stream_conda_component( + filename, conda_file, component + ): + info = {k: v for k, v in member.get_info().items() if k not in ignore_fields} + + if member.isfile(): + hasher = hash_fn() + fd = tar.extractfile(member) + assert fd is not None + for block in iter(lambda: fd.read(1 << 18), b""): # type: ignore + hasher.update(block) + + info["digest"] = hasher.hexdigest() + + fileset[info["name"]] = info + + return fileset + + source_set = get_fileset(src) + reference_set = get_fileset(reference) + + missing = [] + mismatched = [] + + if source_set != reference_set: + for file in chain(source_set, reference_set): + if not (file in source_set and file in reference_set): + missing.append(file) + elif source_set[file] != reference_set[file]: + mismatched.append(file) + + return src, missing, mismatched diff --git a/data/miniconda3/lib/python3.13/site-packages/contourpy-1.3.3.dist-info/INSTALLER b/data/miniconda3/lib/python3.13/site-packages/contourpy-1.3.3.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/contourpy-1.3.3.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/data/miniconda3/lib/python3.13/site-packages/contourpy-1.3.3.dist-info/LICENSE b/data/miniconda3/lib/python3.13/site-packages/contourpy-1.3.3.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..93e41fb6965a930641ba181a3ae4e1008246d9d5 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/contourpy-1.3.3.dist-info/LICENSE @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2021-2025, ContourPy Developers. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/data/miniconda3/lib/python3.13/site-packages/contourpy-1.3.3.dist-info/METADATA b/data/miniconda3/lib/python3.13/site-packages/contourpy-1.3.3.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..68529fbd400e902db54175b9286d9f24eb6976e1 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/contourpy-1.3.3.dist-info/METADATA @@ -0,0 +1,94 @@ +Metadata-Version: 2.1 +Name: contourpy +Version: 1.3.3 +Summary: Python library for calculating contours of 2D quadrilateral grids +Author-Email: Ian Thomas +License: BSD 3-Clause License + + Copyright (c) 2021-2025, ContourPy Developers. + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Science/Research +Classifier: License :: OSI Approved :: BSD License +Classifier: Programming Language :: C++ +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Topic :: Scientific/Engineering :: Information Analysis +Classifier: Topic :: Scientific/Engineering :: Mathematics +Classifier: Topic :: Scientific/Engineering :: Visualization +Project-URL: Homepage, https://github.com/contourpy/contourpy +Project-URL: Changelog, https://contourpy.readthedocs.io/en/latest/changelog.html +Project-URL: Documentation, https://contourpy.readthedocs.io +Project-URL: Repository, https://github.com/contourpy/contourpy +Requires-Python: >=3.11 +Requires-Dist: numpy>=1.25 +Provides-Extra: docs +Requires-Dist: furo; extra == "docs" +Requires-Dist: sphinx>=7.2; extra == "docs" +Requires-Dist: sphinx-copybutton; extra == "docs" +Provides-Extra: bokeh +Requires-Dist: bokeh; extra == "bokeh" +Requires-Dist: selenium; extra == "bokeh" +Provides-Extra: mypy +Requires-Dist: contourpy[bokeh,docs]; extra == "mypy" +Requires-Dist: bokeh; extra == "mypy" +Requires-Dist: docutils-stubs; extra == "mypy" +Requires-Dist: mypy==1.17.0; extra == "mypy" +Requires-Dist: types-Pillow; extra == "mypy" +Provides-Extra: test +Requires-Dist: contourpy[test-no-images]; extra == "test" +Requires-Dist: matplotlib; extra == "test" +Requires-Dist: Pillow; extra == "test" +Provides-Extra: test-no-images +Requires-Dist: pytest; extra == "test-no-images" +Requires-Dist: pytest-cov; extra == "test-no-images" +Requires-Dist: pytest-rerunfailures; extra == "test-no-images" +Requires-Dist: pytest-xdist; extra == "test-no-images" +Requires-Dist: wurlitzer; extra == "test-no-images" +Description-Content-Type: text/markdown + +ContourPy + +ContourPy is a Python library for calculating contours of 2D quadrilateral grids. It is written in C++11 and wrapped using pybind11. + +It contains the 2005 and 2014 algorithms used in Matplotlib as well as a newer algorithm that includes more features and is available in both serial and multithreaded versions. It provides an easy way for Python libraries to use contouring algorithms without having to include Matplotlib as a dependency. + + * **Documentation**: https://contourpy.readthedocs.io + * **Source code**: https://github.com/contourpy/contourpy + +| | | +| --- | --- | +| Latest release | [![PyPI version](https://img.shields.io/pypi/v/contourpy.svg?label=pypi&color=fdae61)](https://pypi.python.org/pypi/contourpy) [![conda-forge version](https://img.shields.io/conda/v/conda-forge/contourpy.svg?label=conda-forge&color=a6d96a)](https://anaconda.org/conda-forge/contourpy) | +| Downloads | [![PyPi downloads](https://img.shields.io/pypi/dm/contourpy?label=pypi&style=flat&color=fdae61)](https://pepy.tech/project/contourpy) | +| Python version | [![Platforms](https://img.shields.io/pypi/pyversions/contourpy?color=fdae61)](https://pypi.org/project/contourpy/) | +| Coverage | [![Codecov](https://img.shields.io/codecov/c/gh/contourpy/contourpy?color=fdae61&label=codecov)](https://app.codecov.io/gh/contourpy/contourpy) | diff --git a/data/miniconda3/lib/python3.13/site-packages/contourpy-1.3.3.dist-info/RECORD b/data/miniconda3/lib/python3.13/site-packages/contourpy-1.3.3.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..d541b393bec366f509ea1fb97a42dfe21698b488 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/contourpy-1.3.3.dist-info/RECORD @@ -0,0 +1,42 @@ +contourpy-1.3.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +contourpy-1.3.3.dist-info/LICENSE,sha256=NBcJefxk9PXm36Zu8n3sMU___FhSAAxg9INuwd-_FW4,1534 +contourpy-1.3.3.dist-info/METADATA,sha256=xDzvhrrvCc_5x3l15Xj6jMoMlFTfQNwXaTi0maY95Uo,5461 +contourpy-1.3.3.dist-info/RECORD,, +contourpy-1.3.3.dist-info/WHEEL,sha256=CbEWW8vEVtAirkfzwD0j6d8p6yQEVp92CrRZNhdVvK8,138 +contourpy/__init__.py,sha256=6sf-K0D4xaEIDhk38USOjszRiLz52rM43-vtcfVrMvY,11765 +contourpy/__pycache__/__init__.cpython-313.pyc,, +contourpy/__pycache__/_version.cpython-313.pyc,, +contourpy/__pycache__/array.cpython-313.pyc,, +contourpy/__pycache__/chunk.cpython-313.pyc,, +contourpy/__pycache__/convert.cpython-313.pyc,, +contourpy/__pycache__/dechunk.cpython-313.pyc,, +contourpy/__pycache__/enum_util.cpython-313.pyc,, +contourpy/__pycache__/typecheck.cpython-313.pyc,, +contourpy/__pycache__/types.cpython-313.pyc,, +contourpy/_contourpy.cpython-313-x86_64-linux-gnu.so,sha256=w0ooU01EBiFqDlBnD0CRyEEABDPYO4Hq3kgW7ryBzRY,954680 +contourpy/_contourpy.pyi,sha256=fvtccxkiZwGb6qYag7Fp4E8bsFmAIjAmobf8LNxqfgc,7122 +contourpy/_version.py,sha256=Vi6om3KImlKsS_Wg5CjUgYffoi2zx7T-SRPnnGL0G7M,22 +contourpy/array.py,sha256=4WwLuiZe30rizn_raymmY13OzE6hlCsDOO8kuVFOP18,8979 +contourpy/chunk.py,sha256=8njDQqlpuD22RjaaCyA75FXQsSQDY5hZGJSrxFpvGGU,3279 +contourpy/convert.py,sha256=mhyn7prEoWCnf0igaH-VqDwlk-CegFsZ4qOy2LL-hpU,26154 +contourpy/dechunk.py,sha256=EgFL6hw5H54ccuof4tJ2ehdnktT7trgZjiZqppsH8QI,7756 +contourpy/enum_util.py,sha256=o8MItJRs08oqzwPP3IwC75BBAY9Qq95saIzjkXBXwqA,1519 +contourpy/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +contourpy/typecheck.py,sha256=t1nvvCuKMYva1Zx4fc30EpdKFcO0Enz3n_UFfXBsq9o,10747 +contourpy/types.py,sha256=2K4T5tJpMIjYrkkg1Lqh3C2ZKlnOhnMtYmtwz92l_y8,247 +contourpy/util/__init__.py,sha256=eVhJ_crOHL7nkG4Kb0dOo7NL4WHMy_Px665aAN_3d-8,118 +contourpy/util/__pycache__/__init__.cpython-313.pyc,, +contourpy/util/__pycache__/_build_config.cpython-313.pyc,, +contourpy/util/__pycache__/bokeh_renderer.cpython-313.pyc,, +contourpy/util/__pycache__/bokeh_util.cpython-313.pyc,, +contourpy/util/__pycache__/data.cpython-313.pyc,, +contourpy/util/__pycache__/mpl_renderer.cpython-313.pyc,, +contourpy/util/__pycache__/mpl_util.cpython-313.pyc,, +contourpy/util/__pycache__/renderer.cpython-313.pyc,, +contourpy/util/_build_config.py,sha256=HBhIkTcC03y7MBCbQlp87L7VS9CXKEgv9G6lVpY-Y0w,1847 +contourpy/util/bokeh_renderer.py,sha256=vSQcq_3zIQWj1E8qoM2j3sI7XlBFJcam9axuhfZle4I,13836 +contourpy/util/bokeh_util.py,sha256=wc-S3ewBUYWyIkEv9jkhFySIergjLQl4Z0UEVnE0HhA,2804 +contourpy/util/data.py,sha256=-7SSGMLX_gN-1H2JzpNSEB_EcEF_uMtYdOo_ePRIcg8,2586 +contourpy/util/mpl_renderer.py,sha256=dhPhSMKwVuFneNGZuBIgXCp9YjffqHpUyPG5C-T-5tU,20092 +contourpy/util/mpl_util.py,sha256=0Jz5f-aA9XMWlpO2pDnHbkVgxIiw4SY_ysxf_gACWEo,3452 +contourpy/util/renderer.py,sha256=8CBHzPmVsFPfqsWxqrxGBhqFpJhVeFHFeDzVXAgT8Fc,5118 diff --git a/data/miniconda3/lib/python3.13/site-packages/contourpy-1.3.3.dist-info/WHEEL b/data/miniconda3/lib/python3.13/site-packages/contourpy-1.3.3.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..c8d1a17078eed338e92b34312a41235b8da8f511 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/contourpy-1.3.3.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: meson +Root-Is-Purelib: false +Tag: cp313-cp313-manylinux_2_27_x86_64 +Tag: cp313-cp313-manylinux_2_28_x86_64 + diff --git a/data/miniconda3/lib/python3.13/site-packages/contourpy/__init__.py b/data/miniconda3/lib/python3.13/site-packages/contourpy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..82d578db2fc3b165fe55fef879001733448d3524 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/contourpy/__init__.py @@ -0,0 +1,285 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +import numpy as np + +from contourpy._contourpy import ( + ContourGenerator, + FillType, + LineType, + Mpl2005ContourGenerator, + Mpl2014ContourGenerator, + SerialContourGenerator, + ThreadedContourGenerator, + ZInterp, + max_threads, +) +from contourpy._version import __version__ +from contourpy.chunk import calc_chunk_sizes +from contourpy.convert import ( + convert_filled, + convert_lines, + convert_multi_filled, + convert_multi_lines, +) +from contourpy.dechunk import ( + dechunk_filled, + dechunk_lines, + dechunk_multi_filled, + dechunk_multi_lines, +) +from contourpy.enum_util import as_fill_type, as_line_type, as_z_interp + +if TYPE_CHECKING: + from typing import Any + + from numpy.typing import ArrayLike + + from ._contourpy import CoordinateArray, MaskArray + +__all__ = [ + "__version__", + "contour_generator", + "convert_filled", + "convert_lines", + "convert_multi_filled", + "convert_multi_lines", + "dechunk_filled", + "dechunk_lines", + "dechunk_multi_filled", + "dechunk_multi_lines", + "max_threads", + "FillType", + "LineType", + "ContourGenerator", + "Mpl2005ContourGenerator", + "Mpl2014ContourGenerator", + "SerialContourGenerator", + "ThreadedContourGenerator", + "ZInterp", +] + + +# Simple mapping of algorithm name to class name. +_class_lookup: dict[str, type[ContourGenerator]] = { + "mpl2005": Mpl2005ContourGenerator, + "mpl2014": Mpl2014ContourGenerator, + "serial": SerialContourGenerator, + "threaded": ThreadedContourGenerator, +} + + +def _remove_z_mask( + z: ArrayLike | np.ma.MaskedArray[Any, Any] | None, +) -> tuple[CoordinateArray, MaskArray | None]: + # Preserve mask if present. + z_array = np.ma.asarray(z, dtype=np.float64) # type: ignore[no-untyped-call] + z_masked = np.ma.masked_invalid(z_array, copy=False) # type: ignore[no-untyped-call] + + if np.ma.is_masked(z_masked): + mask = np.ma.getmask(z_masked) + else: + mask = None + + return np.ma.getdata(z_masked), mask # type: ignore[no-untyped-call] + + +def contour_generator( + x: ArrayLike | None = None, + y: ArrayLike | None = None, + z: ArrayLike | np.ma.MaskedArray[Any, Any] | None = None, + *, + name: str = "serial", + corner_mask: bool | None = None, + line_type: LineType | str | None = None, + fill_type: FillType | str | None = None, + chunk_size: int | tuple[int, int] | None = None, + chunk_count: int | tuple[int, int] | None = None, + total_chunk_count: int | None = None, + quad_as_tri: bool = False, + z_interp: ZInterp | str | None = ZInterp.Linear, + thread_count: int = 0, +) -> ContourGenerator: + """Create and return a :class:`~.ContourGenerator` object. + + The class and properties of the returned :class:`~.ContourGenerator` are determined by the + function arguments, with sensible defaults. + + Args: + x (array-like of shape (ny, nx) or (nx,), optional): The x-coordinates of the ``z`` values. + May be 2D with the same shape as ``z.shape``, or 1D with length ``nx = z.shape[1]``. + If not specified are assumed to be ``np.arange(nx)``. Must be ordered monotonically. + y (array-like of shape (ny, nx) or (ny,), optional): The y-coordinates of the ``z`` values. + May be 2D with the same shape as ``z.shape``, or 1D with length ``ny = z.shape[0]``. + If not specified are assumed to be ``np.arange(ny)``. Must be ordered monotonically. + z (array-like of shape (ny, nx), may be a masked array): The 2D gridded values to calculate + the contours of. May be a masked array, and any invalid values (``np.inf`` or + ``np.nan``) will also be masked out. + name (str): Algorithm name, one of ``"serial"``, ``"threaded"``, ``"mpl2005"`` or + ``"mpl2014"``, default ``"serial"``. + corner_mask (bool, optional): Enable/disable corner masking, which only has an effect if + ``z`` is a masked array. If ``False``, any quad touching a masked point is masked out. + If ``True``, only the triangular corners of quads nearest these points are always masked + out, other triangular corners comprising three unmasked points are contoured as usual. + If not specified, uses the default provided by the algorithm ``name``. + line_type (LineType or str, optional): The format of contour line data returned from calls + to :meth:`~.ContourGenerator.lines`, specified either as a :class:`~.LineType` or its + string equivalent such as ``"SeparateCode"``. + If not specified, uses the default provided by the algorithm ``name``. + The relationship between the :class:`~.LineType` enum and the data format returned from + :meth:`~.ContourGenerator.lines` is explained at :ref:`line_type`. + fill_type (FillType or str, optional): The format of filled contour data returned from calls + to :meth:`~.ContourGenerator.filled`, specified either as a :class:`~.FillType` or its + string equivalent such as ``"OuterOffset"``. + If not specified, uses the default provided by the algorithm ``name``. + The relationship between the :class:`~.FillType` enum and the data format returned from + :meth:`~.ContourGenerator.filled` is explained at :ref:`fill_type`. + chunk_size (int or tuple(int, int), optional): Chunk size in (y, x) directions, or the same + size in both directions if only one value is specified. + chunk_count (int or tuple(int, int), optional): Chunk count in (y, x) directions, or the + same count in both directions if only one value is specified. + total_chunk_count (int, optional): Total number of chunks. + quad_as_tri (bool): Enable/disable treating quads as 4 triangles, default ``False``. + If ``False``, a contour line within a quad is a straight line between points on two of + its edges. If ``True``, each full quad is divided into 4 triangles using a virtual point + at the centre (mean x, y of the corner points) and a contour line is piecewise linear + within those triangles. Corner-masked triangles are not affected by this setting, only + full unmasked quads. + z_interp (ZInterp or str, optional): How to interpolate ``z`` values when determining where + contour lines intersect the edges of quads and the ``z`` values of the central points of + quads, specified either as a :class:`~contourpy.ZInterp` or its string equivalent such + as ``"Log"``. Default is ``ZInterp.Linear``. + thread_count (int): Number of threads to use for contour calculation, default 0. Threads can + only be used with an algorithm ``name`` that supports threads (currently only + ``name="threaded"``) and there must be at least the same number of chunks as threads. + If ``thread_count=0`` and ``name="threaded"`` then it uses the maximum number of threads + as determined by the C++11 call ``std::thread::hardware_concurrency()``. If ``name`` is + something other than ``"threaded"`` then the ``thread_count`` will be set to ``1``. + + Return: + :class:`~.ContourGenerator`. + + Note: + A maximum of one of ``chunk_size``, ``chunk_count`` and ``total_chunk_count`` may be + specified. + + Warning: + The ``name="mpl2005"`` algorithm does not implement chunking for contour lines. + """ + x = np.asarray(x, dtype=np.float64) + y = np.asarray(y, dtype=np.float64) + z, mask = _remove_z_mask(z) + + # Check arguments: z. + if z.ndim != 2: + raise TypeError(f"Input z must be 2D, not {z.ndim}D") + + if z.shape[0] < 2 or z.shape[1] < 2: + raise TypeError(f"Input z must be at least a (2, 2) shaped array, but has shape {z.shape}") + + ny, nx = z.shape + + # Check arguments: x and y. + if x.ndim != y.ndim: + raise TypeError(f"Number of dimensions of x ({x.ndim}) and y ({y.ndim}) do not match") + + if x.ndim == 0: + x = np.arange(nx, dtype=np.float64) + y = np.arange(ny, dtype=np.float64) + x, y = np.meshgrid(x, y) + elif x.ndim == 1: + if len(x) != nx: + raise TypeError(f"Length of x ({len(x)}) must match number of columns in z ({nx})") + if len(y) != ny: + raise TypeError(f"Length of y ({len(y)}) must match number of rows in z ({ny})") + x, y = np.meshgrid(x, y) + elif x.ndim == 2: + if x.shape != z.shape: + raise TypeError(f"Shapes of x {x.shape} and z {z.shape} do not match") + if y.shape != z.shape: + raise TypeError(f"Shapes of y {y.shape} and z {z.shape} do not match") + else: + raise TypeError(f"Inputs x and y must be None, 1D or 2D, not {x.ndim}D") + + # Check mask shape just in case. + if mask is not None and mask.shape != z.shape: + raise ValueError("If mask is set it must be a 2D array with the same shape as z") + + # Check arguments: name. + if name not in _class_lookup: + raise ValueError(f"Unrecognised contour generator name: {name}") + + # Check arguments: chunk_size, chunk_count and total_chunk_count. + y_chunk_size, x_chunk_size = calc_chunk_sizes( + chunk_size, chunk_count, total_chunk_count, ny, nx) + + cls = _class_lookup[name] + + # Check arguments: corner_mask. + if corner_mask is None: + # Set it to default, which is True if the algorithm supports it. + corner_mask = cls.supports_corner_mask() + elif corner_mask and not cls.supports_corner_mask(): + raise ValueError(f"{name} contour generator does not support corner_mask=True") + + # Check arguments: line_type. + if line_type is None: + line_type = cls.default_line_type + else: + line_type = as_line_type(line_type) + + if not cls.supports_line_type(line_type): + raise ValueError(f"{name} contour generator does not support line_type {line_type}") + + # Check arguments: fill_type. + if fill_type is None: + fill_type = cls.default_fill_type + else: + fill_type = as_fill_type(fill_type) + + if not cls.supports_fill_type(fill_type): + raise ValueError(f"{name} contour generator does not support fill_type {fill_type}") + + # Check arguments: quad_as_tri. + if quad_as_tri and not cls.supports_quad_as_tri(): + raise ValueError(f"{name} contour generator does not support quad_as_tri=True") + + # Check arguments: z_interp. + if z_interp is None: + z_interp = ZInterp.Linear + else: + z_interp = as_z_interp(z_interp) + + if z_interp != ZInterp.Linear and not cls.supports_z_interp(): + raise ValueError(f"{name} contour generator does not support z_interp {z_interp}") + + # Check arguments: thread_count. + if thread_count not in (0, 1) and not cls.supports_threads(): + raise ValueError(f"{name} contour generator does not support thread_count {thread_count}") + + # Prepare args and kwargs for contour generator constructor. + args = [x, y, z, mask] + kwargs: dict[str, int | bool | LineType | FillType | ZInterp] = { + "x_chunk_size": x_chunk_size, + "y_chunk_size": y_chunk_size, + } + + if name not in ("mpl2005", "mpl2014"): + kwargs["line_type"] = line_type + kwargs["fill_type"] = fill_type + + if cls.supports_corner_mask(): + kwargs["corner_mask"] = corner_mask + + if cls.supports_quad_as_tri(): + kwargs["quad_as_tri"] = quad_as_tri + + if cls.supports_z_interp(): + kwargs["z_interp"] = z_interp + + if cls.supports_threads(): + kwargs["thread_count"] = thread_count + + # Create contour generator. + return cls(*args, **kwargs) diff --git a/data/miniconda3/lib/python3.13/site-packages/contourpy/_contourpy.pyi b/data/miniconda3/lib/python3.13/site-packages/contourpy/_contourpy.pyi new file mode 100644 index 0000000000000000000000000000000000000000..5f44eace52ab6df5f3d05443c89e17f363dd8174 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/contourpy/_contourpy.pyi @@ -0,0 +1,199 @@ +from typing import ClassVar, NoReturn, TypeAlias + +import numpy as np +import numpy.typing as npt + +import contourpy._contourpy as cpy + +# Input numpy array types, the same as in common.h +CoordinateArray: TypeAlias = npt.NDArray[np.float64] +MaskArray: TypeAlias = npt.NDArray[np.bool_] +LevelArray: TypeAlias = npt.ArrayLike + +# Output numpy array types, the same as in common.h +PointArray: TypeAlias = npt.NDArray[np.float64] +CodeArray: TypeAlias = npt.NDArray[np.uint8] +OffsetArray: TypeAlias = npt.NDArray[np.uint32] + +# Types returned from filled() +FillReturn_OuterCode: TypeAlias = tuple[list[PointArray], list[CodeArray]] +FillReturn_OuterOffset: TypeAlias = tuple[list[PointArray], list[OffsetArray]] +FillReturn_ChunkCombinedCode: TypeAlias = tuple[list[PointArray | None], list[CodeArray | None]] +FillReturn_ChunkCombinedOffset: TypeAlias = tuple[list[PointArray | None], list[OffsetArray | None]] +FillReturn_ChunkCombinedCodeOffset: TypeAlias = tuple[list[PointArray | None], list[CodeArray | None], list[OffsetArray | None]] +FillReturn_ChunkCombinedOffsetOffset: TypeAlias = tuple[list[PointArray | None], list[OffsetArray | None], list[OffsetArray | None]] +FillReturn_Chunk: TypeAlias = FillReturn_ChunkCombinedCode | FillReturn_ChunkCombinedOffset | FillReturn_ChunkCombinedCodeOffset | FillReturn_ChunkCombinedOffsetOffset +FillReturn: TypeAlias = FillReturn_OuterCode | FillReturn_OuterOffset | FillReturn_Chunk + +# Types returned from lines() +LineReturn_Separate: TypeAlias = list[PointArray] +LineReturn_SeparateCode: TypeAlias = tuple[list[PointArray], list[CodeArray]] +LineReturn_ChunkCombinedCode: TypeAlias = tuple[list[PointArray | None], list[CodeArray | None]] +LineReturn_ChunkCombinedOffset: TypeAlias = tuple[list[PointArray | None], list[OffsetArray | None]] +LineReturn_ChunkCombinedNan: TypeAlias = tuple[list[PointArray | None]] +LineReturn_Chunk: TypeAlias = LineReturn_ChunkCombinedCode | LineReturn_ChunkCombinedOffset | LineReturn_ChunkCombinedNan +LineReturn: TypeAlias = LineReturn_Separate | LineReturn_SeparateCode | LineReturn_Chunk + + +NDEBUG: int +__version__: str + +class FillType: + ChunkCombinedCode: ClassVar[cpy.FillType] + ChunkCombinedCodeOffset: ClassVar[cpy.FillType] + ChunkCombinedOffset: ClassVar[cpy.FillType] + ChunkCombinedOffsetOffset: ClassVar[cpy.FillType] + OuterCode: ClassVar[cpy.FillType] + OuterOffset: ClassVar[cpy.FillType] + __members__: ClassVar[dict[str, cpy.FillType]] + def __eq__(self, other: object) -> bool: ... + def __getstate__(self) -> int: ... + def __hash__(self) -> int: ... + def __index__(self) -> int: ... + def __init__(self, value: int) -> None: ... + def __int__(self) -> int: ... + def __ne__(self, other: object) -> bool: ... + def __setstate__(self, state: int) -> NoReturn: ... + @property + def name(self) -> str: ... + @property + def value(self) -> int: ... + +class LineType: + ChunkCombinedCode: ClassVar[cpy.LineType] + ChunkCombinedNan: ClassVar[cpy.LineType] + ChunkCombinedOffset: ClassVar[cpy.LineType] + Separate: ClassVar[cpy.LineType] + SeparateCode: ClassVar[cpy.LineType] + __members__: ClassVar[dict[str, cpy.LineType]] + def __eq__(self, other: object) -> bool: ... + def __getstate__(self) -> int: ... + def __hash__(self) -> int: ... + def __index__(self) -> int: ... + def __init__(self, value: int) -> None: ... + def __int__(self) -> int: ... + def __ne__(self, other: object) -> bool: ... + def __setstate__(self, state: int) -> NoReturn: ... + @property + def name(self) -> str: ... + @property + def value(self) -> int: ... + +class ZInterp: + Linear: ClassVar[cpy.ZInterp] + Log: ClassVar[cpy.ZInterp] + __members__: ClassVar[dict[str, cpy.ZInterp]] + def __eq__(self, other: object) -> bool: ... + def __getstate__(self) -> int: ... + def __hash__(self) -> int: ... + def __index__(self) -> int: ... + def __init__(self, value: int) -> None: ... + def __int__(self) -> int: ... + def __ne__(self, other: object) -> bool: ... + def __setstate__(self, state: int) -> NoReturn: ... + @property + def name(self) -> str: ... + @property + def value(self) -> int: ... + +def max_threads() -> int: ... + +class ContourGenerator: + def create_contour(self, level: float) -> LineReturn: ... + def create_filled_contour(self, lower_level: float, upper_level: float) -> FillReturn: ... + def filled(self, lower_level: float, upper_level: float) -> FillReturn: ... + def lines(self, level: float) -> LineReturn: ... + def multi_filled(self, levels: LevelArray) -> list[FillReturn]: ... + def multi_lines(self, levels: LevelArray) -> list[LineReturn]: ... + @staticmethod + def supports_corner_mask() -> bool: ... + @staticmethod + def supports_fill_type(fill_type: FillType) -> bool: ... + @staticmethod + def supports_line_type(line_type: LineType) -> bool: ... + @staticmethod + def supports_quad_as_tri() -> bool: ... + @staticmethod + def supports_threads() -> bool: ... + @staticmethod + def supports_z_interp() -> bool: ... + @property + def chunk_count(self) -> tuple[int, int]: ... + @property + def chunk_size(self) -> tuple[int, int]: ... + @property + def corner_mask(self) -> bool: ... + @property + def fill_type(self) -> FillType: ... + @property + def line_type(self) -> LineType: ... + @property + def quad_as_tri(self) -> bool: ... + @property + def thread_count(self) -> int: ... + @property + def z_interp(self) -> ZInterp: ... + default_fill_type: cpy.FillType + default_line_type: cpy.LineType + +class Mpl2005ContourGenerator(ContourGenerator): + def __init__( + self, + x: CoordinateArray, + y: CoordinateArray, + z: CoordinateArray, + mask: MaskArray, + *, + x_chunk_size: int = 0, + y_chunk_size: int = 0, + ) -> None: ... + +class Mpl2014ContourGenerator(ContourGenerator): + def __init__( + self, + x: CoordinateArray, + y: CoordinateArray, + z: CoordinateArray, + mask: MaskArray, + *, + corner_mask: bool, + x_chunk_size: int = 0, + y_chunk_size: int = 0, + ) -> None: ... + +class SerialContourGenerator(ContourGenerator): + def __init__( + self, + x: CoordinateArray, + y: CoordinateArray, + z: CoordinateArray, + mask: MaskArray, + *, + corner_mask: bool, + line_type: LineType, + fill_type: FillType, + quad_as_tri: bool, + z_interp: ZInterp, + x_chunk_size: int = 0, + y_chunk_size: int = 0, + ) -> None: ... + def _write_cache(self) -> NoReturn: ... + +class ThreadedContourGenerator(ContourGenerator): + def __init__( + self, + x: CoordinateArray, + y: CoordinateArray, + z: CoordinateArray, + mask: MaskArray, + *, + corner_mask: bool, + line_type: LineType, + fill_type: FillType, + quad_as_tri: bool, + z_interp: ZInterp, + x_chunk_size: int = 0, + y_chunk_size: int = 0, + thread_count: int = 0, + ) -> None: ... + def _write_cache(self) -> None: ... diff --git a/data/miniconda3/lib/python3.13/site-packages/contourpy/_version.py b/data/miniconda3/lib/python3.13/site-packages/contourpy/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..7b1e312007554cf3d9c95081dc04bb15e77d3018 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/contourpy/_version.py @@ -0,0 +1 @@ +__version__ = "1.3.3" diff --git a/data/miniconda3/lib/python3.13/site-packages/contourpy/array.py b/data/miniconda3/lib/python3.13/site-packages/contourpy/array.py new file mode 100644 index 0000000000000000000000000000000000000000..a7054fae1dc2f39b2dc6789e60818b1dd9b49c55 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/contourpy/array.py @@ -0,0 +1,261 @@ +from __future__ import annotations + +from itertools import chain, pairwise +from typing import TYPE_CHECKING + +import numpy as np + +from contourpy.typecheck import check_code_array, check_offset_array, check_point_array +from contourpy.types import CLOSEPOLY, LINETO, MOVETO, code_dtype, offset_dtype, point_dtype + +if TYPE_CHECKING: + import contourpy._contourpy as cpy + + +def codes_from_offsets(offsets: cpy.OffsetArray) -> cpy.CodeArray: + """Determine codes from offsets, assuming they all correspond to closed polygons. + """ + check_offset_array(offsets) + + n = offsets[-1] + codes = np.full(n, LINETO, dtype=code_dtype) + codes[offsets[:-1]] = MOVETO + codes[offsets[1:] - 1] = CLOSEPOLY + return codes + + +def codes_from_offsets_and_points( + offsets: cpy.OffsetArray, + points: cpy.PointArray, +) -> cpy.CodeArray: + """Determine codes from offsets and points, using the equality of the start and end points of + each line to determine if lines are closed or not. + """ + check_offset_array(offsets) + check_point_array(points) + + codes = np.full(len(points), LINETO, dtype=code_dtype) + codes[offsets[:-1]] = MOVETO + + end_offsets = offsets[1:] - 1 + closed = np.all(points[offsets[:-1]] == points[end_offsets], axis=1) + codes[end_offsets[closed]] = CLOSEPOLY + + return codes + + +def codes_from_points(points: cpy.PointArray) -> cpy.CodeArray: + """Determine codes for a single line, using the equality of the start and end points to + determine if the line is closed or not. + """ + check_point_array(points) + + n = len(points) + codes = np.full(n, LINETO, dtype=code_dtype) + codes[0] = MOVETO + if np.all(points[0] == points[-1]): + codes[-1] = CLOSEPOLY + return codes + + +def concat_codes(list_of_codes: list[cpy.CodeArray]) -> cpy.CodeArray: + """Concatenate a list of codes arrays into a single code array. + """ + if not list_of_codes: + raise ValueError("Empty list passed to concat_codes") + + return np.concatenate(list_of_codes, dtype=code_dtype) + + +def concat_codes_or_none(list_of_codes_or_none: list[cpy.CodeArray | None]) -> cpy.CodeArray | None: + """Concatenate a list of codes arrays or None into a single code array or None. + """ + list_of_codes = [codes for codes in list_of_codes_or_none if codes is not None] + if list_of_codes: + return concat_codes(list_of_codes) + else: + return None + + +def concat_offsets(list_of_offsets: list[cpy.OffsetArray]) -> cpy.OffsetArray: + """Concatenate a list of offsets arrays into a single offset array. + """ + if not list_of_offsets: + raise ValueError("Empty list passed to concat_offsets") + + n = len(list_of_offsets) + cumulative = np.cumsum([offsets[-1] for offsets in list_of_offsets], dtype=offset_dtype) + ret: cpy.OffsetArray = np.concatenate( + (list_of_offsets[0], *(list_of_offsets[i+1][1:] + cumulative[i] for i in range(n-1))), + dtype=offset_dtype, + ) + return ret + + +def concat_offsets_or_none( + list_of_offsets_or_none: list[cpy.OffsetArray | None], +) -> cpy.OffsetArray | None: + """Concatenate a list of offsets arrays or None into a single offset array or None. + """ + list_of_offsets = [offsets for offsets in list_of_offsets_or_none if offsets is not None] + if list_of_offsets: + return concat_offsets(list_of_offsets) + else: + return None + + +def concat_points(list_of_points: list[cpy.PointArray]) -> cpy.PointArray: + """Concatenate a list of point arrays into a single point array. + """ + if not list_of_points: + raise ValueError("Empty list passed to concat_points") + + return np.concatenate(list_of_points, dtype=point_dtype) + + +def concat_points_or_none( + list_of_points_or_none: list[cpy.PointArray | None], +) -> cpy.PointArray | None: + """Concatenate a list of point arrays or None into a single point array or None. + """ + list_of_points = [points for points in list_of_points_or_none if points is not None] + if list_of_points: + return concat_points(list_of_points) + else: + return None + + +def concat_points_or_none_with_nan( + list_of_points_or_none: list[cpy.PointArray | None], +) -> cpy.PointArray | None: + """Concatenate a list of points or None into a single point array or None, with NaNs used to + separate each line. + """ + list_of_points = [points for points in list_of_points_or_none if points is not None] + if list_of_points: + return concat_points_with_nan(list_of_points) + else: + return None + + +def concat_points_with_nan(list_of_points: list[cpy.PointArray]) -> cpy.PointArray: + """Concatenate a list of points into a single point array with NaNs used to separate each line. + """ + if not list_of_points: + raise ValueError("Empty list passed to concat_points_with_nan") + + if len(list_of_points) == 1: + return list_of_points[0] + else: + nan_spacer = np.full((1, 2), np.nan, dtype=point_dtype) + list_of_points = [list_of_points[0], + *list(chain(*((nan_spacer, x) for x in list_of_points[1:])))] + return concat_points(list_of_points) + + +def insert_nan_at_offsets(points: cpy.PointArray, offsets: cpy.OffsetArray) -> cpy.PointArray: + """Insert NaNs into a point array at locations specified by an offset array. + """ + check_point_array(points) + check_offset_array(offsets) + + if len(offsets) <= 2: + return points + else: + nan_spacer = np.array([np.nan, np.nan], dtype=point_dtype) + # Convert offsets to int64 to avoid numpy error when mixing signed and unsigned ints. + return np.insert(points, offsets[1:-1].astype(np.int64), nan_spacer, axis=0) + + +def offsets_from_codes(codes: cpy.CodeArray) -> cpy.OffsetArray: + """Determine offsets from codes using locations of MOVETO codes. + """ + check_code_array(codes) + + return np.append(np.nonzero(codes == MOVETO)[0], len(codes)).astype(offset_dtype) + + +def offsets_from_lengths(list_of_points: list[cpy.PointArray]) -> cpy.OffsetArray: + """Determine offsets from lengths of point arrays. + """ + if not list_of_points: + raise ValueError("Empty list passed to offsets_from_lengths") + + return np.cumsum([0] + [len(line) for line in list_of_points], dtype=offset_dtype) + + +def outer_offsets_from_list_of_codes(list_of_codes: list[cpy.CodeArray]) -> cpy.OffsetArray: + """Determine outer offsets from codes using locations of MOVETO codes. + """ + if not list_of_codes: + raise ValueError("Empty list passed to outer_offsets_from_list_of_codes") + + return np.cumsum([0] + [np.count_nonzero(codes == MOVETO) for codes in list_of_codes], + dtype=offset_dtype) + + +def outer_offsets_from_list_of_offsets(list_of_offsets: list[cpy.OffsetArray]) -> cpy.OffsetArray: + """Determine outer offsets from a list of offsets. + """ + if not list_of_offsets: + raise ValueError("Empty list passed to outer_offsets_from_list_of_offsets") + + return np.cumsum([0] + [len(offsets)-1 for offsets in list_of_offsets], dtype=offset_dtype) + + +def remove_nan(points: cpy.PointArray) -> tuple[cpy.PointArray, cpy.OffsetArray]: + """Remove NaN from a points array, also return the offsets corresponding to the NaN removed. + """ + check_point_array(points) + + nan_offsets = np.nonzero(np.isnan(points[:, 0]))[0] + if len(nan_offsets) == 0: + return points, np.array([0, len(points)], dtype=offset_dtype) + else: + points = np.delete(points, nan_offsets, axis=0) + nan_offsets -= np.arange(len(nan_offsets)) + offsets: cpy.OffsetArray = np.empty(len(nan_offsets)+2, dtype=offset_dtype) + offsets[0] = 0 + offsets[1:-1] = nan_offsets + offsets[-1] = len(points) + return points, offsets + + +def split_codes_by_offsets(codes: cpy.CodeArray, offsets: cpy.OffsetArray) -> list[cpy.CodeArray]: + """Split a code array at locations specified by an offset array into a list of code arrays. + """ + check_code_array(codes) + check_offset_array(offsets) + + if len(offsets) > 2: + return np.split(codes, offsets[1:-1]) + else: + return [codes] + + +def split_points_by_offsets( + points: cpy.PointArray, + offsets: cpy.OffsetArray, +) -> list[cpy.PointArray]: + """Split a point array at locations specified by an offset array into a list of point arrays. + """ + check_point_array(points) + check_offset_array(offsets) + + if len(offsets) > 2: + return np.split(points, offsets[1:-1]) + else: + return [points] + + +def split_points_at_nan(points: cpy.PointArray) -> list[cpy.PointArray]: + """Split a points array at NaNs into a list of point arrays. + """ + check_point_array(points) + + nan_offsets = np.nonzero(np.isnan(points[:, 0]))[0] + if len(nan_offsets) == 0: + return [points] + else: + nan_offsets = np.concatenate(([-1], nan_offsets, [len(points)])) + return [points[s+1:e] for s, e in pairwise(nan_offsets)] diff --git a/data/miniconda3/lib/python3.13/site-packages/contourpy/chunk.py b/data/miniconda3/lib/python3.13/site-packages/contourpy/chunk.py new file mode 100644 index 0000000000000000000000000000000000000000..94fded1b161d64adb23748b067630370d8fa2f3c --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/contourpy/chunk.py @@ -0,0 +1,95 @@ +from __future__ import annotations + +import math + + +def calc_chunk_sizes( + chunk_size: int | tuple[int, int] | None, + chunk_count: int | tuple[int, int] | None, + total_chunk_count: int | None, + ny: int, + nx: int, +) -> tuple[int, int]: + """Calculate chunk sizes. + + Args: + chunk_size (int or tuple(int, int), optional): Chunk size in (y, x) directions, or the same + size in both directions if only one is specified. Cannot be negative. + chunk_count (int or tuple(int, int), optional): Chunk count in (y, x) directions, or the + same count in both directions if only one is specified. If less than 1, set to 1. + total_chunk_count (int, optional): Total number of chunks. If less than 1, set to 1. + ny (int): Number of grid points in y-direction. + nx (int): Number of grid points in x-direction. + + Return: + tuple(int, int): Chunk sizes (y_chunk_size, x_chunk_size). + + Note: + Zero or one of ``chunk_size``, ``chunk_count`` and ``total_chunk_count`` should be + specified. + """ + if sum([chunk_size is not None, chunk_count is not None, total_chunk_count is not None]) > 1: + raise ValueError("Only one of chunk_size, chunk_count and total_chunk_count should be set") + + if nx < 2 or ny < 2: + raise ValueError(f"(ny, nx) must be at least (2, 2), not ({ny}, {nx})") + + if total_chunk_count is not None: + max_chunk_count = (nx-1)*(ny-1) + total_chunk_count = min(max(total_chunk_count, 1), max_chunk_count) + if total_chunk_count == 1: + chunk_size = 0 + elif total_chunk_count == max_chunk_count: + chunk_size = (1, 1) + else: + factors = two_factors(total_chunk_count) + if ny > nx: + chunk_count = factors + else: + chunk_count = (factors[1], factors[0]) + + if chunk_count is not None: + if isinstance(chunk_count, tuple): + y_chunk_count, x_chunk_count = chunk_count + else: + y_chunk_count = x_chunk_count = chunk_count + x_chunk_count = min(max(x_chunk_count, 1), nx-1) + y_chunk_count = min(max(y_chunk_count, 1), ny-1) + chunk_size = (math.ceil((ny-1) / y_chunk_count), math.ceil((nx-1) / x_chunk_count)) + + if chunk_size is None: + y_chunk_size = x_chunk_size = 0 + elif isinstance(chunk_size, tuple): + y_chunk_size, x_chunk_size = chunk_size + else: + y_chunk_size = x_chunk_size = chunk_size + + if x_chunk_size < 0 or y_chunk_size < 0: + raise ValueError("chunk_size cannot be negative") + + return y_chunk_size, x_chunk_size + + +def two_factors(n: int) -> tuple[int, int]: + """Split an integer into two integer factors. + + The two factors will be as close as possible to the sqrt of n, and are returned in decreasing + order. Worst case returns (n, 1). + + Args: + n (int): The integer to factorize, must be positive. + + Return: + tuple(int, int): The two factors of n, in decreasing order. + """ + if n < 0: + raise ValueError(f"two_factors expects positive integer not {n}") + + i = math.ceil(math.sqrt(n)) + while n % i != 0: + i -= 1 + j = n // i + if i > j: + return i, j + else: + return j, i diff --git a/data/miniconda3/lib/python3.13/site-packages/contourpy/convert.py b/data/miniconda3/lib/python3.13/site-packages/contourpy/convert.py new file mode 100644 index 0000000000000000000000000000000000000000..ebdb1af8bf2f9b30c2d177dce9adf876dcb32835 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/contourpy/convert.py @@ -0,0 +1,621 @@ +from __future__ import annotations + +from itertools import pairwise +from typing import TYPE_CHECKING, cast + +import numpy as np + +from contourpy._contourpy import FillType, LineType +import contourpy.array as arr +from contourpy.enum_util import as_fill_type, as_line_type +from contourpy.typecheck import check_filled, check_lines +from contourpy.types import MOVETO, offset_dtype + +if TYPE_CHECKING: + import contourpy._contourpy as cpy + + +def _convert_filled_from_OuterCode( + filled: cpy.FillReturn_OuterCode, + fill_type_to: FillType, +) -> cpy.FillReturn: + if fill_type_to == FillType.OuterCode: + return filled + elif fill_type_to == FillType.OuterOffset: + return (filled[0], [arr.offsets_from_codes(codes) for codes in filled[1]]) + + if len(filled[0]) > 0: + points = arr.concat_points(filled[0]) + codes = arr.concat_codes(filled[1]) + else: + points = None + codes = None + + if fill_type_to == FillType.ChunkCombinedCode: + return ([points], [codes]) + elif fill_type_to == FillType.ChunkCombinedOffset: + return ([points], [None if codes is None else arr.offsets_from_codes(codes)]) + elif fill_type_to == FillType.ChunkCombinedCodeOffset: + outer_offsets = None if points is None else arr.offsets_from_lengths(filled[0]) + ret1: cpy.FillReturn_ChunkCombinedCodeOffset = ([points], [codes], [outer_offsets]) + return ret1 + elif fill_type_to == FillType.ChunkCombinedOffsetOffset: + if codes is None: + ret2: cpy.FillReturn_ChunkCombinedOffsetOffset = ([None], [None], [None]) + else: + offsets = arr.offsets_from_codes(codes) + outer_offsets = arr.outer_offsets_from_list_of_codes(filled[1]) + ret2 = ([points], [offsets], [outer_offsets]) + return ret2 + else: + raise ValueError(f"Invalid FillType {fill_type_to}") + + +def _convert_filled_from_OuterOffset( + filled: cpy.FillReturn_OuterOffset, + fill_type_to: FillType, +) -> cpy.FillReturn: + if fill_type_to == FillType.OuterCode: + separate_codes = [arr.codes_from_offsets(offsets) for offsets in filled[1]] + return (filled[0], separate_codes) + elif fill_type_to == FillType.OuterOffset: + return filled + + if len(filled[0]) > 0: + points = arr.concat_points(filled[0]) + offsets = arr.concat_offsets(filled[1]) + else: + points = None + offsets = None + + if fill_type_to == FillType.ChunkCombinedCode: + return ([points], [None if offsets is None else arr.codes_from_offsets(offsets)]) + elif fill_type_to == FillType.ChunkCombinedOffset: + return ([points], [offsets]) + elif fill_type_to == FillType.ChunkCombinedCodeOffset: + if offsets is None: + ret1: cpy.FillReturn_ChunkCombinedCodeOffset = ([None], [None], [None]) + else: + codes = arr.codes_from_offsets(offsets) + outer_offsets = arr.offsets_from_lengths(filled[0]) + ret1 = ([points], [codes], [outer_offsets]) + return ret1 + elif fill_type_to == FillType.ChunkCombinedOffsetOffset: + if points is None: + ret2: cpy.FillReturn_ChunkCombinedOffsetOffset = ([None], [None], [None]) + else: + outer_offsets = arr.outer_offsets_from_list_of_offsets(filled[1]) + ret2 = ([points], [offsets], [outer_offsets]) + return ret2 + else: + raise ValueError(f"Invalid FillType {fill_type_to}") + + +def _convert_filled_from_ChunkCombinedCode( + filled: cpy.FillReturn_ChunkCombinedCode, + fill_type_to: FillType, +) -> cpy.FillReturn: + if fill_type_to == FillType.ChunkCombinedCode: + return filled + elif fill_type_to == FillType.ChunkCombinedOffset: + codes = [None if codes is None else arr.offsets_from_codes(codes) for codes in filled[1]] + return (filled[0], codes) + else: + raise ValueError( + f"Conversion from {FillType.ChunkCombinedCode} to {fill_type_to} not supported") + + +def _convert_filled_from_ChunkCombinedOffset( + filled: cpy.FillReturn_ChunkCombinedOffset, + fill_type_to: FillType, +) -> cpy.FillReturn: + if fill_type_to == FillType.ChunkCombinedCode: + chunk_codes: list[cpy.CodeArray | None] = [] + for points, offsets in zip(*filled): + if points is None: + chunk_codes.append(None) + else: + if TYPE_CHECKING: + assert offsets is not None + chunk_codes.append(arr.codes_from_offsets_and_points(offsets, points)) + return (filled[0], chunk_codes) + elif fill_type_to == FillType.ChunkCombinedOffset: + return filled + else: + raise ValueError( + f"Conversion from {FillType.ChunkCombinedOffset} to {fill_type_to} not supported") + + +def _convert_filled_from_ChunkCombinedCodeOffset( + filled: cpy.FillReturn_ChunkCombinedCodeOffset, + fill_type_to: FillType, +) -> cpy.FillReturn: + if fill_type_to == FillType.OuterCode: + separate_points = [] + separate_codes = [] + for points, codes, outer_offsets in zip(*filled): + if points is not None: + if TYPE_CHECKING: + assert codes is not None + assert outer_offsets is not None + separate_points += arr.split_points_by_offsets(points, outer_offsets) + separate_codes += arr.split_codes_by_offsets(codes, outer_offsets) + return (separate_points, separate_codes) + elif fill_type_to == FillType.OuterOffset: + separate_points = [] + separate_offsets = [] + for points, codes, outer_offsets in zip(*filled): + if points is not None: + if TYPE_CHECKING: + assert codes is not None + assert outer_offsets is not None + separate_points += arr.split_points_by_offsets(points, outer_offsets) + separate_codes = arr.split_codes_by_offsets(codes, outer_offsets) + separate_offsets += [arr.offsets_from_codes(codes) for codes in separate_codes] + return (separate_points, separate_offsets) + elif fill_type_to == FillType.ChunkCombinedCode: + ret1: cpy.FillReturn_ChunkCombinedCode = (filled[0], filled[1]) + return ret1 + elif fill_type_to == FillType.ChunkCombinedOffset: + all_offsets = [None if codes is None else arr.offsets_from_codes(codes) + for codes in filled[1]] + ret2: cpy.FillReturn_ChunkCombinedOffset = (filled[0], all_offsets) + return ret2 + elif fill_type_to == FillType.ChunkCombinedCodeOffset: + return filled + elif fill_type_to == FillType.ChunkCombinedOffsetOffset: + chunk_offsets: list[cpy.OffsetArray | None] = [] + chunk_outer_offsets: list[cpy.OffsetArray | None] = [] + for codes, outer_offsets in zip(*filled[1:]): + if codes is None: + chunk_offsets.append(None) + chunk_outer_offsets.append(None) + else: + if TYPE_CHECKING: + assert outer_offsets is not None + offsets = arr.offsets_from_codes(codes) + outer_offsets = np.array([np.nonzero(offsets == oo)[0][0] for oo in outer_offsets], + dtype=offset_dtype) + chunk_offsets.append(offsets) + chunk_outer_offsets.append(outer_offsets) + ret3: cpy.FillReturn_ChunkCombinedOffsetOffset = ( + filled[0], chunk_offsets, chunk_outer_offsets, + ) + return ret3 + else: + raise ValueError(f"Invalid FillType {fill_type_to}") + + +def _convert_filled_from_ChunkCombinedOffsetOffset( + filled: cpy.FillReturn_ChunkCombinedOffsetOffset, + fill_type_to: FillType, +) -> cpy.FillReturn: + if fill_type_to == FillType.OuterCode: + separate_points = [] + separate_codes = [] + for points, offsets, outer_offsets in zip(*filled): + if points is not None: + if TYPE_CHECKING: + assert offsets is not None + assert outer_offsets is not None + codes = arr.codes_from_offsets_and_points(offsets, points) + outer_offsets = offsets[outer_offsets] + separate_points += arr.split_points_by_offsets(points, outer_offsets) + separate_codes += arr.split_codes_by_offsets(codes, outer_offsets) + return (separate_points, separate_codes) + elif fill_type_to == FillType.OuterOffset: + separate_points = [] + separate_offsets = [] + for points, offsets, outer_offsets in zip(*filled): + if points is not None: + if TYPE_CHECKING: + assert offsets is not None + assert outer_offsets is not None + if len(outer_offsets) > 2: + separate_offsets += [offsets[s:e+1] - offsets[s] for s, e in + pairwise(outer_offsets)] + else: + separate_offsets.append(offsets) + separate_points += arr.split_points_by_offsets(points, offsets[outer_offsets]) + return (separate_points, separate_offsets) + elif fill_type_to == FillType.ChunkCombinedCode: + chunk_codes: list[cpy.CodeArray | None] = [] + for points, offsets, outer_offsets in zip(*filled): + if points is None: + chunk_codes.append(None) + else: + if TYPE_CHECKING: + assert offsets is not None + assert outer_offsets is not None + chunk_codes.append(arr.codes_from_offsets_and_points(offsets, points)) + ret1: cpy.FillReturn_ChunkCombinedCode = (filled[0], chunk_codes) + return ret1 + elif fill_type_to == FillType.ChunkCombinedOffset: + return (filled[0], filled[1]) + elif fill_type_to == FillType.ChunkCombinedCodeOffset: + chunk_codes = [] + chunk_outer_offsets: list[cpy.OffsetArray | None] = [] + for points, offsets, outer_offsets in zip(*filled): + if points is None: + chunk_codes.append(None) + chunk_outer_offsets.append(None) + else: + if TYPE_CHECKING: + assert offsets is not None + assert outer_offsets is not None + chunk_codes.append(arr.codes_from_offsets_and_points(offsets, points)) + chunk_outer_offsets.append(offsets[outer_offsets]) + ret2: cpy.FillReturn_ChunkCombinedCodeOffset = (filled[0], chunk_codes, chunk_outer_offsets) + return ret2 + elif fill_type_to == FillType.ChunkCombinedOffsetOffset: + return filled + else: + raise ValueError(f"Invalid FillType {fill_type_to}") + + +def convert_filled( + filled: cpy.FillReturn, + fill_type_from: FillType | str, + fill_type_to: FillType | str, +) -> cpy.FillReturn: + """Convert filled contours from one :class:`~.FillType` to another. + + Args: + filled (sequence of arrays): Filled contour polygons to convert, such as those returned by + :meth:`.ContourGenerator.filled`. + fill_type_from (FillType or str): :class:`~.FillType` to convert from as enum or + string equivalent. + fill_type_to (FillType or str): :class:`~.FillType` to convert to as enum or string + equivalent. + + Return: + Converted filled contour polygons. + + When converting non-chunked fill types (``FillType.OuterCode`` or ``FillType.OuterOffset``) to + chunked ones, all polygons are placed in the first chunk. When converting in the other + direction, all chunk information is discarded. Converting a fill type that is not aware of the + relationship between outer boundaries and contained holes (``FillType.ChunkCombinedCode`` or + ``FillType.ChunkCombinedOffset``) to one that is will raise a ``ValueError``. + + .. versionadded:: 1.2.0 + """ + fill_type_from = as_fill_type(fill_type_from) + fill_type_to = as_fill_type(fill_type_to) + + check_filled(filled, fill_type_from) + + if fill_type_from == FillType.OuterCode: + if TYPE_CHECKING: + filled = cast(cpy.FillReturn_OuterCode, filled) + return _convert_filled_from_OuterCode(filled, fill_type_to) + elif fill_type_from == FillType.OuterOffset: + if TYPE_CHECKING: + filled = cast(cpy.FillReturn_OuterOffset, filled) + return _convert_filled_from_OuterOffset(filled, fill_type_to) + elif fill_type_from == FillType.ChunkCombinedCode: + if TYPE_CHECKING: + filled = cast(cpy.FillReturn_ChunkCombinedCode, filled) + return _convert_filled_from_ChunkCombinedCode(filled, fill_type_to) + elif fill_type_from == FillType.ChunkCombinedOffset: + if TYPE_CHECKING: + filled = cast(cpy.FillReturn_ChunkCombinedOffset, filled) + return _convert_filled_from_ChunkCombinedOffset(filled, fill_type_to) + elif fill_type_from == FillType.ChunkCombinedCodeOffset: + if TYPE_CHECKING: + filled = cast(cpy.FillReturn_ChunkCombinedCodeOffset, filled) + return _convert_filled_from_ChunkCombinedCodeOffset(filled, fill_type_to) + elif fill_type_from == FillType.ChunkCombinedOffsetOffset: + if TYPE_CHECKING: + filled = cast(cpy.FillReturn_ChunkCombinedOffsetOffset, filled) + return _convert_filled_from_ChunkCombinedOffsetOffset(filled, fill_type_to) + else: + raise ValueError(f"Invalid FillType {fill_type_from}") + + +def _convert_lines_from_Separate( + lines: cpy.LineReturn_Separate, + line_type_to: LineType, +) -> cpy.LineReturn: + if line_type_to == LineType.Separate: + return lines + elif line_type_to == LineType.SeparateCode: + separate_codes = [arr.codes_from_points(line) for line in lines] + return (lines, separate_codes) + elif line_type_to == LineType.ChunkCombinedCode: + if not lines: + ret1: cpy.LineReturn_ChunkCombinedCode = ([None], [None]) + else: + points = arr.concat_points(lines) + offsets = arr.offsets_from_lengths(lines) + codes = arr.codes_from_offsets_and_points(offsets, points) + ret1 = ([points], [codes]) + return ret1 + elif line_type_to == LineType.ChunkCombinedOffset: + if not lines: + ret2: cpy.LineReturn_ChunkCombinedOffset = ([None], [None]) + else: + ret2 = ([arr.concat_points(lines)], [arr.offsets_from_lengths(lines)]) + return ret2 + elif line_type_to == LineType.ChunkCombinedNan: + if not lines: + ret3: cpy.LineReturn_ChunkCombinedNan = ([None],) + else: + ret3 = ([arr.concat_points_with_nan(lines)],) + return ret3 + else: + raise ValueError(f"Invalid LineType {line_type_to}") + + +def _convert_lines_from_SeparateCode( + lines: cpy.LineReturn_SeparateCode, + line_type_to: LineType, +) -> cpy.LineReturn: + if line_type_to == LineType.Separate: + # Drop codes. + return lines[0] + elif line_type_to == LineType.SeparateCode: + return lines + elif line_type_to == LineType.ChunkCombinedCode: + if not lines[0]: + ret1: cpy.LineReturn_ChunkCombinedCode = ([None], [None]) + else: + ret1 = ([arr.concat_points(lines[0])], [arr.concat_codes(lines[1])]) + return ret1 + elif line_type_to == LineType.ChunkCombinedOffset: + if not lines[0]: + ret2: cpy.LineReturn_ChunkCombinedOffset = ([None], [None]) + else: + ret2 = ([arr.concat_points(lines[0])], [arr.offsets_from_lengths(lines[0])]) + return ret2 + elif line_type_to == LineType.ChunkCombinedNan: + if not lines[0]: + ret3: cpy.LineReturn_ChunkCombinedNan = ([None],) + else: + ret3 = ([arr.concat_points_with_nan(lines[0])],) + return ret3 + else: + raise ValueError(f"Invalid LineType {line_type_to}") + + +def _convert_lines_from_ChunkCombinedCode( + lines: cpy.LineReturn_ChunkCombinedCode, + line_type_to: LineType, +) -> cpy.LineReturn: + if line_type_to in (LineType.Separate, LineType.SeparateCode): + separate_lines = [] + for points, codes in zip(*lines): + if points is not None: + if TYPE_CHECKING: + assert codes is not None + split_at = np.nonzero(codes == MOVETO)[0] + if len(split_at) > 1: + separate_lines += np.split(points, split_at[1:]) + else: + separate_lines.append(points) + if line_type_to == LineType.Separate: + return separate_lines + else: + separate_codes = [arr.codes_from_points(line) for line in separate_lines] + return (separate_lines, separate_codes) + elif line_type_to == LineType.ChunkCombinedCode: + return lines + elif line_type_to == LineType.ChunkCombinedOffset: + chunk_offsets = [None if codes is None else arr.offsets_from_codes(codes) + for codes in lines[1]] + return (lines[0], chunk_offsets) + elif line_type_to == LineType.ChunkCombinedNan: + points_nan: list[cpy.PointArray | None] = [] + for points, codes in zip(*lines): + if points is None: + points_nan.append(None) + else: + if TYPE_CHECKING: + assert codes is not None + offsets = arr.offsets_from_codes(codes) + points_nan.append(arr.insert_nan_at_offsets(points, offsets)) + return (points_nan,) + else: + raise ValueError(f"Invalid LineType {line_type_to}") + + +def _convert_lines_from_ChunkCombinedOffset( + lines: cpy.LineReturn_ChunkCombinedOffset, + line_type_to: LineType, +) -> cpy.LineReturn: + if line_type_to in (LineType.Separate, LineType.SeparateCode): + separate_lines = [] + for points, offsets in zip(*lines): + if points is not None: + if TYPE_CHECKING: + assert offsets is not None + separate_lines += arr.split_points_by_offsets(points, offsets) + if line_type_to == LineType.Separate: + return separate_lines + else: + separate_codes = [arr.codes_from_points(line) for line in separate_lines] + return (separate_lines, separate_codes) + elif line_type_to == LineType.ChunkCombinedCode: + chunk_codes: list[cpy.CodeArray | None] = [] + for points, offsets in zip(*lines): + if points is None: + chunk_codes.append(None) + else: + if TYPE_CHECKING: + assert offsets is not None + chunk_codes.append(arr.codes_from_offsets_and_points(offsets, points)) + return (lines[0], chunk_codes) + elif line_type_to == LineType.ChunkCombinedOffset: + return lines + elif line_type_to == LineType.ChunkCombinedNan: + points_nan: list[cpy.PointArray | None] = [] + for points, offsets in zip(*lines): + if points is None: + points_nan.append(None) + else: + if TYPE_CHECKING: + assert offsets is not None + points_nan.append(arr.insert_nan_at_offsets(points, offsets)) + return (points_nan,) + else: + raise ValueError(f"Invalid LineType {line_type_to}") + + +def _convert_lines_from_ChunkCombinedNan( + lines: cpy.LineReturn_ChunkCombinedNan, + line_type_to: LineType, +) -> cpy.LineReturn: + if line_type_to in (LineType.Separate, LineType.SeparateCode): + separate_lines = [] + for points in lines[0]: + if points is not None: + separate_lines += arr.split_points_at_nan(points) + if line_type_to == LineType.Separate: + return separate_lines + else: + separate_codes = [arr.codes_from_points(points) for points in separate_lines] + return (separate_lines, separate_codes) + elif line_type_to == LineType.ChunkCombinedCode: + chunk_points: list[cpy.PointArray | None] = [] + chunk_codes: list[cpy.CodeArray | None] = [] + for points in lines[0]: + if points is None: + chunk_points.append(None) + chunk_codes.append(None) + else: + points, offsets = arr.remove_nan(points) + chunk_points.append(points) + chunk_codes.append(arr.codes_from_offsets_and_points(offsets, points)) + return (chunk_points, chunk_codes) + elif line_type_to == LineType.ChunkCombinedOffset: + chunk_points = [] + chunk_offsets: list[cpy.OffsetArray | None] = [] + for points in lines[0]: + if points is None: + chunk_points.append(None) + chunk_offsets.append(None) + else: + points, offsets = arr.remove_nan(points) + chunk_points.append(points) + chunk_offsets.append(offsets) + return (chunk_points, chunk_offsets) + elif line_type_to == LineType.ChunkCombinedNan: + return lines + else: + raise ValueError(f"Invalid LineType {line_type_to}") + + +def convert_lines( + lines: cpy.LineReturn, + line_type_from: LineType | str, + line_type_to: LineType | str, +) -> cpy.LineReturn: + """Convert contour lines from one :class:`~.LineType` to another. + + Args: + lines (sequence of arrays): Contour lines to convert, such as those returned by + :meth:`.ContourGenerator.lines`. + line_type_from (LineType or str): :class:`~.LineType` to convert from as enum or + string equivalent. + line_type_to (LineType or str): :class:`~.LineType` to convert to as enum or string + equivalent. + + Return: + Converted contour lines. + + When converting non-chunked line types (``LineType.Separate`` or ``LineType.SeparateCode``) to + chunked ones (``LineType.ChunkCombinedCode``, ``LineType.ChunkCombinedOffset`` or + ``LineType.ChunkCombinedNan``), all lines are placed in the first chunk. When converting in the + other direction, all chunk information is discarded. + + .. versionadded:: 1.2.0 + """ + line_type_from = as_line_type(line_type_from) + line_type_to = as_line_type(line_type_to) + + check_lines(lines, line_type_from) + + if line_type_from == LineType.Separate: + if TYPE_CHECKING: + lines = cast(cpy.LineReturn_Separate, lines) + return _convert_lines_from_Separate(lines, line_type_to) + elif line_type_from == LineType.SeparateCode: + if TYPE_CHECKING: + lines = cast(cpy.LineReturn_SeparateCode, lines) + return _convert_lines_from_SeparateCode(lines, line_type_to) + elif line_type_from == LineType.ChunkCombinedCode: + if TYPE_CHECKING: + lines = cast(cpy.LineReturn_ChunkCombinedCode, lines) + return _convert_lines_from_ChunkCombinedCode(lines, line_type_to) + elif line_type_from == LineType.ChunkCombinedOffset: + if TYPE_CHECKING: + lines = cast(cpy.LineReturn_ChunkCombinedOffset, lines) + return _convert_lines_from_ChunkCombinedOffset(lines, line_type_to) + elif line_type_from == LineType.ChunkCombinedNan: + if TYPE_CHECKING: + lines = cast(cpy.LineReturn_ChunkCombinedNan, lines) + return _convert_lines_from_ChunkCombinedNan(lines, line_type_to) + else: + raise ValueError(f"Invalid LineType {line_type_from}") + + +def convert_multi_filled( + multi_filled: list[cpy.FillReturn], + fill_type_from: FillType | str, + fill_type_to: FillType | str, +) -> list[cpy.FillReturn]: + """Convert multiple sets of filled contours from one :class:`~.FillType` to another. + + Args: + multi_filled (nested sequence of arrays): Filled contour polygons to convert, such as those + returned by :meth:`.ContourGenerator.multi_filled`. + fill_type_from (FillType or str): :class:`~.FillType` to convert from as enum or + string equivalent. + fill_type_to (FillType or str): :class:`~.FillType` to convert to as enum or string + equivalent. + + Return: + Converted sets filled contour polygons. + + When converting non-chunked fill types (``FillType.OuterCode`` or ``FillType.OuterOffset``) to + chunked ones, all polygons are placed in the first chunk. When converting in the other + direction, all chunk information is discarded. Converting a fill type that is not aware of the + relationship between outer boundaries and contained holes (``FillType.ChunkCombinedCode`` or + ``FillType.ChunkCombinedOffset``) to one that is will raise a ``ValueError``. + + .. versionadded:: 1.3.0 + """ + fill_type_from = as_fill_type(fill_type_from) + fill_type_to = as_fill_type(fill_type_to) + + return [convert_filled(filled, fill_type_from, fill_type_to) for filled in multi_filled] + + +def convert_multi_lines( + multi_lines: list[cpy.LineReturn], + line_type_from: LineType | str, + line_type_to: LineType | str, +) -> list[cpy.LineReturn]: + """Convert multiple sets of contour lines from one :class:`~.LineType` to another. + + Args: + multi_lines (nested sequence of arrays): Contour lines to convert, such as those returned by + :meth:`.ContourGenerator.multi_lines`. + line_type_from (LineType or str): :class:`~.LineType` to convert from as enum or + string equivalent. + line_type_to (LineType or str): :class:`~.LineType` to convert to as enum or string + equivalent. + + Return: + Converted set of contour lines. + + When converting non-chunked line types (``LineType.Separate`` or ``LineType.SeparateCode``) to + chunked ones (``LineType.ChunkCombinedCode``, ``LineType.ChunkCombinedOffset`` or + ``LineType.ChunkCombinedNan``), all lines are placed in the first chunk. When converting in the + other direction, all chunk information is discarded. + + .. versionadded:: 1.3.0 + """ + line_type_from = as_line_type(line_type_from) + line_type_to = as_line_type(line_type_to) + + return [convert_lines(lines, line_type_from, line_type_to) for lines in multi_lines] diff --git a/data/miniconda3/lib/python3.13/site-packages/contourpy/dechunk.py b/data/miniconda3/lib/python3.13/site-packages/contourpy/dechunk.py new file mode 100644 index 0000000000000000000000000000000000000000..f571b4b5ffbb4801cd687b065314b51a93a1997d --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/contourpy/dechunk.py @@ -0,0 +1,207 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, cast + +from contourpy._contourpy import FillType, LineType +from contourpy.array import ( + concat_codes_or_none, + concat_offsets_or_none, + concat_points_or_none, + concat_points_or_none_with_nan, +) +from contourpy.enum_util import as_fill_type, as_line_type +from contourpy.typecheck import check_filled, check_lines + +if TYPE_CHECKING: + import contourpy._contourpy as cpy + + +def dechunk_filled(filled: cpy.FillReturn, fill_type: FillType | str) -> cpy.FillReturn: + """Return the specified filled contours with chunked data moved into the first chunk. + + Filled contours that are not chunked (``FillType.OuterCode`` and ``FillType.OuterOffset``) and + those that are but only contain a single chunk are returned unmodified. Individual polygons are + unchanged, they are not geometrically combined. + + Args: + filled (sequence of arrays): Filled contour data, such as returned by + :meth:`.ContourGenerator.filled`. + fill_type (FillType or str): Type of :meth:`~.ContourGenerator.filled` as enum or string + equivalent. + + Return: + Filled contours in a single chunk. + + .. versionadded:: 1.2.0 + """ + fill_type = as_fill_type(fill_type) + + if fill_type in (FillType.OuterCode, FillType.OuterOffset): + # No-op if fill_type is not chunked. + return filled + + check_filled(filled, fill_type) + if len(filled[0]) < 2: + # No-op if just one chunk. + return filled + + if TYPE_CHECKING: + filled = cast(cpy.FillReturn_Chunk, filled) + points = concat_points_or_none(filled[0]) + + if fill_type == FillType.ChunkCombinedCode: + if TYPE_CHECKING: + filled = cast(cpy.FillReturn_ChunkCombinedCode, filled) + if points is None: + ret1: cpy.FillReturn_ChunkCombinedCode = ([None], [None]) + else: + ret1 = ([points], [concat_codes_or_none(filled[1])]) + return ret1 + elif fill_type == FillType.ChunkCombinedOffset: + if TYPE_CHECKING: + filled = cast(cpy.FillReturn_ChunkCombinedOffset, filled) + if points is None: + ret2: cpy.FillReturn_ChunkCombinedOffset = ([None], [None]) + else: + ret2 = ([points], [concat_offsets_or_none(filled[1])]) + return ret2 + elif fill_type == FillType.ChunkCombinedCodeOffset: + if TYPE_CHECKING: + filled = cast(cpy.FillReturn_ChunkCombinedCodeOffset, filled) + if points is None: + ret3: cpy.FillReturn_ChunkCombinedCodeOffset = ([None], [None], [None]) + else: + outer_offsets = concat_offsets_or_none(filled[2]) + ret3 = ([points], [concat_codes_or_none(filled[1])], [outer_offsets]) + return ret3 + elif fill_type == FillType.ChunkCombinedOffsetOffset: + if TYPE_CHECKING: + filled = cast(cpy.FillReturn_ChunkCombinedOffsetOffset, filled) + if points is None: + ret4: cpy.FillReturn_ChunkCombinedOffsetOffset = ([None], [None], [None]) + else: + outer_offsets = concat_offsets_or_none(filled[2]) + ret4 = ([points], [concat_offsets_or_none(filled[1])], [outer_offsets]) + return ret4 + else: + raise ValueError(f"Invalid FillType {fill_type}") + + +def dechunk_lines(lines: cpy.LineReturn, line_type: LineType | str) -> cpy.LineReturn: + """Return the specified contour lines with chunked data moved into the first chunk. + + Contour lines that are not chunked (``LineType.Separate`` and ``LineType.SeparateCode``) and + those that are but only contain a single chunk are returned unmodified. Individual lines are + unchanged, they are not geometrically combined. + + Args: + lines (sequence of arrays): Contour line data, such as returned by + :meth:`.ContourGenerator.lines`. + line_type (LineType or str): Type of :meth:`~.ContourGenerator.lines` as enum or string + equivalent. + + Return: + Contour lines in a single chunk. + + .. versionadded:: 1.2.0 + """ + line_type = as_line_type(line_type) + + if line_type in (LineType.Separate, LineType.SeparateCode): + # No-op if line_type is not chunked. + return lines + + check_lines(lines, line_type) + if len(lines[0]) < 2: + # No-op if just one chunk. + return lines + + if TYPE_CHECKING: + lines = cast(cpy.LineReturn_Chunk, lines) + + if line_type == LineType.ChunkCombinedCode: + if TYPE_CHECKING: + lines = cast(cpy.LineReturn_ChunkCombinedCode, lines) + points = concat_points_or_none(lines[0]) + if points is None: + ret1: cpy.LineReturn_ChunkCombinedCode = ([None], [None]) + else: + ret1 = ([points], [concat_codes_or_none(lines[1])]) + return ret1 + elif line_type == LineType.ChunkCombinedOffset: + if TYPE_CHECKING: + lines = cast(cpy.LineReturn_ChunkCombinedOffset, lines) + points = concat_points_or_none(lines[0]) + if points is None: + ret2: cpy.LineReturn_ChunkCombinedOffset = ([None], [None]) + else: + ret2 = ([points], [concat_offsets_or_none(lines[1])]) + return ret2 + elif line_type == LineType.ChunkCombinedNan: + if TYPE_CHECKING: + lines = cast(cpy.LineReturn_ChunkCombinedNan, lines) + points = concat_points_or_none_with_nan(lines[0]) + ret3: cpy.LineReturn_ChunkCombinedNan = ([points],) + return ret3 + else: + raise ValueError(f"Invalid LineType {line_type}") + + +def dechunk_multi_filled( + multi_filled: list[cpy.FillReturn], + fill_type: FillType | str, +) -> list[cpy.FillReturn]: + """Return multiple sets of filled contours with chunked data moved into the first chunks. + + Filled contours that are not chunked (``FillType.OuterCode`` and ``FillType.OuterOffset``) and + those that are but only contain a single chunk are returned unmodified. Individual polygons are + unchanged, they are not geometrically combined. + + Args: + multi_filled (nested sequence of arrays): Filled contour data, such as returned by + :meth:`.ContourGenerator.multi_filled`. + fill_type (FillType or str): Type of :meth:`~.ContourGenerator.filled` as enum or string + equivalent. + + Return: + Multiple sets of filled contours in a single chunk. + + .. versionadded:: 1.3.0 + """ + fill_type = as_fill_type(fill_type) + + if fill_type in (FillType.OuterCode, FillType.OuterOffset): + # No-op if fill_type is not chunked. + return multi_filled + + return [dechunk_filled(filled, fill_type) for filled in multi_filled] + + +def dechunk_multi_lines( + multi_lines: list[cpy.LineReturn], + line_type: LineType | str, +) -> list[cpy.LineReturn]: + """Return multiple sets of contour lines with all chunked data moved into the first chunks. + + Contour lines that are not chunked (``LineType.Separate`` and ``LineType.SeparateCode``) and + those that are but only contain a single chunk are returned unmodified. Individual lines are + unchanged, they are not geometrically combined. + + Args: + multi_lines (nested sequence of arrays): Contour line data, such as returned by + :meth:`.ContourGenerator.multi_lines`. + line_type (LineType or str): Type of :meth:`~.ContourGenerator.lines` as enum or string + equivalent. + + Return: + Multiple sets of contour lines in a single chunk. + + .. versionadded:: 1.3.0 + """ + line_type = as_line_type(line_type) + + if line_type in (LineType.Separate, LineType.SeparateCode): + # No-op if line_type is not chunked. + return multi_lines + + return [dechunk_lines(lines, line_type) for lines in multi_lines] diff --git a/data/miniconda3/lib/python3.13/site-packages/contourpy/enum_util.py b/data/miniconda3/lib/python3.13/site-packages/contourpy/enum_util.py new file mode 100644 index 0000000000000000000000000000000000000000..14229abebf7e342a2834ffec2a0ad427a727fa5c --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/contourpy/enum_util.py @@ -0,0 +1,57 @@ +from __future__ import annotations + +from contourpy._contourpy import FillType, LineType, ZInterp + + +def as_fill_type(fill_type: FillType | str) -> FillType: + """Coerce a FillType or string value to a FillType. + + Args: + fill_type (FillType or str): Value to convert. + + Return: + FillType: Converted value. + """ + if isinstance(fill_type, str): + try: + return FillType.__members__[fill_type] + except KeyError as e: + raise ValueError(f"'{fill_type}' is not a valid FillType") from e + else: + return fill_type + + +def as_line_type(line_type: LineType | str) -> LineType: + """Coerce a LineType or string value to a LineType. + + Args: + line_type (LineType or str): Value to convert. + + Return: + LineType: Converted value. + """ + if isinstance(line_type, str): + try: + return LineType.__members__[line_type] + except KeyError as e: + raise ValueError(f"'{line_type}' is not a valid LineType") from e + else: + return line_type + + +def as_z_interp(z_interp: ZInterp | str) -> ZInterp: + """Coerce a ZInterp or string value to a ZInterp. + + Args: + z_interp (ZInterp or str): Value to convert. + + Return: + ZInterp: Converted value. + """ + if isinstance(z_interp, str): + try: + return ZInterp.__members__[z_interp] + except KeyError as e: + raise ValueError(f"'{z_interp}' is not a valid ZInterp") from e + else: + return z_interp diff --git a/data/miniconda3/lib/python3.13/site-packages/contourpy/py.typed b/data/miniconda3/lib/python3.13/site-packages/contourpy/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/lib/python3.13/site-packages/contourpy/typecheck.py b/data/miniconda3/lib/python3.13/site-packages/contourpy/typecheck.py new file mode 100644 index 0000000000000000000000000000000000000000..23fbd54856a96f6b6b60b8557c76936f615a9cdc --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/contourpy/typecheck.py @@ -0,0 +1,203 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, cast + +import numpy as np + +from contourpy import FillType, LineType +from contourpy.enum_util import as_fill_type, as_line_type +from contourpy.types import MOVETO, code_dtype, offset_dtype, point_dtype + +if TYPE_CHECKING: + import contourpy._contourpy as cpy + + +# Minimalist array-checking functions that check dtype, ndims and shape only. +# They do not walk the arrays to check the contents for performance reasons. +def check_code_array(codes: Any) -> None: + if not isinstance(codes, np.ndarray): + raise TypeError(f"Expected numpy array not {type(codes)}") + if codes.dtype != code_dtype: + raise ValueError(f"Expected numpy array of dtype {code_dtype} not {codes.dtype}") + if not (codes.ndim == 1 and len(codes) > 1): + raise ValueError(f"Expected numpy array of shape (?,) not {codes.shape}") + if codes[0] != MOVETO: + raise ValueError(f"First element of code array must be {MOVETO}, not {codes[0]}") + + +def check_offset_array(offsets: Any) -> None: + if not isinstance(offsets, np.ndarray): + raise TypeError(f"Expected numpy array not {type(offsets)}") + if offsets.dtype != offset_dtype: + raise ValueError(f"Expected numpy array of dtype {offset_dtype} not {offsets.dtype}") + if not (offsets.ndim == 1 and len(offsets) > 1): + raise ValueError(f"Expected numpy array of shape (?,) not {offsets.shape}") + if offsets[0] != 0: + raise ValueError(f"First element of offset array must be 0, not {offsets[0]}") + + +def check_point_array(points: Any) -> None: + if not isinstance(points, np.ndarray): + raise TypeError(f"Expected numpy array not {type(points)}") + if points.dtype != point_dtype: + raise ValueError(f"Expected numpy array of dtype {point_dtype} not {points.dtype}") + if not (points.ndim == 2 and points.shape[1] ==2 and points.shape[0] > 1): + raise ValueError(f"Expected numpy array of shape (?, 2) not {points.shape}") + + +def _check_tuple_of_lists_with_same_length( + maybe_tuple: Any, + tuple_length: int, + allow_empty_lists: bool = True, +) -> None: + if not isinstance(maybe_tuple, tuple): + raise TypeError(f"Expected tuple not {type(maybe_tuple)}") + if len(maybe_tuple) != tuple_length: + raise ValueError(f"Expected tuple of length {tuple_length} not {len(maybe_tuple)}") + for maybe_list in maybe_tuple: + if not isinstance(maybe_list, list): + msg = f"Expected tuple to contain {tuple_length} lists but found a {type(maybe_list)}" + raise TypeError(msg) + lengths = [len(item) for item in maybe_tuple] + if len(set(lengths)) != 1: + msg = f"Expected {tuple_length} lists with same length but lengths are {lengths}" + raise ValueError(msg) + if not allow_empty_lists and lengths[0] == 0: + raise ValueError(f"Expected {tuple_length} non-empty lists") + + +def check_filled(filled: cpy.FillReturn, fill_type: FillType | str) -> None: + fill_type = as_fill_type(fill_type) + + if fill_type == FillType.OuterCode: + if TYPE_CHECKING: + filled = cast(cpy.FillReturn_OuterCode, filled) + _check_tuple_of_lists_with_same_length(filled, 2) + for i, (points, codes) in enumerate(zip(*filled)): + check_point_array(points) + check_code_array(codes) + if len(points) != len(codes): + raise ValueError(f"Points and codes have different lengths in polygon {i}") + elif fill_type == FillType.OuterOffset: + if TYPE_CHECKING: + filled = cast(cpy.FillReturn_OuterOffset, filled) + _check_tuple_of_lists_with_same_length(filled, 2) + for i, (points, offsets) in enumerate(zip(*filled)): + check_point_array(points) + check_offset_array(offsets) + if offsets[-1] != len(points): + raise ValueError(f"Inconsistent points and offsets in polygon {i}") + elif fill_type == FillType.ChunkCombinedCode: + if TYPE_CHECKING: + filled = cast(cpy.FillReturn_ChunkCombinedCode, filled) + _check_tuple_of_lists_with_same_length(filled, 2, allow_empty_lists=False) + for chunk, (points_or_none, codes_or_none) in enumerate(zip(*filled)): + if points_or_none is not None and codes_or_none is not None: + check_point_array(points_or_none) + check_code_array(codes_or_none) + if len(points_or_none) != len(codes_or_none): + raise ValueError(f"Points and codes have different lengths in chunk {chunk}") + elif not (points_or_none is None and codes_or_none is None): + raise ValueError(f"Inconsistent Nones in chunk {chunk}") + elif fill_type == FillType.ChunkCombinedOffset: + if TYPE_CHECKING: + filled = cast(cpy.FillReturn_ChunkCombinedOffset, filled) + _check_tuple_of_lists_with_same_length(filled, 2, allow_empty_lists=False) + for chunk, (points_or_none, offsets_or_none) in enumerate(zip(*filled)): + if points_or_none is not None and offsets_or_none is not None: + check_point_array(points_or_none) + check_offset_array(offsets_or_none) + if offsets_or_none[-1] != len(points_or_none): + raise ValueError(f"Inconsistent points and offsets in chunk {chunk}") + elif not (points_or_none is None and offsets_or_none is None): + raise ValueError(f"Inconsistent Nones in chunk {chunk}") + elif fill_type == FillType.ChunkCombinedCodeOffset: + if TYPE_CHECKING: + filled = cast(cpy.FillReturn_ChunkCombinedCodeOffset, filled) + _check_tuple_of_lists_with_same_length(filled, 3, allow_empty_lists=False) + for i, (points_or_none, codes_or_none, outer_offsets_or_none) in enumerate(zip(*filled)): + if (points_or_none is not None and codes_or_none is not None and + outer_offsets_or_none is not None): + check_point_array(points_or_none) + check_code_array(codes_or_none) + check_offset_array(outer_offsets_or_none) + if len(codes_or_none) != len(points_or_none): + raise ValueError(f"Points and codes have different lengths in chunk {i}") + if outer_offsets_or_none[-1] != len(codes_or_none): + raise ValueError(f"Inconsistent codes and outer_offsets in chunk {i}") + elif not (points_or_none is None and codes_or_none is None and + outer_offsets_or_none is None): + raise ValueError(f"Inconsistent Nones in chunk {i}") + elif fill_type == FillType.ChunkCombinedOffsetOffset: + if TYPE_CHECKING: + filled = cast(cpy.FillReturn_ChunkCombinedOffsetOffset, filled) + _check_tuple_of_lists_with_same_length(filled, 3, allow_empty_lists=False) + for i, (points_or_none, offsets_or_none, outer_offsets_or_none) in enumerate(zip(*filled)): + if (points_or_none is not None and offsets_or_none is not None and + outer_offsets_or_none is not None): + check_point_array(points_or_none) + check_offset_array(offsets_or_none) + check_offset_array(outer_offsets_or_none) + if offsets_or_none[-1] != len(points_or_none): + raise ValueError(f"Inconsistent points and offsets in chunk {i}") + if outer_offsets_or_none[-1] != len(offsets_or_none) - 1: + raise ValueError(f"Inconsistent offsets and outer_offsets in chunk {i}") + elif not (points_or_none is None and offsets_or_none is None and + outer_offsets_or_none is None): + raise ValueError(f"Inconsistent Nones in chunk {i}") + else: + raise ValueError(f"Invalid FillType {fill_type}") + + +def check_lines(lines: cpy.LineReturn, line_type: LineType | str) -> None: + line_type = as_line_type(line_type) + + if line_type == LineType.Separate: + if TYPE_CHECKING: + lines = cast(cpy.LineReturn_Separate, lines) + if not isinstance(lines, list): + raise TypeError(f"Expected list not {type(lines)}") + for points in lines: + check_point_array(points) + elif line_type == LineType.SeparateCode: + if TYPE_CHECKING: + lines = cast(cpy.LineReturn_SeparateCode, lines) + _check_tuple_of_lists_with_same_length(lines, 2) + for i, (points, codes) in enumerate(zip(*lines)): + check_point_array(points) + check_code_array(codes) + if len(points) != len(codes): + raise ValueError(f"Points and codes have different lengths in line {i}") + elif line_type == LineType.ChunkCombinedCode: + if TYPE_CHECKING: + lines = cast(cpy.LineReturn_ChunkCombinedCode, lines) + _check_tuple_of_lists_with_same_length(lines, 2, allow_empty_lists=False) + for chunk, (points_or_none, codes_or_none) in enumerate(zip(*lines)): + if points_or_none is not None and codes_or_none is not None: + check_point_array(points_or_none) + check_code_array(codes_or_none) + if len(points_or_none) != len(codes_or_none): + raise ValueError(f"Points and codes have different lengths in chunk {chunk}") + elif not (points_or_none is None and codes_or_none is None): + raise ValueError(f"Inconsistent Nones in chunk {chunk}") + elif line_type == LineType.ChunkCombinedOffset: + if TYPE_CHECKING: + lines = cast(cpy.LineReturn_ChunkCombinedOffset, lines) + _check_tuple_of_lists_with_same_length(lines, 2, allow_empty_lists=False) + for chunk, (points_or_none, offsets_or_none) in enumerate(zip(*lines)): + if points_or_none is not None and offsets_or_none is not None: + check_point_array(points_or_none) + check_offset_array(offsets_or_none) + if offsets_or_none[-1] != len(points_or_none): + raise ValueError(f"Inconsistent points and offsets in chunk {chunk}") + elif not (points_or_none is None and offsets_or_none is None): + raise ValueError(f"Inconsistent Nones in chunk {chunk}") + elif line_type == LineType.ChunkCombinedNan: + if TYPE_CHECKING: + lines = cast(cpy.LineReturn_ChunkCombinedNan, lines) + _check_tuple_of_lists_with_same_length(lines, 1, allow_empty_lists=False) + for _chunk, points_or_none in enumerate(lines[0]): + if points_or_none is not None: + check_point_array(points_or_none) + else: + raise ValueError(f"Invalid LineType {line_type}") diff --git a/data/miniconda3/lib/python3.13/site-packages/contourpy/types.py b/data/miniconda3/lib/python3.13/site-packages/contourpy/types.py new file mode 100644 index 0000000000000000000000000000000000000000..e704b98eac0736d83586c66803db6b79cdfc5967 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/contourpy/types.py @@ -0,0 +1,13 @@ +from __future__ import annotations + +import numpy as np + +# dtypes of arrays returned by ContourPy. +point_dtype = np.float64 +code_dtype = np.uint8 +offset_dtype = np.uint32 + +# Kind codes used in Matplotlib Paths. +MOVETO = 1 +LINETO = 2 +CLOSEPOLY = 79 diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/__about__.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/__about__.py new file mode 100644 index 0000000000000000000000000000000000000000..a81162845df5e06072148ffc10631da4f10a0980 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/__about__.py @@ -0,0 +1,17 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +__all__ = [ + "__author__", + "__copyright__", + "__version__", +] + +__version__ = "46.0.3" + + +__author__ = "The Python Cryptographic Authority and individual contributors" +__copyright__ = f"Copyright 2013-2025 {__author__}" diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/__init__.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d374f752dfd53c6f9a12c69309fdcb6eee765251 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/__init__.py @@ -0,0 +1,13 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography.__about__ import __author__, __copyright__, __version__ + +__all__ = [ + "__author__", + "__copyright__", + "__version__", +] diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/exceptions.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..fe125ea9a763ad731ba99e4761d6623e1d2c639c --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/exceptions.py @@ -0,0 +1,52 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import typing + +from cryptography.hazmat.bindings._rust import exceptions as rust_exceptions + +if typing.TYPE_CHECKING: + from cryptography.hazmat.bindings._rust import openssl as rust_openssl + +_Reasons = rust_exceptions._Reasons + + +class UnsupportedAlgorithm(Exception): + def __init__(self, message: str, reason: _Reasons | None = None) -> None: + super().__init__(message) + self._reason = reason + + +class AlreadyFinalized(Exception): + pass + + +class AlreadyUpdated(Exception): + pass + + +class NotYetFinalized(Exception): + pass + + +class InvalidTag(Exception): + pass + + +class InvalidSignature(Exception): + pass + + +class InternalError(Exception): + def __init__( + self, msg: str, err_code: list[rust_openssl.OpenSSLError] + ) -> None: + super().__init__(msg) + self.err_code = err_code + + +class InvalidKey(Exception): + pass diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/fernet.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/fernet.py new file mode 100644 index 0000000000000000000000000000000000000000..c6744ae384e3497d2855b32398f8ee59b972f371 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/fernet.py @@ -0,0 +1,224 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import base64 +import binascii +import os +import time +import typing +from collections.abc import Iterable + +from cryptography import utils +from cryptography.exceptions import InvalidSignature +from cryptography.hazmat.primitives import hashes, padding +from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes +from cryptography.hazmat.primitives.hmac import HMAC + + +class InvalidToken(Exception): + pass + + +_MAX_CLOCK_SKEW = 60 + + +class Fernet: + def __init__( + self, + key: bytes | str, + backend: typing.Any = None, + ) -> None: + try: + key = base64.urlsafe_b64decode(key) + except binascii.Error as exc: + raise ValueError( + "Fernet key must be 32 url-safe base64-encoded bytes." + ) from exc + if len(key) != 32: + raise ValueError( + "Fernet key must be 32 url-safe base64-encoded bytes." + ) + + self._signing_key = key[:16] + self._encryption_key = key[16:] + + @classmethod + def generate_key(cls) -> bytes: + return base64.urlsafe_b64encode(os.urandom(32)) + + def encrypt(self, data: bytes) -> bytes: + return self.encrypt_at_time(data, int(time.time())) + + def encrypt_at_time(self, data: bytes, current_time: int) -> bytes: + iv = os.urandom(16) + return self._encrypt_from_parts(data, current_time, iv) + + def _encrypt_from_parts( + self, data: bytes, current_time: int, iv: bytes + ) -> bytes: + utils._check_bytes("data", data) + + padder = padding.PKCS7(algorithms.AES.block_size).padder() + padded_data = padder.update(data) + padder.finalize() + encryptor = Cipher( + algorithms.AES(self._encryption_key), + modes.CBC(iv), + ).encryptor() + ciphertext = encryptor.update(padded_data) + encryptor.finalize() + + basic_parts = ( + b"\x80" + + current_time.to_bytes(length=8, byteorder="big") + + iv + + ciphertext + ) + + h = HMAC(self._signing_key, hashes.SHA256()) + h.update(basic_parts) + hmac = h.finalize() + return base64.urlsafe_b64encode(basic_parts + hmac) + + def decrypt(self, token: bytes | str, ttl: int | None = None) -> bytes: + timestamp, data = Fernet._get_unverified_token_data(token) + if ttl is None: + time_info = None + else: + time_info = (ttl, int(time.time())) + return self._decrypt_data(data, timestamp, time_info) + + def decrypt_at_time( + self, token: bytes | str, ttl: int, current_time: int + ) -> bytes: + if ttl is None: + raise ValueError( + "decrypt_at_time() can only be used with a non-None ttl" + ) + timestamp, data = Fernet._get_unverified_token_data(token) + return self._decrypt_data(data, timestamp, (ttl, current_time)) + + def extract_timestamp(self, token: bytes | str) -> int: + timestamp, data = Fernet._get_unverified_token_data(token) + # Verify the token was not tampered with. + self._verify_signature(data) + return timestamp + + @staticmethod + def _get_unverified_token_data(token: bytes | str) -> tuple[int, bytes]: + if not isinstance(token, (str, bytes)): + raise TypeError("token must be bytes or str") + + try: + data = base64.urlsafe_b64decode(token) + except (TypeError, binascii.Error): + raise InvalidToken + + if not data or data[0] != 0x80: + raise InvalidToken + + if len(data) < 9: + raise InvalidToken + + timestamp = int.from_bytes(data[1:9], byteorder="big") + return timestamp, data + + def _verify_signature(self, data: bytes) -> None: + h = HMAC(self._signing_key, hashes.SHA256()) + h.update(data[:-32]) + try: + h.verify(data[-32:]) + except InvalidSignature: + raise InvalidToken + + def _decrypt_data( + self, + data: bytes, + timestamp: int, + time_info: tuple[int, int] | None, + ) -> bytes: + if time_info is not None: + ttl, current_time = time_info + if timestamp + ttl < current_time: + raise InvalidToken + + if current_time + _MAX_CLOCK_SKEW < timestamp: + raise InvalidToken + + self._verify_signature(data) + + iv = data[9:25] + ciphertext = data[25:-32] + decryptor = Cipher( + algorithms.AES(self._encryption_key), modes.CBC(iv) + ).decryptor() + plaintext_padded = decryptor.update(ciphertext) + try: + plaintext_padded += decryptor.finalize() + except ValueError: + raise InvalidToken + unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder() + + unpadded = unpadder.update(plaintext_padded) + try: + unpadded += unpadder.finalize() + except ValueError: + raise InvalidToken + return unpadded + + +class MultiFernet: + def __init__(self, fernets: Iterable[Fernet]): + fernets = list(fernets) + if not fernets: + raise ValueError( + "MultiFernet requires at least one Fernet instance" + ) + self._fernets = fernets + + def encrypt(self, msg: bytes) -> bytes: + return self.encrypt_at_time(msg, int(time.time())) + + def encrypt_at_time(self, msg: bytes, current_time: int) -> bytes: + return self._fernets[0].encrypt_at_time(msg, current_time) + + def rotate(self, msg: bytes | str) -> bytes: + timestamp, data = Fernet._get_unverified_token_data(msg) + for f in self._fernets: + try: + p = f._decrypt_data(data, timestamp, None) + break + except InvalidToken: + pass + else: + raise InvalidToken + + iv = os.urandom(16) + return self._fernets[0]._encrypt_from_parts(p, timestamp, iv) + + def decrypt(self, msg: bytes | str, ttl: int | None = None) -> bytes: + for f in self._fernets: + try: + return f.decrypt(msg, ttl) + except InvalidToken: + pass + raise InvalidToken + + def decrypt_at_time( + self, msg: bytes | str, ttl: int, current_time: int + ) -> bytes: + for f in self._fernets: + try: + return f.decrypt_at_time(msg, ttl, current_time) + except InvalidToken: + pass + raise InvalidToken + + def extract_timestamp(self, msg: bytes | str) -> int: + for f in self._fernets: + try: + return f.extract_timestamp(msg) + except InvalidToken: + pass + raise InvalidToken diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/py.typed b/data/miniconda3/lib/python3.13/site-packages/cryptography/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/utils.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a0fc3b1da231d6a81328839cd0236d9eea3b00a0 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/utils.py @@ -0,0 +1,137 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import enum +import sys +import types +import typing +import warnings +from collections.abc import Callable, Sequence + + +# We use a UserWarning subclass, instead of DeprecationWarning, because CPython +# decided deprecation warnings should be invisible by default. +class CryptographyDeprecationWarning(UserWarning): + pass + + +# Several APIs were deprecated with no specific end-of-life date because of the +# ubiquity of their use. They should not be removed until we agree on when that +# cycle ends. +DeprecatedIn36 = CryptographyDeprecationWarning +DeprecatedIn40 = CryptographyDeprecationWarning +DeprecatedIn41 = CryptographyDeprecationWarning +DeprecatedIn42 = CryptographyDeprecationWarning +DeprecatedIn43 = CryptographyDeprecationWarning + + +# If you're wondering why we don't use `Buffer`, it's because `Buffer` would +# be more accurately named: Bufferable. It means something which has an +# `__buffer__`. Which means you can't actually treat the result as a buffer +# (and do things like take a `len()`). +if sys.version_info >= (3, 9): + Buffer = typing.Union[bytes, bytearray, memoryview] +else: + Buffer = typing.ByteString + + +def _check_bytes(name: str, value: bytes) -> None: + if not isinstance(value, bytes): + raise TypeError(f"{name} must be bytes") + + +def _check_byteslike(name: str, value: Buffer) -> None: + try: + memoryview(value) + except TypeError: + raise TypeError(f"{name} must be bytes-like") + + +def int_to_bytes(integer: int, length: int | None = None) -> bytes: + if length == 0: + raise ValueError("length argument can't be 0") + return integer.to_bytes( + length or (integer.bit_length() + 7) // 8 or 1, "big" + ) + + +class InterfaceNotImplemented(Exception): + pass + + +class _DeprecatedValue: + def __init__(self, value: object, message: str, warning_class): + self.value = value + self.message = message + self.warning_class = warning_class + + +class _ModuleWithDeprecations(types.ModuleType): + def __init__(self, module: types.ModuleType): + super().__init__(module.__name__) + self.__dict__["_module"] = module + + def __getattr__(self, attr: str) -> object: + obj = getattr(self._module, attr) + if isinstance(obj, _DeprecatedValue): + warnings.warn(obj.message, obj.warning_class, stacklevel=2) + obj = obj.value + return obj + + def __setattr__(self, attr: str, value: object) -> None: + setattr(self._module, attr, value) + + def __delattr__(self, attr: str) -> None: + obj = getattr(self._module, attr) + if isinstance(obj, _DeprecatedValue): + warnings.warn(obj.message, obj.warning_class, stacklevel=2) + + delattr(self._module, attr) + + def __dir__(self) -> Sequence[str]: + return ["_module", *dir(self._module)] + + +def deprecated( + value: object, + module_name: str, + message: str, + warning_class: type[Warning], + name: str | None = None, +) -> _DeprecatedValue: + module = sys.modules[module_name] + if not isinstance(module, _ModuleWithDeprecations): + sys.modules[module_name] = module = _ModuleWithDeprecations(module) + dv = _DeprecatedValue(value, message, warning_class) + # Maintain backwards compatibility with `name is None` for pyOpenSSL. + if name is not None: + setattr(module, name, dv) + return dv + + +def cached_property(func: Callable) -> property: + cached_name = f"_cached_{func}" + sentinel = object() + + def inner(instance: object): + cache = getattr(instance, cached_name, sentinel) + if cache is not sentinel: + return cache + result = func(instance) + setattr(instance, cached_name, result) + return result + + return property(inner) + + +# Python 3.10 changed representation of enums. We use well-defined object +# representation and string representation from Python 3.9. +class Enum(enum.Enum): + def __repr__(self) -> str: + return f"<{self.__class__.__name__}.{self._name_}: {self._value_!r}>" + + def __str__(self) -> str: + return f"{self.__class__.__name__}.{self._name_}" diff --git a/data/miniconda3/lib/python3.13/site-packages/cycler-0.12.1.dist-info/INSTALLER b/data/miniconda3/lib/python3.13/site-packages/cycler-0.12.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cycler-0.12.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/data/miniconda3/lib/python3.13/site-packages/cycler-0.12.1.dist-info/LICENSE b/data/miniconda3/lib/python3.13/site-packages/cycler-0.12.1.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d41d808995af2d59db2496a3ae772ca3d849cab2 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cycler-0.12.1.dist-info/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2015, matplotlib project +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the matplotlib project nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/data/miniconda3/lib/python3.13/site-packages/cycler-0.12.1.dist-info/METADATA b/data/miniconda3/lib/python3.13/site-packages/cycler-0.12.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..e81ab4fa3c9649ef7bc6355d1042f0344c90d83b --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cycler-0.12.1.dist-info/METADATA @@ -0,0 +1,78 @@ +Metadata-Version: 2.1 +Name: cycler +Version: 0.12.1 +Summary: Composable style cycles +Author-email: Thomas A Caswell +License: Copyright (c) 2015, matplotlib project + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + * Neither the name of the matplotlib project nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +Project-URL: homepage, https://matplotlib.org/cycler/ +Project-URL: repository, https://github.com/matplotlib/cycler +Keywords: cycle kwargs +Classifier: License :: OSI Approved :: BSD License +Classifier: Development Status :: 4 - Beta +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3 :: Only +Requires-Python: >=3.8 +Description-Content-Type: text/x-rst +License-File: LICENSE +Provides-Extra: docs +Requires-Dist: ipython ; extra == 'docs' +Requires-Dist: matplotlib ; extra == 'docs' +Requires-Dist: numpydoc ; extra == 'docs' +Requires-Dist: sphinx ; extra == 'docs' +Provides-Extra: tests +Requires-Dist: pytest ; extra == 'tests' +Requires-Dist: pytest-cov ; extra == 'tests' +Requires-Dist: pytest-xdist ; extra == 'tests' + +|PyPi|_ |Conda|_ |Supported Python versions|_ |GitHub Actions|_ |Codecov|_ + +.. |PyPi| image:: https://img.shields.io/pypi/v/cycler.svg?style=flat +.. _PyPi: https://pypi.python.org/pypi/cycler + +.. |Conda| image:: https://img.shields.io/conda/v/conda-forge/cycler +.. _Conda: https://anaconda.org/conda-forge/cycler + +.. |Supported Python versions| image:: https://img.shields.io/pypi/pyversions/cycler.svg +.. _Supported Python versions: https://pypi.python.org/pypi/cycler + +.. |GitHub Actions| image:: https://github.com/matplotlib/cycler/actions/workflows/tests.yml/badge.svg +.. _GitHub Actions: https://github.com/matplotlib/cycler/actions + +.. |Codecov| image:: https://codecov.io/github/matplotlib/cycler/badge.svg?branch=main&service=github +.. _Codecov: https://codecov.io/github/matplotlib/cycler?branch=main + +cycler: composable cycles +========================= + +Docs: https://matplotlib.org/cycler/ diff --git a/data/miniconda3/lib/python3.13/site-packages/cycler-0.12.1.dist-info/RECORD b/data/miniconda3/lib/python3.13/site-packages/cycler-0.12.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..6757d124bfd43c4b0b98508a2f345bbf685e54a0 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cycler-0.12.1.dist-info/RECORD @@ -0,0 +1,9 @@ +cycler-0.12.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +cycler-0.12.1.dist-info/LICENSE,sha256=8SGBQ9dm2j_qZvEzlrfxXfRqgzA_Kb-Wum6Y601C9Ag,1497 +cycler-0.12.1.dist-info/METADATA,sha256=IyieGbdvHgE5Qidpbmryts0c556JcxIJv5GVFIsY7TY,3779 +cycler-0.12.1.dist-info/RECORD,, +cycler-0.12.1.dist-info/WHEEL,sha256=yQN5g4mg4AybRjkgi-9yy4iQEFibGQmlz78Pik5Or-A,92 +cycler-0.12.1.dist-info/top_level.txt,sha256=D8BVVDdAAelLb2FOEz7lDpc6-AL21ylKPrMhtG6yzyE,7 +cycler/__init__.py,sha256=1JdRgv5Zzxo-W1ev7B_LWquysWP6LZH6CHk_COtIaXE,16709 +cycler/__pycache__/__init__.cpython-313.pyc,, +cycler/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/data/miniconda3/lib/python3.13/site-packages/cycler-0.12.1.dist-info/WHEEL b/data/miniconda3/lib/python3.13/site-packages/cycler-0.12.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..7e688737d490be3643d705bc16b5a77f7bd567b7 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cycler-0.12.1.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.41.2) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/data/miniconda3/lib/python3.13/site-packages/cycler-0.12.1.dist-info/top_level.txt b/data/miniconda3/lib/python3.13/site-packages/cycler-0.12.1.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..22546440faf3e339c5fb7ec3956bd03cb602ac92 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cycler-0.12.1.dist-info/top_level.txt @@ -0,0 +1 @@ +cycler diff --git a/data/miniconda3/lib/python3.13/site-packages/ezdxf-1.4.3.dist-info/INSTALLER b/data/miniconda3/lib/python3.13/site-packages/ezdxf-1.4.3.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ezdxf-1.4.3.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/data/miniconda3/lib/python3.13/site-packages/ezdxf-1.4.3.dist-info/METADATA b/data/miniconda3/lib/python3.13/site-packages/ezdxf-1.4.3.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..5d6344e3a3a8861c0dd85de1318f1ccaf84c433a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ezdxf-1.4.3.dist-info/METADATA @@ -0,0 +1,287 @@ +Metadata-Version: 2.4 +Name: ezdxf +Version: 1.4.3 +Summary: A Python package to create/manipulate DXF drawings. +Author-email: Manfred Moitzi +Project-URL: Repository, https://github.com/mozman/ezdxf +Project-URL: Documentation, https://ezdxf.readthedocs.io +Project-URL: Changelog, https://ezdxf.mozman.at/notes/#/page/changelog +Project-URL: Forum, https://github.com/mozman/ezdxf/discussions +Project-URL: Issues, https://github.com/mozman/ezdxf/issues +Project-URL: Website, https://ezdxf.mozman.at +Project-URL: Download, https://pypi.org/project/ezdxf +Keywords: DXF,CAD +Classifier: Development Status :: 5 - Production/Stable +Classifier: License :: OSI Approved :: MIT License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Intended Audience :: Developers +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Typing :: Typed +Provides: ezdxf +Requires-Python: >=3.10 +Description-Content-Type: text/markdown +License-File: LICENSE +Requires-Dist: pyparsing>=2.0.1 +Requires-Dist: typing_extensions>=4.6.0 +Requires-Dist: numpy +Requires-Dist: fonttools +Provides-Extra: draw +Requires-Dist: PySide6; extra == "draw" +Requires-Dist: matplotlib; extra == "draw" +Requires-Dist: PyMuPDF>=1.20.0; extra == "draw" +Requires-Dist: Pillow; extra == "draw" +Provides-Extra: draw5 +Requires-Dist: PyQt5; extra == "draw5" +Requires-Dist: matplotlib; extra == "draw5" +Requires-Dist: PyMuPDF>=1.20.0; extra == "draw5" +Requires-Dist: Pillow; extra == "draw5" +Provides-Extra: dev +Requires-Dist: PySide6; extra == "dev" +Requires-Dist: setuptools; extra == "dev" +Requires-Dist: wheel; extra == "dev" +Requires-Dist: Cython; extra == "dev" +Requires-Dist: pytest; extra == "dev" +Requires-Dist: Pillow; extra == "dev" +Requires-Dist: matplotlib; extra == "dev" +Requires-Dist: PyMuPDF>=1.20.0; extra == "dev" +Provides-Extra: dev5 +Requires-Dist: PyQt5; extra == "dev5" +Requires-Dist: setuptools; extra == "dev5" +Requires-Dist: wheel; extra == "dev5" +Requires-Dist: Cython; extra == "dev5" +Requires-Dist: pytest; extra == "dev5" +Requires-Dist: Pillow; extra == "dev5" +Requires-Dist: matplotlib; extra == "dev5" +Requires-Dist: PyMuPDF>=1.20.0; extra == "dev5" +Dynamic: license-file + + +# ezdxf + +## Abstract + +This Python package is designed to facilitate the creation and manipulation of DXF +documents, with compatibility across various DXF versions. It empowers users to +seamlessly load and edit DXF files while preserving all content, except for comments. + +Any unfamiliar DXF tags encountered in the document are gracefully ignored but retained +for future modifications. This feature enables the processing of DXF documents +containing data from third-party applications without any loss of valuable information. + +## Quick-Info + +- `ezdxf` is a Python package to create new DXF files and read/modify/write + existing DXF documents +- MIT-License +- the intended audience are programmers +- requires at least Python 3.10 +- OS independent +- tested with CPython and pypy3 +- has type annotations and passes `mypy --ignore-missing-imports -p ezdxf` successful +- additional required packages for the core package without add-ons + - [typing_extensions](https://pypi.org/project/typing-extensions/) + - [pyparsing](https://pypi.org/project/pyparsing/) + - [numpy](https://pypi.org/project/numpy/) + - [fontTools](https://pypi.org/project/fonttools/) +- read/write/new support for DXF versions: R12, R2000, R2004, R2007, R2010, R2013 and R2018 +- additional read-only support for DXF versions R13/R14 (upgraded to R2000) +- additional read-only support for older DXF versions than R12 (upgraded to R12) +- read/write support for ASCII DXF and Binary DXF +- retains third-party DXF content +- optional C-extensions for CPython are included in the binary wheels, available + on [PyPI](https://pypi.org/project/ezdxf/) for Windows, Linux and macOS +- command line script `ezdxf` to display, convert and inspect DXF files + +## Included Extensions + +Additional packages required for these add-ons are not automatically installed +during the *basic* setup, for more information about the setup & dependencies +visit the [documentation](https://ezdxf.mozman.at/docs/setup.html). + +- The `drawing` add-on is a translation layer to send DXF data to a render backend, + interfaces to [matplotlib](https://pypi.org/project/matplotlib/), which can export + images as PNG, PDF or SVG, and [PyQt5](https://pypi.org/project/PyQt5/) are implemented. +- `r12writer` add-on to write basic DXF entities direct and fast into a DXF R12 + file or stream +- `iterdxf` add-on to iterate over DXF entities from the modelspace of huge DXF + files (> 5GB) which do not fit into memory +- `Importer` add-on to import entities, blocks and table entries from another DXF document +- `dxf2code` add-on to generate Python code for DXF structures loaded from DXF + documents as starting point for parametric DXF entity creation +- `acadctb` add-on to read/write plot style files (CTB/STB) +- `pycsg` add-on for basic Constructive Solid Geometry (CSG) modeling +- `MTextExplode` add-on for exploding MTEXT entities into single-line TEXT entities +- `text2path` add-on to convert text into outline paths +- `geo` add-on to support the [`__geo_interface__`](https://gist.github.com/sgillies/2217756) +- `meshex` for exchanging meshes with other tools as STL, OFF or OBJ files +- `openscad` add-on, an interface to [OpenSCAD](https://openscad.org) +- `odafc` add-on, an interface to the [ODA File Converter](https://www.opendesign.com/guestfiles/oda_file_converter) + to read and write DWG files +- `hpgl2` add-on for converting HPGL/2 plot files to DXF, SVG and PDF + +A simple example: + +```Python +import ezdxf +from ezdxf import colors +from ezdxf.enums import TextEntityAlignment + +# Create a new DXF document. +doc = ezdxf.new(dxfversion="R2010") + +# Create new table entries (layers, linetypes, text styles, ...). +doc.layers.add("TEXTLAYER", color=colors.RED) + +# DXF entities (LINE, TEXT, ...) reside in a layout (modelspace, +# paperspace layout or block definition). +msp = doc.modelspace() + +# Add entities to a layout by factory methods: layout.add_...() +msp.add_line((0, 0), (10, 0), dxfattribs={"color": colors.YELLOW}) +msp.add_text( + "Test", + dxfattribs={ + "layer": "TEXTLAYER" + }).set_placement((0, 0.2), align=TextEntityAlignment.CENTER) + +# Save the DXF document. +doc.saveas("test.dxf") +``` + +Example for the *r12writer*, which writes a simple DXF R12 file without +in-memory structures: + +```Python +from random import random +from ezdxf.addons import r12writer + +MAX_X_COORD = 1000 +MAX_Y_COORD = 1000 + +with r12writer("many_circles.dxf") as doc: + for _ in range(100000): + doc.add_circle((MAX_X_COORD*random(), MAX_Y_COORD*random()), radius=2) +``` + +The r12writer supports only the ENTITIES section of a DXF R12 drawing, no HEADER, +TABLES or BLOCKS section is present, except FIXED-TABLES are written, than some +additional predefined text styles and line types are available. + +## Installation + +Basic installation by pip including the optional C-extensions from PyPI as +binary wheels: + + pip install ezdxf + +Full installation with all dependencies (matplotlib, PySide6) for using the +drawing add-on: + + pip install ezdxf[draw] + +For more information about the setup & dependencies visit the +[documentation](https://ezdxf.mozman.at/docs/setup.html). + +## Command Line + +Use `python -m ezdxf ...` if your shell can't find the `ezdxf` script. + +Get additional help for a sub-command: + + ezdxf -h + +Preview DXF files in a graphical window: + + ezdxf view + +Export the modelspace of DXF files as PNG|SVG|PDF: + + ezdxf draw -o file. + +Print basic information about DXF files: + + ezdxf info + +Show detailed information and structures of DXF files: + + ezdxf browse + +Audit DXF files: + + ezdxf audit + +Preview and convert HPGL/2 plot files: + + ezdxf hpgl + + +## Website + +https://ezdxf.mozman.at/ + +## Documentation + +Documentation of the development version at https://ezdxf.mozman.at/docs + +Documentation of the latest release at https://ezdxf.readthedocs.io/ + +## Knowledge Graph + +The knowledge graph contains additional information beyond the documentation and is +managed by [logseq](https://logseq.com/). The source data is included in the repository +in the folder `ezdxf/notes`. There is also a [HTML export](https://ezdxf.mozman.at/notes/#/page/ezdxf) +on the website which gets regular updates. + + +## Contribution + +The source code of *ezdxf* can be found at __GitHub__, target your pull requests +to the `master` branch: + +https://github.com/mozman/ezdxf.git + + +## Feedback + +Questions and feedback at __GitHub Discussions__: + +https://github.com/mozman/ezdxf/discussions + +Questions at __Stack Overflow__: + +Post questions at [stack overflow](https://stackoverflow.com/) and use the tag `dxf` or `ezdxf`. + +Issue tracker at __GitHub__: + +http://github.com/mozman/ezdxf/issues + +## Release Notes + +The [release notes](https://ezdxf.mozman.at/notes/#/page/release%20notes) are included +in the knowledge graph. + +## Changelog + +The [changelog](https://ezdxf.mozman.at/notes/#/page/changelog) is included +in the knowledge graph. + + +## Contact + +Please __always__ post questions at the [forum](https://github.com/mozman/ezdxf/discussions) +or [stack overflow](https://stackoverflow.com/) to make answers +available to other users as well. + +ezdxf@mozman.at + +Feedback is greatly appreciated. + +Manfred diff --git a/data/miniconda3/lib/python3.13/site-packages/ezdxf-1.4.3.dist-info/RECORD b/data/miniconda3/lib/python3.13/site-packages/ezdxf-1.4.3.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..7a46b548b99aaa9055504ca4b0bf32cbec6f9254 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ezdxf-1.4.3.dist-info/RECORD @@ -0,0 +1,739 @@ +../../../bin/ezdxf,sha256=-xhlir8xibNc8LkoqmMA163R5QdQOg-Ap2vzRCzVABw,210 +ezdxf-1.4.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +ezdxf-1.4.3.dist-info/METADATA,sha256=ONjPVURGTlMkWDKbB7X2kCOFqoAPw7uEucW5eY_nlb0,9899 +ezdxf-1.4.3.dist-info/RECORD,, +ezdxf-1.4.3.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +ezdxf-1.4.3.dist-info/WHEEL,sha256=sLnxkimgGZnkHfiVG0CKXk3cbEzmkkBUHrkKJEO9o6g,151 +ezdxf-1.4.3.dist-info/entry_points.txt,sha256=Mxa4CfzxalQCVrE5K4LnCmYrMHNvdVold1cn05O8MbM,46 +ezdxf-1.4.3.dist-info/licenses/LICENSE,sha256=25fKQm_A0rgSQUXeDzYYHbc-bnE85kLUL-0u_EQu3xk,1071 +ezdxf-1.4.3.dist-info/top_level.txt,sha256=jDpbvSz92tkSe1t8mGnMMWQp6VOaxtRxpmcpNEWe6IM,6 +ezdxf/__init__.py,sha256=b7bOHjtAZoJa9GrkC7G6KqZOBYYOi7lefx3Nbh_Tn_A,3034 +ezdxf/__main__.py,sha256=HyzvMb5cKnIg2R0kEjpzYi9tVTrK5PLnTLYCQi-IAjI,3139 +ezdxf/__pycache__/__init__.cpython-313.pyc,, +ezdxf/__pycache__/__main__.cpython-313.pyc,, +ezdxf/__pycache__/_options.cpython-313.pyc,, +ezdxf/__pycache__/appsettings.cpython-313.pyc,, +ezdxf/__pycache__/audit.cpython-313.pyc,, +ezdxf/__pycache__/bbox.cpython-313.pyc,, +ezdxf/__pycache__/blkrefs.cpython-313.pyc,, +ezdxf/__pycache__/colors.cpython-313.pyc,, +ezdxf/__pycache__/commands.cpython-313.pyc,, +ezdxf/__pycache__/comments.cpython-313.pyc,, +ezdxf/__pycache__/disassemble.cpython-313.pyc,, +ezdxf/__pycache__/document.cpython-313.pyc,, +ezdxf/__pycache__/dwginfo.cpython-313.pyc,, +ezdxf/__pycache__/dynblkhelper.cpython-313.pyc,, +ezdxf/__pycache__/edgeminer.cpython-313.pyc,, +ezdxf/__pycache__/edgesmith.cpython-313.pyc,, +ezdxf/__pycache__/entitydb.cpython-313.pyc,, +ezdxf/__pycache__/enums.cpython-313.pyc,, +ezdxf/__pycache__/explode.cpython-313.pyc,, +ezdxf/__pycache__/eztypes.cpython-313.pyc,, +ezdxf/__pycache__/filemanagement.cpython-313.pyc,, +ezdxf/__pycache__/gfxattribs.cpython-313.pyc,, +ezdxf/__pycache__/graphicsfactory.cpython-313.pyc,, +ezdxf/__pycache__/groupby.cpython-313.pyc,, +ezdxf/__pycache__/messenger.cpython-313.pyc,, +ezdxf/__pycache__/msgtypes.cpython-313.pyc,, +ezdxf/__pycache__/npshapes.cpython-313.pyc,, +ezdxf/__pycache__/protocols.cpython-313.pyc,, +ezdxf/__pycache__/proxygraphic.cpython-313.pyc,, +ezdxf/__pycache__/query.cpython-313.pyc,, +ezdxf/__pycache__/queryparser.cpython-313.pyc,, +ezdxf/__pycache__/r12strict.cpython-313.pyc,, +ezdxf/__pycache__/recover.cpython-313.pyc,, +ezdxf/__pycache__/reorder.cpython-313.pyc,, +ezdxf/__pycache__/revcloud.cpython-313.pyc,, +ezdxf/__pycache__/select.cpython-313.pyc,, +ezdxf/__pycache__/transform.cpython-313.pyc,, +ezdxf/__pycache__/units.cpython-313.pyc,, +ezdxf/__pycache__/upright.cpython-313.pyc,, +ezdxf/__pycache__/urecord.cpython-313.pyc,, +ezdxf/__pycache__/version.cpython-313.pyc,, +ezdxf/__pycache__/xclip.cpython-313.pyc,, +ezdxf/__pycache__/xref.cpython-313.pyc,, +ezdxf/__pycache__/zoom.cpython-313.pyc,, +ezdxf/_options.py,sha256=Eg3jipDnqQuDjpAFN520JEcMFP6s3J-qccMo0yaXmuY,10563 +ezdxf/acc/__init__.py,sha256=6A57wOpq0goZScvZhCKsUImkapXBhRaCNDoqwunYFjY,1226 +ezdxf/acc/__pycache__/__init__.cpython-313.pyc,, +ezdxf/acc/bezier3p.c,sha256=7iVhI7QoEQqmk-gquoJK5KVdtcYgm7XMRpTxHbAC0aw,578427 +ezdxf/acc/bezier3p.cpython-313-x86_64-linux-gnu.so,sha256=-FoQvETQWRKcsXKgUZCvRygaAvIEOATy47kZa5CAJag,881984 +ezdxf/acc/bezier3p.pyx,sha256=ihwT1ejKHaxy5gh3lp6j5eQiPIAaB43vn2_8wCtjr5Y,6566 +ezdxf/acc/bezier4p.c,sha256=I9CGgwHtS4Y3v0p60L7zR0HA4HWdIzx_6cz0BaxqsLI,784694 +ezdxf/acc/bezier4p.cpython-313-x86_64-linux-gnu.so,sha256=EMr5tgN2XQKvq9CIm-xP0xMpBwYDv5GnzGYVzjEpWiY,1155040 +ezdxf/acc/bezier4p.pyx,sha256=c-tlaAi-lFzBGUNa6kodAca3EtuBOYzk9N0gbIMps5s,11131 +ezdxf/acc/bspline.c,sha256=EUbeEwQx7lO6cqHTRlqqI9ToKIimBnqmqdg019HIRuo,820601 +ezdxf/acc/bspline.cpython-313-x86_64-linux-gnu.so,sha256=P1USAbT1w_AemdtQ-OpWavwoh_UuR62UGFb-0boRc88,1309656 +ezdxf/acc/bspline.pyx,sha256=R7aykWi5-w9oq3eufsmzpv5GUCXuixHWyfuAAL4hnq4,13736 +ezdxf/acc/constants.h,sha256=JvAaWl6LBubuuZMh18Zu1PLbjwJvEFoIhObY_S9vMY8,244 +ezdxf/acc/construct.c,sha256=dBgRlr6MC1EAN1_oWNSNxXSsV8aQiQVaFXwcOD_yJvc,526439 +ezdxf/acc/construct.cpython-313-x86_64-linux-gnu.so,sha256=7_5clOXLMlb_IQvUiYMTj5rUMvhXFGTW5H085piD6x4,748752 +ezdxf/acc/construct.pyx,sha256=H4anrrevB2HI-0kY9B9Td5FnqmuTS8ujyH3kKK2N8_w,11486 +ezdxf/acc/linetypes.c,sha256=GcvpOcrJDE09t3nz9tVopqwvoQL9F25e8scbB_bAOgw,492767 +ezdxf/acc/linetypes.cpython-313-x86_64-linux-gnu.so,sha256=Q4v7mwj3OGigXA4YBpBilIzXYglVxMCpMhC1TR8fZNQ,588768 +ezdxf/acc/linetypes.pyx,sha256=msIJPqEpnsQGc7ktLe8K6YrV-8_XKKtJFz6hMQM5b5Y,3070 +ezdxf/acc/mapbox_earcut.c,sha256=Wgy52PJuz2u5uG0uo-vByhczlBS8_ebb2RrNND3HDgY,637811 +ezdxf/acc/mapbox_earcut.cpython-313-x86_64-linux-gnu.so,sha256=WKCC5xqQ2RRLP9Lv-ZuJl_1MgTDQvghhOHU5jo7WXbY,834600 +ezdxf/acc/mapbox_earcut.pyx,sha256=qHE8ukGi7NCHGqLRZZiNdtYFtthVwiVBgBvsYzsSjxk,23141 +ezdxf/acc/matrix44.c,sha256=cmXpYQiGzaSJA5sMwryLFxyGdHnXoRxXb7zmVKEaG2A,1836311 +ezdxf/acc/matrix44.cpython-313-x86_64-linux-gnu.so,sha256=ExrdP0_f60HTPkDXocs1lwaQXq815XGqpo0GYpHIy_Q,2742152 +ezdxf/acc/matrix44.pxd,sha256=JJCSLlwXknv1r-r1GUMQhZcCh3fA1QWrk7Pxp9mlvUU,371 +ezdxf/acc/matrix44.pyx,sha256=jMGw9Ug64Cz44c6dLB2_29OKK2FcJ9pQD69QNItd1b8,23027 +ezdxf/acc/np_support.c,sha256=lnBu-hkagJSbheZAGktV_RZqPWpEIaOR7Dj3DSf1eNw,1105092 +ezdxf/acc/np_support.cpython-313-x86_64-linux-gnu.so,sha256=KpLARLKUu8Hcn6Z4SAWYRDZR4Bgcdm4D_2caeyRooPM,1678800 +ezdxf/acc/np_support.pyx,sha256=z74akgfzYIE4eZi_nNC1F_es3p6Zknd2M4pnaETutK4,4528 +ezdxf/acc/vector.c,sha256=Ug7gfTzQquPoTm2HP_eC4V5gIHITohzfAyt3Mmz_6jM,1332711 +ezdxf/acc/vector.cpython-313-x86_64-linux-gnu.so,sha256=XU5sl7vMjc8lMO906H_uocHHwsQhb2KTuf1T71AH1PM,1910240 +ezdxf/acc/vector.pxd,sha256=iV_NNQ2_Wfzju7RXEvQO3v-KH4F6Q7ttONthWXnNRgA,1670 +ezdxf/acc/vector.pyx,sha256=1DjzL8d_c7BkXfnF6GT-jvPV20JODFKDMtEgJvEWtCw,22539 +ezdxf/acis/__init__.py,sha256=LumXqj8kBH6TrgmoqgF88LmTWRsnh8vR4YyqxkoGGrE,117 +ezdxf/acis/__pycache__/__init__.cpython-313.pyc,, +ezdxf/acis/__pycache__/abstract.cpython-313.pyc,, +ezdxf/acis/__pycache__/api.cpython-313.pyc,, +ezdxf/acis/__pycache__/cache.cpython-313.pyc,, +ezdxf/acis/__pycache__/const.cpython-313.pyc,, +ezdxf/acis/__pycache__/dbg.cpython-313.pyc,, +ezdxf/acis/__pycache__/dxf.cpython-313.pyc,, +ezdxf/acis/__pycache__/entities.cpython-313.pyc,, +ezdxf/acis/__pycache__/hdr.cpython-313.pyc,, +ezdxf/acis/__pycache__/mesh.cpython-313.pyc,, +ezdxf/acis/__pycache__/sab.cpython-313.pyc,, +ezdxf/acis/__pycache__/sat.cpython-313.pyc,, +ezdxf/acis/__pycache__/type_hints.cpython-313.pyc,, +ezdxf/acis/abstract.py,sha256=mmt82FvfnrWvsGShzdlJD93vo0lBje54fZu88mrmbzk,6174 +ezdxf/acis/api.py,sha256=P2NVgPyVi4k2PwXHg3P8GNDkXPsgK7g7BTp3HOKHwGk,907 +ezdxf/acis/cache.py,sha256=zNjDI0gTbD5pQaYlYkPZ0fUfGqzg21elBNuW-FXXbtQ,1733 +ezdxf/acis/const.py,sha256=CsXe8jKlXNTLb0kDvU6f5A16koSyPr0hJDE3pj6gDJU,5306 +ezdxf/acis/dbg.py,sha256=Z9MbCH3_unno26gjNTo95vHRzDbRjHF63dY_KNDybGI,6538 +ezdxf/acis/dxf.py,sha256=OVioKoHjkmZzAWuHYOBVbUFx7RFkojt1fiB4tCGgY1o,2903 +ezdxf/acis/entities.py,sha256=YRN-J3RuPzs-MiVqorOysB6_pvPaLnsUyr5CQATnMGg,27948 +ezdxf/acis/hdr.py,sha256=jRQ4KN0ewrZWWYEd9c2PCu3fIBQGvfkNNOZMAFUZMos,3983 +ezdxf/acis/mesh.py,sha256=m-MrPh9HG5bod5Fjjq8ORpD_Bx1lJzBcKYAiBtgP3ns,15151 +ezdxf/acis/sab.py,sha256=VPIm6ybeIDppWJonhYQuhYidUKW32ML3KkIckI1aOTI,18168 +ezdxf/acis/sat.py,sha256=OqCuajqhLBWYrIQKColyIiid0tnt1AieJwVy9EaEIFI,12758 +ezdxf/acis/type_hints.py,sha256=DIpayCTj0vwEhJTBpGTkydblbh_U_jKED4pswkqTCEA,240 +ezdxf/addons/__init__.py,sha256=3ZTRNtrdtox-5wq1jKu4Vcgzjm-1IMgDgymuMM5xqZY,443 +ezdxf/addons/__pycache__/__init__.cpython-313.pyc,, +ezdxf/addons/__pycache__/acadctb.cpython-313.pyc,, +ezdxf/addons/__pycache__/binpacking.cpython-313.pyc,, +ezdxf/addons/__pycache__/dimlines.cpython-313.pyc,, +ezdxf/addons/__pycache__/dxf2code.cpython-313.pyc,, +ezdxf/addons/__pycache__/genetic_algorithm.cpython-313.pyc,, +ezdxf/addons/__pycache__/geo.cpython-313.pyc,, +ezdxf/addons/__pycache__/gerber_D6673.cpython-313.pyc,, +ezdxf/addons/__pycache__/importer.cpython-313.pyc,, +ezdxf/addons/__pycache__/iterdxf.cpython-313.pyc,, +ezdxf/addons/__pycache__/menger_sponge.cpython-313.pyc,, +ezdxf/addons/__pycache__/meshex.cpython-313.pyc,, +ezdxf/addons/__pycache__/mixins.cpython-313.pyc,, +ezdxf/addons/__pycache__/mtextsurrogate.cpython-313.pyc,, +ezdxf/addons/__pycache__/mtxpl.cpython-313.pyc,, +ezdxf/addons/__pycache__/odafc.cpython-313.pyc,, +ezdxf/addons/__pycache__/openscad.cpython-313.pyc,, +ezdxf/addons/__pycache__/pycsg.cpython-313.pyc,, +ezdxf/addons/__pycache__/r12export.cpython-313.pyc,, +ezdxf/addons/__pycache__/r12writer.cpython-313.pyc,, +ezdxf/addons/__pycache__/sierpinski_pyramid.cpython-313.pyc,, +ezdxf/addons/__pycache__/tablepainter.cpython-313.pyc,, +ezdxf/addons/__pycache__/text2path.cpython-313.pyc,, +ezdxf/addons/__pycache__/xplayer.cpython-313.pyc,, +ezdxf/addons/__pycache__/xqt.cpython-313.pyc,, +ezdxf/addons/acadctb.py,sha256=mU1IXPnJDcvhnJP-EqB_QZQI2sRM6ZdSzaUWKr_3Ve8,25987 +ezdxf/addons/acisbrowser/__init__.py,sha256=fDQ7wDl4R_pMX_CHJ5O6JUZLoBm04YcquUR9AkVLE7o,62 +ezdxf/addons/acisbrowser/__pycache__/__init__.cpython-313.pyc,, +ezdxf/addons/acisbrowser/__pycache__/browser.cpython-313.pyc,, +ezdxf/addons/acisbrowser/__pycache__/data.cpython-313.pyc,, +ezdxf/addons/acisbrowser/browser.py,sha256=CQrW44aYqtZriYqw79qyeefF0cOQamsGi1f6FfoVeZc,9694 +ezdxf/addons/acisbrowser/data.py,sha256=yKG_W9UBrEoSRDaRXn-hUmsz2iuH0r-f_-WIOYfYZSs,1847 +ezdxf/addons/binpacking.py,sha256=sVXSxqCJyzJiyVpXkJwKT9NclxUL2lTqZ-K8zW57skA,21513 +ezdxf/addons/browser/__init__.py,sha256=_o3jB7kZd9z_tFemgVWbxDzwLnGzrS8rlYR5NgvW0TE,127 +ezdxf/addons/browser/__pycache__/__init__.cpython-313.pyc,, +ezdxf/addons/browser/__pycache__/bookmarks.cpython-313.pyc,, +ezdxf/addons/browser/__pycache__/browser.cpython-313.pyc,, +ezdxf/addons/browser/__pycache__/data.cpython-313.pyc,, +ezdxf/addons/browser/__pycache__/find_dialog.cpython-313.pyc,, +ezdxf/addons/browser/__pycache__/loader.cpython-313.pyc,, +ezdxf/addons/browser/__pycache__/model.cpython-313.pyc,, +ezdxf/addons/browser/__pycache__/reflinks.cpython-313.pyc,, +ezdxf/addons/browser/__pycache__/tags.cpython-313.pyc,, +ezdxf/addons/browser/__pycache__/views.cpython-313.pyc,, +ezdxf/addons/browser/bookmarks.py,sha256=i5V3NdlaDuPnWjCP7a7alSEJH84SSu2vW1px_chjTis,787 +ezdxf/addons/browser/browser.py,sha256=PT4DyYSfqn7__d9xDc0lwMmsYtzJUYN6cKkIaE2SXxk,28551 +ezdxf/addons/browser/data.py,sha256=7zhv0KQuQKRQG7MevLbVfxzygtNMShKzQM8ievjjKfk,14463 +ezdxf/addons/browser/find_dialog.py,sha256=FfI3ChEb7nhc8bjX3RKLofQL1Q8rD9rKhwMdVOiCyVg,10822 +ezdxf/addons/browser/loader.py,sha256=2KntX9NQQReA3aE3J6Jseyx0FzgrYauQTiscqKy4PQk,1213 +ezdxf/addons/browser/model.py,sha256=nt01snJSUl9BHBA2Kmmrls6CcrcLtA0W-i1cevZLL4o,20537 +ezdxf/addons/browser/reflinks.py,sha256=LzG_KS6oARzt_pnP7ntikL43ccZgrZ7v8-hJOPd_yKo,6779 +ezdxf/addons/browser/tags.py,sha256=k2I5OpMz-aabPpgrdFcrZ0wlMS176w_BSDcl_sGacJo,2143 +ezdxf/addons/browser/views.py,sha256=kcwiwWTq-AEA8tmphX0eTndgS4b3QdJWbY952P3xAOk,1325 +ezdxf/addons/dimlines.py,sha256=2pgQWfIn3sgIN6FUSHRjzl-ducvubcSxgyqBfsEjo1Q,26926 +ezdxf/addons/drawing/__init__.py,sha256=K_I-4w71JrpVZDAYaqOVCgUPcAAQITDoQlLkaWp5D50,166 +ezdxf/addons/drawing/__pycache__/__init__.cpython-313.pyc,, +ezdxf/addons/drawing/__pycache__/backend.cpython-313.pyc,, +ezdxf/addons/drawing/__pycache__/config.cpython-313.pyc,, +ezdxf/addons/drawing/__pycache__/debug_backend.cpython-313.pyc,, +ezdxf/addons/drawing/__pycache__/debug_utils.cpython-313.pyc,, +ezdxf/addons/drawing/__pycache__/dxf.cpython-313.pyc,, +ezdxf/addons/drawing/__pycache__/file_output.cpython-313.pyc,, +ezdxf/addons/drawing/__pycache__/frontend.cpython-313.pyc,, +ezdxf/addons/drawing/__pycache__/gfxproxy.cpython-313.pyc,, +ezdxf/addons/drawing/__pycache__/hpgl2.cpython-313.pyc,, +ezdxf/addons/drawing/__pycache__/json.cpython-313.pyc,, +ezdxf/addons/drawing/__pycache__/layout.cpython-313.pyc,, +ezdxf/addons/drawing/__pycache__/matplotlib.cpython-313.pyc,, +ezdxf/addons/drawing/__pycache__/mtext_complex.cpython-313.pyc,, +ezdxf/addons/drawing/__pycache__/pipeline.cpython-313.pyc,, +ezdxf/addons/drawing/__pycache__/properties.cpython-313.pyc,, +ezdxf/addons/drawing/__pycache__/pymupdf.cpython-313.pyc,, +ezdxf/addons/drawing/__pycache__/pyqt.cpython-313.pyc,, +ezdxf/addons/drawing/__pycache__/qtviewer.cpython-313.pyc,, +ezdxf/addons/drawing/__pycache__/recorder.cpython-313.pyc,, +ezdxf/addons/drawing/__pycache__/svg.cpython-313.pyc,, +ezdxf/addons/drawing/__pycache__/text.cpython-313.pyc,, +ezdxf/addons/drawing/__pycache__/text_renderer.cpython-313.pyc,, +ezdxf/addons/drawing/__pycache__/type_hints.cpython-313.pyc,, +ezdxf/addons/drawing/__pycache__/unified_text_renderer.cpython-313.pyc,, +ezdxf/addons/drawing/backend.py,sha256=7keMHuK3GStQXF1BdCX2XZFvlbJSkPcUE593FtvmNTg,9000 +ezdxf/addons/drawing/config.py,sha256=2w23wH-vNo9qoBvfHIQqLofQZOGQ6xj0KHOG_UOgv4k,10821 +ezdxf/addons/drawing/debug_backend.py,sha256=Ll2KVaB0pddQV4P5DDtqsy_lfvJJiAx_ThsvOWutNUM,1704 +ezdxf/addons/drawing/debug_utils.py,sha256=JSikPHVsjZioPA4FiibbMObZ0ZdkUp8ABfzz9s03WdQ,499 +ezdxf/addons/drawing/dxf.py,sha256=7RIhjXpCrA9lEmEznFRRX0N93-yLbk9v_wMv1aCjczc,7168 +ezdxf/addons/drawing/file_output.py,sha256=n3W57_y6eDgo_K_dSktcU-o7-RAteteDDoxvjuwLJ7k,7525 +ezdxf/addons/drawing/frontend.py,sha256=j26ENrPeCy2SuNTL3ndrsb_kdmA9UF4VYTpFP1bikQs,43896 +ezdxf/addons/drawing/gfxproxy.py,sha256=DwEorryhbImnG2D1GpOuwe0hqX_7kczVU_9m6WlD18A,1829 +ezdxf/addons/drawing/hpgl2.py,sha256=_u_bnNcpowhlZzKgRPq33y10F-bJg7wJ_4Vz2fdViY8,20285 +ezdxf/addons/drawing/json.py,sha256=GAyiPfiKjxPybN4tPv3YJOxF2OrjYuDMT-IbW2oo4Pg,19511 +ezdxf/addons/drawing/layout.py,sha256=-3-nNjVyYwN39nwe5xpTHz6GgFVb72v6WzYBvOjdNmM,18457 +ezdxf/addons/drawing/matplotlib.py,sha256=qdC9MqanMEr3WCXtEq0VodknJDdmjt_sk2TGWobzPmY,12848 +ezdxf/addons/drawing/mtext_complex.py,sha256=5i7BglzBsn8Fj9QiPejp-y3a_P8oVCvGdKSfihr0ZPM,9552 +ezdxf/addons/drawing/pipeline.py,sha256=eea6aHGU_nQQqApQZcylkFhxFQzFyK8sU_PDW8eb_Mc,31559 +ezdxf/addons/drawing/properties.py,sha256=Ac3Pk7-7XeRWJZzkkI9G2i1UZ8Ck8Xx4OvQ4d5Y1h7c,39281 +ezdxf/addons/drawing/pymupdf.py,sha256=EtnV2sg5ELssO4RAZqU3WMFWBnsGRbTLiuAK6DOcefI,18515 +ezdxf/addons/drawing/pyqt.py,sha256=cVV9WPNwKT4ufhHgJWchoZt2pIOAOhO43RxwF011MFE,11263 +ezdxf/addons/drawing/qtviewer.py,sha256=vxImoyAaIJ9LNvVnHh6DcsFmpx--yPFqyB1t3Xw1FHs,22090 +ezdxf/addons/drawing/recorder.py,sha256=t9ILNwzzz_KmdVdYCKkme4rlRCeUedP23u1d693_DQE,15987 +ezdxf/addons/drawing/svg.py,sha256=mq0J0LUYrdU-gxpDtcQ19ImU0U5Wny8Xvc-jsG7JwAg,15642 +ezdxf/addons/drawing/text.py,sha256=h1R96mdiAArLnCsbvAydk2Mv5WST6LRpdhjKwqofD6A,12672 +ezdxf/addons/drawing/text_renderer.py,sha256=l9lmBBozkMgCXhX7cDlai7GirVjsb8yGrzgrfmauXS4,1148 +ezdxf/addons/drawing/type_hints.py,sha256=QQ2OqbTyJaIr7gYoW0rwy63cBGQaBngzIjyXamLgmss,304 +ezdxf/addons/drawing/unified_text_renderer.py,sha256=aZDlUJq69eu_C2AtkXkEzH8pCylDYl6o8apQoVQW5ao,2487 +ezdxf/addons/dwg/__init__.py,sha256=EVNuNTgPsO8UKaKEvmPMlwC2AbYN4b88JYwpxceo6g4,136 +ezdxf/addons/dwg/__pycache__/__init__.cpython-313.pyc,, +ezdxf/addons/dwg/__pycache__/classes_section.cpython-313.pyc,, +ezdxf/addons/dwg/__pycache__/const.cpython-313.pyc,, +ezdxf/addons/dwg/__pycache__/crc.cpython-313.pyc,, +ezdxf/addons/dwg/__pycache__/fileheader.cpython-313.pyc,, +ezdxf/addons/dwg/__pycache__/header_section.cpython-313.pyc,, +ezdxf/addons/dwg/__pycache__/loader.cpython-313.pyc,, +ezdxf/addons/dwg/classes_section.py,sha256=ywuE7vTLFBYZUW9GlJ0Rf3iHfOprLGIbAWtiv1Q7t1I,3030 +ezdxf/addons/dwg/const.py,sha256=L3qzZmbhyFzuQpIOgmYuk8a2Y1R-O5_v-1Yu5yLkvrw,718 +ezdxf/addons/dwg/crc.py,sha256=Ka6mHI8O8zSjxyNB_aVWWLurncUuRjX3BMv_oWvVsig,6008 +ezdxf/addons/dwg/fileheader.py,sha256=dUEKVFaPPqjwaKv5R8lEGiQZQP18s3jzLvtzs5oiwfQ,3068 +ezdxf/addons/dwg/header_section.py,sha256=GLAlCf_LiE-Cncp6tJUv2EShqrAkefkkWOfEMRO02Is,14194 +ezdxf/addons/dwg/loader.py,sha256=yPXw2aBp0nAgyUE17cJwcIJCn2myfolopiNjeWnhurA,2888 +ezdxf/addons/dxf2code.py,sha256=x2Q4bUkI0adUJ0K80kDfaaUZW59oCLSFQCXaHDP7Zdk,30793 +ezdxf/addons/genetic_algorithm.py,sha256=o0T2LQX_albB0L7n3chdLOQTgfsENAXzP8cWBg2VVAQ,21284 +ezdxf/addons/geo.py,sha256=IaBtwCCoklnFufH5tEZkXDUe0AM9VCNoNXUlGq6vA5g,37795 +ezdxf/addons/gerber_D6673.py,sha256=lR0fNB43TulhlSOKVHpVvYobSGTlvV9lFYUefyUdSUE,2605 +ezdxf/addons/hpgl2/__init__.py,sha256=AzF9D_tSprdO4wjFUDH_aTI-5MiIVABghLuBRESreII,157 +ezdxf/addons/hpgl2/__pycache__/__init__.cpython-313.pyc,, +ezdxf/addons/hpgl2/__pycache__/api.cpython-313.pyc,, +ezdxf/addons/hpgl2/__pycache__/backend.cpython-313.pyc,, +ezdxf/addons/hpgl2/__pycache__/deps.cpython-313.pyc,, +ezdxf/addons/hpgl2/__pycache__/interpreter.cpython-313.pyc,, +ezdxf/addons/hpgl2/__pycache__/page.cpython-313.pyc,, +ezdxf/addons/hpgl2/__pycache__/plotter.cpython-313.pyc,, +ezdxf/addons/hpgl2/__pycache__/polygon_buffer.cpython-313.pyc,, +ezdxf/addons/hpgl2/__pycache__/properties.cpython-313.pyc,, +ezdxf/addons/hpgl2/__pycache__/tokenizer.cpython-313.pyc,, +ezdxf/addons/hpgl2/__pycache__/viewer.cpython-313.pyc,, +ezdxf/addons/hpgl2/api.py,sha256=0aaWqx7ZySnJQCZ2BUXLkEO6MBpHaMzM1jz5pvaYLEA,13045 +ezdxf/addons/hpgl2/backend.py,sha256=w_MjDeivmhf0iL-nOI2jVEUK7dxTRC3gc5oTo4J6pFY,8317 +ezdxf/addons/hpgl2/deps.py,sha256=88PMt_a4o9NH-qWddTh3Sz48xvNBGRFRQwG3T7IQUCE,548 +ezdxf/addons/hpgl2/interpreter.py,sha256=HvR0DuZ3gLL2i1rvlBkgkZi8CeGcpOVTitq8eAYhLkk,15621 +ezdxf/addons/hpgl2/page.py,sha256=SdBo7SMlutgXIkoN8DAwmtTqkLtv0KXl7z7tmu9C1FM,4702 +ezdxf/addons/hpgl2/plotter.py,sha256=LMMFpcEpwU9ugSJqto1XyByL6oAHLonHOGMXxQyEOY0,11451 +ezdxf/addons/hpgl2/polygon_buffer.py,sha256=yratUhVxEmoXEEkCJuCUdxVzmrYwBC-qIhwPa_yK0Co,1645 +ezdxf/addons/hpgl2/properties.py,sha256=hDcKIjr0NZq7WOZkoDfm-T-oL2vnmAaZsabFulTehA8,5440 +ezdxf/addons/hpgl2/tokenizer.py,sha256=n_kI7WbgB9AzvCLPEeKljIAGi6i02o1JtDoFaXqskNU,5998 +ezdxf/addons/hpgl2/viewer.py,sha256=DOKuRtzz61ej3bRg2vQIn9q6s-e47jzdJqnIoFkFkbs,18913 +ezdxf/addons/importer.py,sha256=ohK991QxqYi0w9UOyDT3ArJO9qQ4k1B_n6GjpYdb0gM,24808 +ezdxf/addons/iterdxf.py,sha256=7ZZRWHB0l3cidXb4JXmH4JD2FrSxl8yVRozH_AGxuO4,16875 +ezdxf/addons/menger_sponge.py,sha256=bAmGtdamYclv025bMPFg7UACimYeP9aUl6CFlkONFA0,8680 +ezdxf/addons/meshex.py,sha256=vQ5XSLbvESMb6zFKzgqOLjy2ZFjXVef0dqc7GV4pnPU,24112 +ezdxf/addons/mixins.py,sha256=kVnpr8H1vZgT9lG48892djBcQn0uWhZ9J0sWYPku_Po,473 +ezdxf/addons/mtextsurrogate.py,sha256=shNC-qeYwWm0jmkDQyHsY5FyQ9nwoJR-OOkvCLv0_TQ,6029 +ezdxf/addons/mtxpl.py,sha256=U45waek-UG7p7b2nn1XYZnIt3H-VtTsIPXihdq6dpNc,13140 +ezdxf/addons/odafc.py,sha256=bPxaKKMw5mckVpaCNxKM8TAH6B6zkt88QGHgqu7DTzg,16070 +ezdxf/addons/openscad.py,sha256=NtQKI-32wHboN7rhtmnlL9Iwt4VNGJC_VtCSV79bhQo,9441 +ezdxf/addons/pycsg.py,sha256=mDhsSSxcj1EOdkzUh06DvsyvqXvOSXP0broWoz4_cGU,15434 +ezdxf/addons/r12export.py,sha256=ujk6ogAW1O1oNJOOCWzTiCaP3GqFfc02UWaNi0SquNk,21665 +ezdxf/addons/r12writer.py,sha256=MEghiMHb0NSTkrnGdNHf5SoJhiRym0ZES91C6b8MbxA,25958 +ezdxf/addons/sierpinski_pyramid.py,sha256=8tIedR9aVCoM2uMEylTupbJViy5KzEEIZZ8sE1gN8ZE,7370 +ezdxf/addons/tablepainter.py,sha256=XOjwM5NGspmArCJGNiS36LLFg7dDntxuMNAYhTC465o,32240 +ezdxf/addons/text2path.py,sha256=4raio53vMolTbhewzK5CZBtB4lv1oUptGPPVD0gvbi8,12410 +ezdxf/addons/xplayer.py,sha256=vqAphNOmQo8Ji6xnPh7MyMhO4IQhWuc1l73HRaPVKzg,3245 +ezdxf/addons/xqt.py,sha256=FSQTMjHP8n4lHVJarU1KBJLQt4HbyQT6TfVPxPg4CKU,2226 +ezdxf/appsettings.py,sha256=fDIfzyGSg0br_focwxmb-0JBGGxzYBP3SqyTu6llsFs,4700 +ezdxf/audit.py,sha256=lsXO9X0_2hyCMFVLpPrjjo_u42wYo4s9C6jIE1ctV3M,20307 +ezdxf/bbox.py,sha256=qv22ZlNcsFTutFU8xH07-DhanQL42c1XELf49KiuCec,5149 +ezdxf/blkrefs.py,sha256=Vx4XKu6Ss9HNjXE9TRLxvFjHuaKLEVNH6nvslUrzWec,8803 +ezdxf/colors.py,sha256=LcILdkp8p2b5cZ-VSXTkY0hZVmmkro633U2lEuDtFvs,16706 +ezdxf/commands.py,sha256=RHL-HCy3G01un6q902xf_vi323BohTtVeJOcWlu3s38,32580 +ezdxf/comments.py,sha256=JGfD8EgJWP4AP4HK3YRJFeFFG56HMjac0N5nHTCL4Vg,1506 +ezdxf/disassemble.py,sha256=sgsgPXzptUL3GCphOnG65bQLyLtZqhU6aAmSGH5yeG8,21694 +ezdxf/document.py,sha256=HVAeusZO8pnFVVzy972F3Ytbekq4XHaWeeBicpoF01A,53771 +ezdxf/dwginfo.py,sha256=iI5SraX7TeoXVnVx3fcYd_5l8FjcQivMI0MybGJKlic,805 +ezdxf/dynblkhelper.py,sha256=4RRe4SOtBnVQylmkFLuZ8YVNEECYGbMz2OEEVHooxZo,2405 +ezdxf/edgeminer.py,sha256=Stjz_ipL4iKXEGFKYalHbTVt3VHj41TYqDb8seyMSRM,42037 +ezdxf/edgesmith.py,sha256=gG2TQJn8eNKM_fe5V-kE-lL7uocgR_gvOSEgKvv0uI0,35285 +ezdxf/entities/__init__.py,sha256=GJ9WEEe4FGSeOE3-l8MjVm_kxs0U69hlgpcd5KNA92U,3122 +ezdxf/entities/__pycache__/__init__.cpython-313.pyc,, +ezdxf/entities/__pycache__/acad_proxy_entity.cpython-313.pyc,, +ezdxf/entities/__pycache__/acad_table.cpython-313.pyc,, +ezdxf/entities/__pycache__/acad_xrec_roundtrip.cpython-313.pyc,, +ezdxf/entities/__pycache__/acis.cpython-313.pyc,, +ezdxf/entities/__pycache__/appdata.cpython-313.pyc,, +ezdxf/entities/__pycache__/appid.cpython-313.pyc,, +ezdxf/entities/__pycache__/arc.cpython-313.pyc,, +ezdxf/entities/__pycache__/attrib.cpython-313.pyc,, +ezdxf/entities/__pycache__/block.cpython-313.pyc,, +ezdxf/entities/__pycache__/blockrecord.cpython-313.pyc,, +ezdxf/entities/__pycache__/boundary_paths.cpython-313.pyc,, +ezdxf/entities/__pycache__/circle.cpython-313.pyc,, +ezdxf/entities/__pycache__/copy.cpython-313.pyc,, +ezdxf/entities/__pycache__/dictionary.cpython-313.pyc,, +ezdxf/entities/__pycache__/dimension.cpython-313.pyc,, +ezdxf/entities/__pycache__/dimstyle.cpython-313.pyc,, +ezdxf/entities/__pycache__/dimstyleoverride.cpython-313.pyc,, +ezdxf/entities/__pycache__/dxfclass.cpython-313.pyc,, +ezdxf/entities/__pycache__/dxfentity.cpython-313.pyc,, +ezdxf/entities/__pycache__/dxfgfx.cpython-313.pyc,, +ezdxf/entities/__pycache__/dxfgroups.cpython-313.pyc,, +ezdxf/entities/__pycache__/dxfns.cpython-313.pyc,, +ezdxf/entities/__pycache__/dxfobj.cpython-313.pyc,, +ezdxf/entities/__pycache__/ellipse.cpython-313.pyc,, +ezdxf/entities/__pycache__/factory.cpython-313.pyc,, +ezdxf/entities/__pycache__/geodata.cpython-313.pyc,, +ezdxf/entities/__pycache__/gradient.cpython-313.pyc,, +ezdxf/entities/__pycache__/hatch.cpython-313.pyc,, +ezdxf/entities/__pycache__/helix.cpython-313.pyc,, +ezdxf/entities/__pycache__/idbuffer.cpython-313.pyc,, +ezdxf/entities/__pycache__/image.cpython-313.pyc,, +ezdxf/entities/__pycache__/insert.cpython-313.pyc,, +ezdxf/entities/__pycache__/layer.cpython-313.pyc,, +ezdxf/entities/__pycache__/layout.cpython-313.pyc,, +ezdxf/entities/__pycache__/leader.cpython-313.pyc,, +ezdxf/entities/__pycache__/light.cpython-313.pyc,, +ezdxf/entities/__pycache__/line.cpython-313.pyc,, +ezdxf/entities/__pycache__/ltype.cpython-313.pyc,, +ezdxf/entities/__pycache__/lwpolyline.cpython-313.pyc,, +ezdxf/entities/__pycache__/material.cpython-313.pyc,, +ezdxf/entities/__pycache__/mesh.cpython-313.pyc,, +ezdxf/entities/__pycache__/mleader.cpython-313.pyc,, +ezdxf/entities/__pycache__/mline.cpython-313.pyc,, +ezdxf/entities/__pycache__/mpolygon.cpython-313.pyc,, +ezdxf/entities/__pycache__/mtext.cpython-313.pyc,, +ezdxf/entities/__pycache__/mtext_columns.cpython-313.pyc,, +ezdxf/entities/__pycache__/objectcollection.cpython-313.pyc,, +ezdxf/entities/__pycache__/oleframe.cpython-313.pyc,, +ezdxf/entities/__pycache__/pattern.cpython-313.pyc,, +ezdxf/entities/__pycache__/point.cpython-313.pyc,, +ezdxf/entities/__pycache__/polygon.cpython-313.pyc,, +ezdxf/entities/__pycache__/polyline.cpython-313.pyc,, +ezdxf/entities/__pycache__/shape.cpython-313.pyc,, +ezdxf/entities/__pycache__/solid.cpython-313.pyc,, +ezdxf/entities/__pycache__/spatial_filter.cpython-313.pyc,, +ezdxf/entities/__pycache__/spline.cpython-313.pyc,, +ezdxf/entities/__pycache__/subentity.cpython-313.pyc,, +ezdxf/entities/__pycache__/sun.cpython-313.pyc,, +ezdxf/entities/__pycache__/table.cpython-313.pyc,, +ezdxf/entities/__pycache__/temporary_transform.cpython-313.pyc,, +ezdxf/entities/__pycache__/text.cpython-313.pyc,, +ezdxf/entities/__pycache__/textstyle.cpython-313.pyc,, +ezdxf/entities/__pycache__/tolerance.cpython-313.pyc,, +ezdxf/entities/__pycache__/ucs.cpython-313.pyc,, +ezdxf/entities/__pycache__/underlay.cpython-313.pyc,, +ezdxf/entities/__pycache__/view.cpython-313.pyc,, +ezdxf/entities/__pycache__/viewport.cpython-313.pyc,, +ezdxf/entities/__pycache__/visualstyle.cpython-313.pyc,, +ezdxf/entities/__pycache__/vport.cpython-313.pyc,, +ezdxf/entities/__pycache__/xdata.cpython-313.pyc,, +ezdxf/entities/__pycache__/xdict.cpython-313.pyc,, +ezdxf/entities/__pycache__/xline.cpython-313.pyc,, +ezdxf/entities/acad_proxy_entity.py,sha256=k0Txnw3JwrNyrdc-Sa0ESxFHG7qvaU7X2Sc5J9s1V5s,5563 +ezdxf/entities/acad_table.py,sha256=ZiCdFQk3AI8Lw4fJyqVBjCavTiAXUKsv-fvKTkr0n_8,21102 +ezdxf/entities/acad_xrec_roundtrip.py,sha256=cun_M61SUwiZRb7GCxmZg3bbOY8jHxVOGZo4okFtCrI,2751 +ezdxf/entities/acis.py,sha256=ZePkt3TzXVdQQlDPg7iSjnwMgZv5lktCeoNbG_GEHYw,29430 +ezdxf/entities/appdata.py,sha256=LJGmiIQVAdmVHG1J0Fuqabd1NVdokgnUBbARcoFrh_I,4847 +ezdxf/entities/appid.py,sha256=5e9cgFB7VCu-WC1xq6XkK4WYI4k4DOBV0AEyzCbL1BQ,1892 +ezdxf/entities/arc.py,sha256=jTsVeQgl0ZJW435gqIRx-hrn-u4iDhOaO-HSRvZdwCU,4794 +ezdxf/entities/attrib.py,sha256=W29ro3dujsS0QYeC-SB_Vnx2uOPxnB9ykjR3k-Q3uEM,27210 +ezdxf/entities/block.py,sha256=KMnroNxI7ThnMqjXbDMVQHNRqVH0GRmJq-aCaK6B0W4,8704 +ezdxf/entities/blockrecord.py,sha256=4dyR9zqtWRbqI1hLvHFi4wQEY4Ny9PXvgyd0iRjK53A,10271 +ezdxf/entities/boundary_paths.py,sha256=WxzVRmmgsEs7yoDl2FK076X7TpkpVrHNw8TycOJ4Rhg,51485 +ezdxf/entities/circle.py,sha256=g2JRPzcEnvU9_ymmkN4pDyGujJvGsXhYCsO3ZhnXdp0,7715 +ezdxf/entities/copy.py,sha256=weAQSpuusAM_wJath0snmIwFO_mAJ6Iurxj3dqCW2v4,3112 +ezdxf/entities/dictionary.py,sha256=kb7x0BKl7ilNXiIdrsfTmzJ_w3NmYA1_fTwt57C6-cg,24571 +ezdxf/entities/dimension.py,sha256=I1B-R2MZ092JIVWTtmwsWghVe0hVyZCTBevbZ-aaRak,47493 +ezdxf/entities/dimstyle.py,sha256=lYbb5XWfWMVxu30ytYnFKe0DcD5RRqh36s8wygmOQ18,34084 +ezdxf/entities/dimstyleoverride.py,sha256=qy8zAzMnmyuwkDKVsXUTCY2b8HwqMX_p3pMQWoHIxLQ,23230 +ezdxf/entities/dxfclass.py,sha256=qsbi4-BrnseE4BbggY274U2HJ70VYqG3qfPzMZTP7tY,4276 +ezdxf/entities/dxfentity.py,sha256=xGNQHWfYtdpnNfzmvFfpvo3VQSq62J_ws1aPC91NFDY,39511 +ezdxf/entities/dxfgfx.py,sha256=QW7jqF9cv5vIkdokibZJHDEMncIsXMFFe4H__-zBIew,26572 +ezdxf/entities/dxfgroups.py,sha256=JZF-UHNQwMnQKGXWg-qTUyv7QwuMRYOdmqQ15stsOoA,16016 +ezdxf/entities/dxfns.py,sha256=nXUklakehk3RMUGno8jXg4UPXu_4EF5hAntgdRGvuuA,24179 +ezdxf/entities/dxfobj.py,sha256=RCb8vA-RBv_eJI1D6a68u0pQ6dsDTidHirTgmI8MxZw,13510 +ezdxf/entities/ellipse.py,sha256=gufHDNWF2JNA_Myy3MWAbzlrqk3KYU7ufJyLr2WA9hs,10866 +ezdxf/entities/factory.py,sha256=L6t2x5skuNS4WXrv-YMAygnytZZ2ewUe8ULcp5t888E,4062 +ezdxf/entities/geodata.py,sha256=mLJ2eW8csUJ-nt-9l5AZvGEctf_wUKZjTXMw84nk5FU,23124 +ezdxf/entities/gradient.py,sha256=airxBqEOMd31VJEov1Hlox6fL3ej_Wp7HTA9CIS0w6E,3902 +ezdxf/entities/hatch.py,sha256=n__tR1h50jil-GkSGrG37VPUTgBBkzlCgqDk0mm26x8,11940 +ezdxf/entities/helix.py,sha256=lDStumPEGF0q9i9O-VmpKQgmhBI7Gx3Sg9wCB5wCvR4,3822 +ezdxf/entities/idbuffer.py,sha256=LcFz9U4JCdhuTtwjN-dKROft2b9JbhhdbkK_Nl8ldFc,4699 +ezdxf/entities/image.py,sha256=q6nDqESS4MxHc2lxvXBmyHXCSTQWn4WKaOjRd_5Fyy8,26365 +ezdxf/entities/insert.py,sha256=UR8pxuyWQoA8Ei_LHdttLDNHwNK6ZoGXzjMMYHhiVEo,28458 +ezdxf/entities/layer.py,sha256=PDoSlurplXfzSEutc-Es1BcGoz6IuzmZmSAB0lTd15Y,27904 +ezdxf/entities/layout.py,sha256=rUyA6I9ea9xlC1Wn52_LdAVrWtcCeYwxEDDtSnte64E,13964 +ezdxf/entities/leader.py,sha256=kY4gocMUL3OT1pEU_5vUIGWjPJhX_ecji_hkc37Rgjw,12710 +ezdxf/entities/light.py,sha256=557KDdPCJP0mFyC4mvq6081v6XrgK21kWTGKNMWAA3I,4566 +ezdxf/entities/line.py,sha256=9e1fM2iWwPcDlmYrQCrqiTBKgA6P1B-e4RJb9OwW0mQ,3608 +ezdxf/entities/ltype.py,sha256=k4JMNhH3ZQWhbhXhySBBgWEVXeCbW64lNClL4ruJ3Vk,9493 +ezdxf/entities/lwpolyline.py,sha256=xPXikzoB_i32eUczX_-fix16Zsdt0UwcaknuAS9B8DU,18516 +ezdxf/entities/material.py,sha256=1ZD1HPKeLH79XcUaxTBkbO2OFZpHqZxSM9iaLaT_hWU,18920 +ezdxf/entities/mesh.py,sha256=PS9e477O27jpFmfejHgTJdKXEf2D5WtkJZMHFY3G9UQ,17865 +ezdxf/entities/mleader.py,sha256=kwPTPEmrIA8i4vZZwF98L2Ghl8ghYYuObiASGDqwWlk,55967 +ezdxf/entities/mline.py,sha256=7uRs2j0dLj-gU89EePC8Dtiz342FazhJCyxEb1e8YDg,36262 +ezdxf/entities/mpolygon.py,sha256=4sgv9axllTQU1UNY1ok2iqPoXmqS2OByLH7-bPhm-jc,8144 +ezdxf/entities/mtext.py,sha256=Nl478O-UJi7f0EOGAMNacF3pNTEnAfKT2e8HuOjDn5o,46978 +ezdxf/entities/mtext_columns.py,sha256=UJ-lLnv_dCndGyYgh3aeMwWIEa9UBS2pSKxRN11-Zqo,4197 +ezdxf/entities/objectcollection.py,sha256=H36yRD74xRHRFulPtsy7sYlJD7YptkBTl1Oh89I650g,6037 +ezdxf/entities/oleframe.py,sha256=o8Mbec7LoIilrH5C5f5wdeaePURPrRDzz1fyE5YO12U,2094 +ezdxf/entities/pattern.py,sha256=WOOA6gRNwaepm1DPhMjlcXeyNBjmlJ3pvri4GPIrtJI,4198 +ezdxf/entities/point.py,sha256=KEmbPtHnXhhSU8jBPa_DJoXIevUIqyuTHV8Wk5a9vd8,5093 +ezdxf/entities/polygon.py,sha256=UndK5P2ddtWIXFeVSU_-gK5Gemkm9ng_pRYQMMeWuvM,16516 +ezdxf/entities/polyline.py,sha256=U_Z5eFAj2KD_DRTqR_DyYXoPaw6UXD2YoHUgwqPj1w8,39829 +ezdxf/entities/shape.py,sha256=7cmHVRy8mW7EJw4eEiHWuotYKBOLhT7mCM-hLWMxvQU,4684 +ezdxf/entities/solid.py,sha256=ql58Sduwmjop6io69bCU5CQm41pqQPxhSdzJCkPGha4,10206 +ezdxf/entities/spatial_filter.py,sha256=kLCRY4d70HYNDG34_odwmUJ6JW1VaVW9kqgfQXUyctU,7789 +ezdxf/entities/spline.py,sha256=3tDU7WOK6wRYVYntN1UjDUInNCIe9F4j3Gas5OR6gyE,23261 +ezdxf/entities/subentity.py,sha256=q1nbMTljeMAUixFHI839MM4MFGSoB-Dh8-hrep3tAOk,8165 +ezdxf/entities/sun.py,sha256=AshVsCplyOZ_OX2xAiDUUumXJwgMxc6A0sHeuBdMonM,5042 +ezdxf/entities/table.py,sha256=kVt8qZjNVqNyUKyXYrGQMOxgBoo0zStyZAp51dndPEg,2378 +ezdxf/entities/temporary_transform.py,sha256=A4-Y6IeqR7CPmSdJu9um7RVVHTKqHTBTFiRC6RUIjH8,1292 +ezdxf/entities/text.py,sha256=L9DoBIgkA1kkGmU0Ax1_C7BxtRbPsWfxb7j5JJzcnuA,17150 +ezdxf/entities/textstyle.py,sha256=qYkBvQf_7v940wjxm7gk0vU0vUYXTZjvwhN4cnqzdSA,8805 +ezdxf/entities/tolerance.py,sha256=oZ1vKmO-3zYGrWv3QNWTGtzz7Qx2TUhotrCc0sIGi6w,3512 +ezdxf/entities/ucs.py,sha256=z6nsc9Vl7ZWsKe-KktZAC4HDZm2TNBIQWhdln5igtOc,2618 +ezdxf/entities/underlay.py,sha256=nHFcTU3_XEqUuqbP0QWfTUJM0U071m5vZXMILTfIMGQ,14006 +ezdxf/entities/view.py,sha256=mRDuYa6tjhhF-52MAS-J9lhFTN2CFc-xQ8jTmncyJMM,5864 +ezdxf/entities/viewport.py,sha256=dW7FtNRgCmPH9k3VdYPsU4z08P5IMuYwcCI56YdhiFE,28601 +ezdxf/entities/visualstyle.py,sha256=RF1aGelaGYF6tTHnw3Po1vJ5PuguQ_Dm6a6thoS_gJA,7723 +ezdxf/entities/vport.py,sha256=UnLUIbH2QCf6qTE9YOLR9dLFPn89SIueRQ0MNVAAbcg,9711 +ezdxf/entities/xdata.py,sha256=m9hQq_iC4T1DXMLr4THoQqr04k8tkA1k4cvri4MBZII,16493 +ezdxf/entities/xdict.py,sha256=HpaHgXUqwSrp9E9krLreccZjfcdMX8NvZDL5sZT6gi4,8290 +ezdxf/entities/xline.py,sha256=Y_0Choa2Gl99zWEyvKp9PCAs4Ik8uTwehWz23cKUhfA,2967 +ezdxf/entitydb.py,sha256=vXnG0PCEzWc1WrJ8gw8AcyKgGcvDTAlqi6_R27ELCRI,15822 +ezdxf/enums.py,sha256=z99GMOCnsbJTZAtM9YGEMpQZJn9oRNhwanieLyy2CoM,7242 +ezdxf/explode.py,sha256=vXdLJvuWggnYjXgB9udHp3Y1x4emlS8aHr-AdGBRrqM,14117 +ezdxf/eztypes.py,sha256=j1Er5NWEZFh799rv-z-oH2kUc4RkisqBX89fz_T1wV4,1590 +ezdxf/filemanagement.py,sha256=RtO1ZXOJ3ojImcNOfDYc40nw32yszT_apGYdnDtvnnc,10088 +ezdxf/fonts/__init__.py,sha256=rKDBFaBNLWqK3LvQyYFAPqdLAdMcudPIgvAXHDDYPno,62 +ezdxf/fonts/__pycache__/__init__.cpython-313.pyc,, +ezdxf/fonts/__pycache__/font_face.cpython-313.pyc,, +ezdxf/fonts/__pycache__/font_manager.cpython-313.pyc,, +ezdxf/fonts/__pycache__/font_measurements.cpython-313.pyc,, +ezdxf/fonts/__pycache__/font_synonyms.cpython-313.pyc,, +ezdxf/fonts/__pycache__/fonts.cpython-313.pyc,, +ezdxf/fonts/__pycache__/glyphs.cpython-313.pyc,, +ezdxf/fonts/__pycache__/lff.cpython-313.pyc,, +ezdxf/fonts/__pycache__/shapefile.cpython-313.pyc,, +ezdxf/fonts/__pycache__/ttfonts.cpython-313.pyc,, +ezdxf/fonts/font_face.py,sha256=657LenF0Q5gSuKNVaTt0H-uLfjroqfw-_lvXhQcgWEk,2164 +ezdxf/fonts/font_manager.py,sha256=5coOTLwgCmWUjvyZX2mh8m5qTEuaXOXyfp33sHkXAO8,18346 +ezdxf/fonts/font_measurements.py,sha256=3zlfzJOB45q88EjE9RKoPYIObLKsRXh_0ewssZibkOs,1648 +ezdxf/fonts/font_synonyms.py,sha256=M7zeZsCVSJBtF4Pb_gXsF_qOB8cl6_uSIbxUBQ9VvyE,278 +ezdxf/fonts/fonts.py,sha256=f-j6KJ4Z-zaUpRclucfOD9ut1G6cRijXeMRBZP13qQo,25592 +ezdxf/fonts/glyphs.py,sha256=DmMV9mR2BMztFY30_X52LlDZ27Yh4PkbU24ecWXdzEg,1136 +ezdxf/fonts/lff.py,sha256=V3m1_WCq3NLqoj02we0pRd7Uie0YJIaW9K9Pl8CfEmk,10439 +ezdxf/fonts/shapefile.py,sha256=9VDlVuDc-B25GEdvCTxVGKPK1n8DF1vB2ZxAwB1hQYU,35090 +ezdxf/fonts/ttfonts.py,sha256=agU5nJXg_Krbj9PMMRFfHFQLp9FNwLMRToHUPY9uYT0,7038 +ezdxf/gfxattribs.py,sha256=-14ORlpVdRCH7M3WLgP5cvi29uMAFNfMFSKJRMYIZi4,11830 +ezdxf/graphicsfactory.py,sha256=nmIBlqJSfKMCtzmhcvl_ms4OZdEcxvY8fHCaA-a1-Lg,104834 +ezdxf/groupby.py,sha256=LL3J5V-Fj6mfXaL4WXnpB6EVxxJ_rTUnWjLxM0hKAtc,3322 +ezdxf/layouts/__init__.py,sha256=y3FjuUOMXUxOXb-nfN-p3MTF090Xy6IJcKsYD_vEaHo,226 +ezdxf/layouts/__pycache__/__init__.cpython-313.pyc,, +ezdxf/layouts/__pycache__/base.cpython-313.pyc,, +ezdxf/layouts/__pycache__/blocklayout.cpython-313.pyc,, +ezdxf/layouts/__pycache__/layout.cpython-313.pyc,, +ezdxf/layouts/__pycache__/layouts.cpython-313.pyc,, +ezdxf/layouts/base.py,sha256=tzusCj3AbhUf5xeCuJyhh-bwtEFVAqXeZBbL06LFP4M,16510 +ezdxf/layouts/blocklayout.py,sha256=eGCYBh8fuNMKSheCWHJdXCnwR2ZpWP-6i_Gbt_4Q7h8,4207 +ezdxf/layouts/layout.py,sha256=_W0EUTDYSxzCb5jsY979HWCwCPDt0USXyYHrbT0siWw,31598 +ezdxf/layouts/layouts.py,sha256=rK8hM2oVTFWTR5Ow7Bz6nKVR6nFilFoKZS9UNDeNqCk,14889 +ezdxf/lldxf/__init__.py,sha256=XymM7BIVJ7315eruh5rosbEjYvYAHqc1lOOznifkPas,89 +ezdxf/lldxf/__pycache__/__init__.cpython-313.pyc,, +ezdxf/lldxf/__pycache__/attributes.cpython-313.pyc,, +ezdxf/lldxf/__pycache__/const.cpython-313.pyc,, +ezdxf/lldxf/__pycache__/encoding.cpython-313.pyc,, +ezdxf/lldxf/__pycache__/extendedtags.cpython-313.pyc,, +ezdxf/lldxf/__pycache__/fileindex.cpython-313.pyc,, +ezdxf/lldxf/__pycache__/hdrvars.cpython-313.pyc,, +ezdxf/lldxf/__pycache__/loader.cpython-313.pyc,, +ezdxf/lldxf/__pycache__/packedtags.cpython-313.pyc,, +ezdxf/lldxf/__pycache__/repair.cpython-313.pyc,, +ezdxf/lldxf/__pycache__/tagger.cpython-313.pyc,, +ezdxf/lldxf/__pycache__/tags.cpython-313.pyc,, +ezdxf/lldxf/__pycache__/tagwriter.cpython-313.pyc,, +ezdxf/lldxf/__pycache__/types.cpython-313.pyc,, +ezdxf/lldxf/__pycache__/validator.cpython-313.pyc,, +ezdxf/lldxf/attributes.py,sha256=_rZ4r478SJa3l-vTgIk7buGz-HYu5D5Vyk0gqz-AD-I,8072 +ezdxf/lldxf/const.py,sha256=csymQrJX84fSZb8LJUCdr3Kq3mAlOdtuN3I-iq_tFks,15941 +ezdxf/lldxf/encoding.py,sha256=IDrrERO5gph7d2bc1xCTOCGkzX71qogA8AVWX9XJIe4,2630 +ezdxf/lldxf/extendedtags.py,sha256=qTtQxVEqlx8NrhjmbbLgJ7EubBx9Og8OgGByprJBeKk,16534 +ezdxf/lldxf/fileindex.py,sha256=su8fwkZgQdlYqFZXgdRvItUCZg8193lP9FkcudSQNB0,5205 +ezdxf/lldxf/hdrvars.py,sha256=K5K9bgC9oasLrjjHhe1GD1Mg1jH9gF2lHqbfGCcCYqw,701 +ezdxf/lldxf/loader.py,sha256=PquVaNtY_Y2fCcAnJKLMiupH8FymH5eF0nR-iJAN83M,5313 +ezdxf/lldxf/packedtags.py,sha256=ZabJ8qsfuM-KX5xJikhpsu-dhkZmw5f9juOakDV2yIk,6944 +ezdxf/lldxf/repair.py,sha256=kD8rAufIseS2RiNKNIRqZlP2xCwM8ZTc7CEKrgt9lCU,6159 +ezdxf/lldxf/tagger.py,sha256=A8Xq-tX16CVwq3KBW7EH5anvQE2jbgRs3Ml0LrWU6X0,14125 +ezdxf/lldxf/tags.py,sha256=9TB0-OtlHKLKeX9v9w-VMsmNOio4tvyfXMJTlab-XC4,13867 +ezdxf/lldxf/tagwriter.py,sha256=LK9PtXpxNxrBTJGQjcfKB_dXqyJmcF5p4HpjmNaRCGg,10738 +ezdxf/lldxf/types.py,sha256=ay1zuRlBkOwG3rj2iHnAe86rwx_tMnG6F1oqq5t0m0Q,11528 +ezdxf/lldxf/validator.py,sha256=yW058HhQCrXKXDz_Ezk0HFBGerKYkBHlzcJ_nu6ebRk,16761 +ezdxf/math/__init__.py,sha256=FGp-mTRXuGAOstYmZpLmeb1D09iBCCsYFWOFiK3SdcE,1913 +ezdxf/math/__pycache__/__init__.cpython-313.pyc,, +ezdxf/math/__pycache__/_bezier3p.cpython-313.pyc,, +ezdxf/math/__pycache__/_bezier4p.cpython-313.pyc,, +ezdxf/math/__pycache__/_bspline.cpython-313.pyc,, +ezdxf/math/__pycache__/_construct.cpython-313.pyc,, +ezdxf/math/__pycache__/_ctypes.cpython-313.pyc,, +ezdxf/math/__pycache__/_mapbox_earcut.cpython-313.pyc,, +ezdxf/math/__pycache__/_matrix44.cpython-313.pyc,, +ezdxf/math/__pycache__/_vector.cpython-313.pyc,, +ezdxf/math/__pycache__/arc.cpython-313.pyc,, +ezdxf/math/__pycache__/bbox.cpython-313.pyc,, +ezdxf/math/__pycache__/bezier.cpython-313.pyc,, +ezdxf/math/__pycache__/bezier_interpolation.cpython-313.pyc,, +ezdxf/math/__pycache__/box.cpython-313.pyc,, +ezdxf/math/__pycache__/bspline.cpython-313.pyc,, +ezdxf/math/__pycache__/bulge.cpython-313.pyc,, +ezdxf/math/__pycache__/circle.cpython-313.pyc,, +ezdxf/math/__pycache__/clipping.cpython-313.pyc,, +ezdxf/math/__pycache__/clustering.cpython-313.pyc,, +ezdxf/math/__pycache__/construct2d.cpython-313.pyc,, +ezdxf/math/__pycache__/construct3d.cpython-313.pyc,, +ezdxf/math/__pycache__/cspline.cpython-313.pyc,, +ezdxf/math/__pycache__/curvetools.cpython-313.pyc,, +ezdxf/math/__pycache__/ellipse.cpython-313.pyc,, +ezdxf/math/__pycache__/eulerspiral.cpython-313.pyc,, +ezdxf/math/__pycache__/legacy.cpython-313.pyc,, +ezdxf/math/__pycache__/linalg.cpython-313.pyc,, +ezdxf/math/__pycache__/line.cpython-313.pyc,, +ezdxf/math/__pycache__/offset2d.cpython-313.pyc,, +ezdxf/math/__pycache__/parametrize.cpython-313.pyc,, +ezdxf/math/__pycache__/perlin.cpython-313.pyc,, +ezdxf/math/__pycache__/polyline.cpython-313.pyc,, +ezdxf/math/__pycache__/rtree.cpython-313.pyc,, +ezdxf/math/__pycache__/shape.cpython-313.pyc,, +ezdxf/math/__pycache__/transformtools.cpython-313.pyc,, +ezdxf/math/__pycache__/triangulation.cpython-313.pyc,, +ezdxf/math/__pycache__/ucs.cpython-313.pyc,, +ezdxf/math/_bezier3p.py,sha256=VDj3qgzkLUTUV4wRNMdkvqghA32uAr1Ckh7k5P_g7_Q,6510 +ezdxf/math/_bezier4p.py,sha256=I8X-ahppGS4qsFjr8G8W626HRRdfsVYcUtYYrFCqW6M,11540 +ezdxf/math/_bspline.py,sha256=hNr-sYZysqFxqpkmQsVCUyAY6E4iPBAuR8gpTM26Uis,9219 +ezdxf/math/_construct.py,sha256=3e7RYmXbhvI1HkjKfz3Ue07XPXN7Zr925kIwvPlya5w,12115 +ezdxf/math/_ctypes.py,sha256=VhSkTg4oPSv7W4G2lDbKa8gxRr1vgfuGOc5wP3CChTc,2447 +ezdxf/math/_mapbox_earcut.py,sha256=zTy1ZJjLgEhwGMcjPBexl9SKbOlUyymLr_ulWIJHFok,23981 +ezdxf/math/_matrix44.py,sha256=rARL85Y_lcLOQuAS_o-ovLoSVpVRNUCiu1qaSGQLH6I,22039 +ezdxf/math/_vector.py,sha256=7CTxQIoy5v3F6yPV-yBeVdhU-W3vxuj-N1fS612GcIU,25057 +ezdxf/math/arc.py,sha256=Q1I6zfv9GSSiAHAP7dZyy_3lbXHnu0bs0IppFucn33k,18745 +ezdxf/math/bbox.py,sha256=Ph5fT35cn5AlKbZcYhYSOVvrSnfcahmB-nwuyqKmFHQ,15075 +ezdxf/math/bezier.py,sha256=LXqoi2zHEX4ack4nVRV4jwYIf76zxh8WlzXTa57-NLg,9050 +ezdxf/math/bezier_interpolation.py,sha256=n3DPzcoIH41TUjlywX23KkYTkDBCo3NbvDno3pd2bFM,2382 +ezdxf/math/box.py,sha256=8voKOf7S4HD-P1dGuzT6jW6X2bURTaLdaqCHnmpl_3w,8462 +ezdxf/math/bspline.py,sha256=mQjGQo7fMFNeyKrGxoOTiQNJZo45GQat_2lG0DvpFO8,68754 +ezdxf/math/bulge.py,sha256=rxjx9FdEU5vdvEjhRDASlmHDVojkSWhHurfoaCwYZt0,5688 +ezdxf/math/circle.py,sha256=u3YCtrE6wFzCAJ_2UKi9DVXHKpd0ffSJ5Is1vPI0Bpw,8886 +ezdxf/math/clipping.py,sha256=yLL5aCLTo2ukRG2dTdhSxF-GLEXNxsSbIJ1P4cgWHlM,33803 +ezdxf/math/clustering.py,sha256=14ICSNKs6y2KXdR1AbjFDdtTvm9mMeroJzOfjDDRLZk,4178 +ezdxf/math/construct2d.py,sha256=B1NX85k7chzXpljMS-CaR7rN5-ld125RB0F0hf1Xpm4,11238 +ezdxf/math/construct3d.py,sha256=GbCLRrgGqnG3U3dymetrCgb0A8G0xLOLKJr8EBTUO90,26965 +ezdxf/math/cspline.py,sha256=4JC-aofxlPrY0Jmuv4Ik32ta27tLvnpWEw7vHLc4_8M,1233 +ezdxf/math/curvetools.py,sha256=RyQKxKRd3S1bWbwnc-wWQKcE1NCd_Ebdl5zQfDY0504,8828 +ezdxf/math/ellipse.py,sha256=U1aFFjtOHh-0_FgzUI0EwIV0JdmkYCQLelxITnlP-gg,21124 +ezdxf/math/eulerspiral.py,sha256=E8m1-BmoTfxF6pFrszyRYC-Ktrmq9in0LE3gnJ-3aZo,4270 +ezdxf/math/legacy.py,sha256=6oUJfduDjDLSc5i9LBFgyj2F8bL7vQpeXok6bwNnd5Y,12773 +ezdxf/math/linalg.py,sha256=qwMyceImEjKFl3LEMZC4obVPVLVJbcT9d0ByU330FqI,26484 +ezdxf/math/line.py,sha256=Hewiv4a48nLLHLHSZ2lN_hdiXCQRDtsZa28Hrlu4Yys,9903 +ezdxf/math/offset2d.py,sha256=Y_cus09Uf4GSyDy-nPybJC_cdnGzS3qh_1W3By72Ozw,2978 +ezdxf/math/parametrize.py,sha256=ghTH7S7kZVnVqdw2J5Z6fN1UVFMgN3nW71QHKu5TWKc,7916 +ezdxf/math/perlin.py,sha256=MgtvqMQyRwg1KkJTrr_kxFsn58d1PD9FQ17o-WpgzqU,15176 +ezdxf/math/polyline.py,sha256=SBQqrBxZmDEL8KCr3qgk1bXXZ--NHXwiK3IUNEc30o4,15460 +ezdxf/math/rtree.py,sha256=RYGyN2AAr1XFac0HVLdtyfIGriG-YxLWfpAC-WeRNEI,11397 +ezdxf/math/shape.py,sha256=cNi8ElC55dcq6UDpasTKqzgGLfiH7q50tiUjut2tmX8,4650 +ezdxf/math/transformtools.py,sha256=3WYL4b8bhWMX1bbkS-wR_TxcGhfY9dzcBLNSciV9cDM,11808 +ezdxf/math/triangulation.py,sha256=ksI4-rIFG7lqQ5QE4MUPGtMl3ssaRRcv9FPX3R3oPko,3433 +ezdxf/math/ucs.py,sha256=pNcQgIlZo6UDrTeaQMTR1U1XZxCHg0uhKsczNXqr9Ow,16599 +ezdxf/messenger.py,sha256=dILPbxkuP-So7Q-rcaVmhajPhbpq4_SJcsZDYdzlkTw,639 +ezdxf/msgtypes.py,sha256=Iz-O-Kwc1bvc0kWT0U6a9tF_YEX4GdJvbtEqgnhAc7I,264 +ezdxf/npshapes.py,sha256=jaFBpydaEZXIq7lWyVNwgPNZNHOleXOs1KerFBEWZNU,19951 +ezdxf/path/__init__.py,sha256=IHMlqFX_q_VzvlSceZwa8pLyoIZfoJRhgOXqCUsOVhQ,371 +ezdxf/path/__pycache__/__init__.cpython-313.pyc,, +ezdxf/path/__pycache__/commands.cpython-313.pyc,, +ezdxf/path/__pycache__/converter.cpython-313.pyc,, +ezdxf/path/__pycache__/nesting.cpython-313.pyc,, +ezdxf/path/__pycache__/path.cpython-313.pyc,, +ezdxf/path/__pycache__/shapes.cpython-313.pyc,, +ezdxf/path/__pycache__/tools.cpython-313.pyc,, +ezdxf/path/commands.py,sha256=shqssckUalqNH1NVXG4u3_6soBYH5N71LK2nWX7Axsg,1242 +ezdxf/path/converter.py,sha256=zj8C9-wFmq1KcthWyWn4vbPyZ0OjYQivzSnr1few2PI,30333 +ezdxf/path/nesting.py,sha256=GUHz5Fi4jbGj32c8Hd1UvjJRF-dd7uP3vinau0SpT0s,5699 +ezdxf/path/path.py,sha256=lKabV_DAhzfYikBmIekVIm8UPnhxbb0T-JUA7ObZLwE,17717 +ezdxf/path/shapes.py,sha256=KdxTK17ensT0uCv4HL4mNiL_cCqCRRd69xWAPdV9q8Y,9823 +ezdxf/path/tools.py,sha256=pQeFifDmBauG3PxuYQN5EU2vcER-EzTlQYmFBIagAyQ,33196 +ezdxf/protocols.py,sha256=XX-EDbfp2V8TCvj4KoT5r9qK_lM6wDFWienXAnr6WzE,2934 +ezdxf/proxygraphic.py,sha256=-s2wu18E3sRwNr1fjZJ7RE93BtYQROQkA1C6dPwpOgU,34535 +ezdxf/py.typed,sha256=UaCuPFa3H8UAakbt-5G8SPacldTOGvJv18pPjUJ5gDY,93 +ezdxf/query.py,sha256=69kTX5HeX-_nbyiq6j-7YwBHDPpUbJX_QQLMrGgnj20,21868 +ezdxf/queryparser.py,sha256=uNMn4gZeLkCzDrmgjD7_m6qHkvR4MC6Gl9Wrt6KicXk,2702 +ezdxf/r12strict.py,sha256=FZ2yCea3hs2vZbckV15mX22bf-ue6QTASKgzPkPBZx8,9306 +ezdxf/recover.py,sha256=EVEuxJll7iLprPSM2e6IRGsiv48kJ5to7J4KSwdQztI,30923 +ezdxf/render/__init__.py,sha256=WYBFfY_pr8YSN9JO9guhHZBBgcCdSp_gyeWXO-krYMQ,748 +ezdxf/render/__pycache__/__init__.cpython-313.pyc,, +ezdxf/render/__pycache__/_linetypes.cpython-313.pyc,, +ezdxf/render/__pycache__/abstract_mtext_renderer.cpython-313.pyc,, +ezdxf/render/__pycache__/arrows.cpython-313.pyc,, +ezdxf/render/__pycache__/curves.cpython-313.pyc,, +ezdxf/render/__pycache__/dim_base.cpython-313.pyc,, +ezdxf/render/__pycache__/dim_curved.cpython-313.pyc,, +ezdxf/render/__pycache__/dim_diameter.cpython-313.pyc,, +ezdxf/render/__pycache__/dim_linear.cpython-313.pyc,, +ezdxf/render/__pycache__/dim_ordinate.cpython-313.pyc,, +ezdxf/render/__pycache__/dim_radius.cpython-313.pyc,, +ezdxf/render/__pycache__/dimension.cpython-313.pyc,, +ezdxf/render/__pycache__/forms.cpython-313.pyc,, +ezdxf/render/__pycache__/hatching.cpython-313.pyc,, +ezdxf/render/__pycache__/leader.cpython-313.pyc,, +ezdxf/render/__pycache__/linetypes.cpython-313.pyc,, +ezdxf/render/__pycache__/mesh.cpython-313.pyc,, +ezdxf/render/__pycache__/mleader.cpython-313.pyc,, +ezdxf/render/__pycache__/mline.cpython-313.pyc,, +ezdxf/render/__pycache__/point.cpython-313.pyc,, +ezdxf/render/__pycache__/polyline.cpython-313.pyc,, +ezdxf/render/__pycache__/r12spline.cpython-313.pyc,, +ezdxf/render/__pycache__/trace.cpython-313.pyc,, +ezdxf/render/_linetypes.py,sha256=sPCkFOhgVmia1tK2nk_mEA0A6EK6LxRIcfrsZPQgUh4,2805 +ezdxf/render/abstract_mtext_renderer.py,sha256=TwqtrtpUbr-58yIr-fGhYLyVGMensvwVHlJkB2U-qRI,9868 +ezdxf/render/arrows.py,sha256=W0Mn2VcXzpxsLd01KieJpNyiAzdfCUhf6a4shVOD2fg,19869 +ezdxf/render/curves.py,sha256=l-o7j-WuQ3AAx3tBrkLcyg6cpZt0-1EtxN9jLv-ecY8,17241 +ezdxf/render/dim_base.py,sha256=LP00oDaXB8FmFFewCU1nQmuWtB1LQBSgXMqUR9BG3EA,50169 +ezdxf/render/dim_curved.py,sha256=HBgENuRUZQ190M73Wvj-n97SLnPgpPtSwqxS0ivQlkU,34725 +ezdxf/render/dim_diameter.py,sha256=xg-GlGuvQ0JYTz7M3RBjtKmjyQ30bXLYbHZUIiiwcD4,6719 +ezdxf/render/dim_linear.py,sha256=s5g6i4-oIM9hSHLyjVR4vIPWDCnEyfqy8TGJg3YyOas,24102 +ezdxf/render/dim_ordinate.py,sha256=It1tMg7Fyfqqh-h7GfHNe3GCzMNEChdoEKOsfEmcvQ0,7875 +ezdxf/render/dim_radius.py,sha256=-du3CysT0hHy2fxUYtXQ_uS3sdqyk46O8i7OJzopo-A,19791 +ezdxf/render/dimension.py,sha256=BDBq8ELlzdzlrTN-BBlR6cpXK0eR4-gQ56nsQFKt8gA,3923 +ezdxf/render/forms.py,sha256=XwHx9F_rm5WlKBEQNrGOnchsAPqMvwVGSS47JYWtQj0,45736 +ezdxf/render/hatching.py,sha256=pgHElSxUDJfq4xFRc_fT-BJhK9PZAhDJbbHhmg6803k,25080 +ezdxf/render/leader.py,sha256=LnP_0HnGpVm9IwLvZFsvgIvdJFT8Mm9iIHKPE-EU9nc,4602 +ezdxf/render/linetypes.py,sha256=Y-Iuyntx7psmmWalfKC2Mky2BnNMlVjTzVGG74mAxss,643 +ezdxf/render/mesh.py,sha256=pWsRBb3rbPKvFu-6cLZzjr2FY0yASAaL-00eIYZ6RnM,63455 +ezdxf/render/mleader.py,sha256=AlL1cAAdl6O8xeJpIPh6KAdL3FdgHExWg5Zo5qmQgYA,59270 +ezdxf/render/mline.py,sha256=w8G9O-O45Bz3EBsDZdjtU12eiiZDYSc4Q6qaL2wRPAo,8208 +ezdxf/render/point.py,sha256=C3Bu9XahAWcEAuQmWB6yleCvl8NB-s0i_QAGJu16hzQ,2876 +ezdxf/render/polyline.py,sha256=_jDOKz6EvlHOTasuyL4K-x7TGJLJzkqvAdm9CevCm6Y,8509 +ezdxf/render/r12spline.py,sha256=OVG943a_0Bci4C8rjLp0dJPz6B3GvSH8ggtPAS8gQyA,7650 +ezdxf/render/trace.py,sha256=S8_9iwnVhZe3kgbyukJnl0qOdebEaUZdW6Nfa4Xu3TU,23162 +ezdxf/reorder.py,sha256=_tDv3Wvicavwl6NaOuTNQm7xyJMqIqzb9u2RxCxDALQ,3415 +ezdxf/resources/16x16.png,sha256=ylZOyLGbIIB2ZelGT8wHuQ5_TlHP30qtebpY0mp4TAk,1050 +ezdxf/resources/24x24.png,sha256=Un0JyM8ttmSnW1jPsqIvnAvkPH36-ZtBJuQKMkBoX2E,1420 +ezdxf/resources/256x256.png,sha256=yj9AbmFwTPYVia0Q7Adet69E68zYwaH1YEe9lXoG7m0,10638 +ezdxf/resources/32x32.png,sha256=sDgIMCJQqAjG_eZ_NFHwrltZT3ltBXpaOrglMzbUNh8,1758 +ezdxf/resources/48x48.png,sha256=VJZ58M-arTIOZfqSjWaBuXv5_TmXRnzGMuIhMhP-9Bo,2335 +ezdxf/resources/64x64.png,sha256=uuO4j37xy0Zre1aqfKRjMIkRBfYGK6koDifouWOSIC0,3050 +ezdxf/resources/icon-copy-64px.png,sha256=AzeuLIbmWpundE3BkLHwppWjzsT6QRmjdeWmWqYz4IM,2090 +ezdxf/resources/icon-find-64px.png,sha256=CPCRoS9u13uoi919iArUnMIb3oEmVE6tWxq-7AUiZKU,3109 +ezdxf/resources/icon-goto-bookmark-64px.png,sha256=xqTPI9F9qgNY8CMKC-DEmrTYPhDN4zaJBKhBCs29etg,2388 +ezdxf/resources/icon-goto-handle-64px.png,sha256=7kpPV5aA7i-D-_ZIqRslSgtiPKVCPN-sJ4IWEA36f48,2519 +ezdxf/resources/icon-goto-line-64px.png,sha256=2A21DQiIsE9kGf9ry95ohKabGj-xVElxtAOCZ2A9ocE,2409 +ezdxf/resources/icon-left-arrow-64px.png,sha256=8dLQb5RbVHcm3mkGGiNdwm7T1L96b3PDaeTnnyN--oM,2231 +ezdxf/resources/icon-next-entity-64px.png,sha256=9hL5rlHD-EQSvRweNC1SlW1QYdOjxDJPwDrQSxWSq_I,2322 +ezdxf/resources/icon-prev-entity-64px.png,sha256=qYlnHwtUgErMucPLhJv3y9ePfeV5iaR7O9az1TUtkHE,2320 +ezdxf/resources/icon-right-arrow-64px.png,sha256=R8TH9cQw2BxzZnMnWr6AKt2c-hWnH73qqP-kk9VxuJU,2244 +ezdxf/resources/icon-show-in-tree-64px.png,sha256=f0gyr9mDADYKCYyJ72GEcXabrlcuPglakGBtXCBK0P0,2553 +ezdxf/resources/icon-store-bookmark-64px.png,sha256=EyF--EqbC_J6iWi-W0l112TdWFBcHQyVMMqR3F17x_k,2373 +ezdxf/revcloud.py,sha256=YEB95v_H0cE4_6AfaFTvf8xBaf8rMdnWr0w2L9zF-yA,3811 +ezdxf/sections/__init__.py,sha256=6NS2_6vo_R2iN4H-QlIYIi_BoLvJHdo5jhix1uCaElA,65 +ezdxf/sections/__pycache__/__init__.cpython-313.pyc,, +ezdxf/sections/__pycache__/acdsdata.cpython-313.pyc,, +ezdxf/sections/__pycache__/blocks.cpython-313.pyc,, +ezdxf/sections/__pycache__/classes.cpython-313.pyc,, +ezdxf/sections/__pycache__/entities.cpython-313.pyc,, +ezdxf/sections/__pycache__/header.cpython-313.pyc,, +ezdxf/sections/__pycache__/headervars.cpython-313.pyc,, +ezdxf/sections/__pycache__/objects.cpython-313.pyc,, +ezdxf/sections/__pycache__/table.cpython-313.pyc,, +ezdxf/sections/__pycache__/tables.cpython-313.pyc,, +ezdxf/sections/acdsdata.py,sha256=7GuauRe7v9BzH8FA_6txqXpZiK_3tcP1ChePuxe9wkE,10132 +ezdxf/sections/blocks.py,sha256=rw_W64HK_H4Cxr648MuVaO7cGhzN3gdbtYlf4dPtyag,19333 +ezdxf/sections/classes.py,sha256=UfSHiMU5HPYGYr4DByyUqDYI5Tw3oDfZ8XZK6qzYKoE,11315 +ezdxf/sections/entities.py,sha256=pL4lujv33dg0ChzAz1nn4ClK29IFF2OnaowJFR_VAUg,4024 +ezdxf/sections/header.py,sha256=GKwgFF2hKF-rHU2ywZoH-OyQWVZGfftjPe-af75Ue_Q,11566 +ezdxf/sections/headervars.py,sha256=R2pOmqXIFucKw1lBYRwGytYJiBFyzTHJW6fH2jXW4So,58983 +ezdxf/sections/objects.py,sha256=i41921rKHC-sDjcJoPTed5cn_-5Na7FSDWMKGwFlmyU,26675 +ezdxf/sections/table.py,sha256=4-vpbywPQXw81_iZt0YY6qCKCpWn2NWNE8t1fMb66mM,25821 +ezdxf/sections/tables.py,sha256=oL_ZwO_sYdZs02Zh1Lj-6Re3RyavED4t9cuGy2oTHgQ,5118 +ezdxf/select.py,sha256=RuSs39nyAbjabG3pPO9Z0gzoNQiVyO8rig6M743Habw,15477 +ezdxf/tools/__init__.py,sha256=EOp1qhfRVoO7_cBD-1kvljogc3gmjNqJvm-90UOJ_HU,4252 +ezdxf/tools/__pycache__/__init__.cpython-313.pyc,, +ezdxf/tools/__pycache__/_iso_pattern.cpython-313.pyc,, +ezdxf/tools/__pycache__/analyze.cpython-313.pyc,, +ezdxf/tools/__pycache__/binarydata.cpython-313.pyc,, +ezdxf/tools/__pycache__/clipping_portal.cpython-313.pyc,, +ezdxf/tools/__pycache__/codepage.cpython-313.pyc,, +ezdxf/tools/__pycache__/complex_ltype.cpython-313.pyc,, +ezdxf/tools/__pycache__/crypt.cpython-313.pyc,, +ezdxf/tools/__pycache__/debug.cpython-313.pyc,, +ezdxf/tools/__pycache__/difftags.cpython-313.pyc,, +ezdxf/tools/__pycache__/handle.cpython-313.pyc,, +ezdxf/tools/__pycache__/indexing.cpython-313.pyc,, +ezdxf/tools/__pycache__/juliandate.cpython-313.pyc,, +ezdxf/tools/__pycache__/pattern.cpython-313.pyc,, +ezdxf/tools/__pycache__/rawloader.cpython-313.pyc,, +ezdxf/tools/__pycache__/standards.cpython-313.pyc,, +ezdxf/tools/__pycache__/strip.cpython-313.pyc,, +ezdxf/tools/__pycache__/test.cpython-313.pyc,, +ezdxf/tools/__pycache__/text.cpython-313.pyc,, +ezdxf/tools/__pycache__/text_layout.cpython-313.pyc,, +ezdxf/tools/__pycache__/text_size.cpython-313.pyc,, +ezdxf/tools/__pycache__/zipmanager.cpython-313.pyc,, +ezdxf/tools/_iso_pattern.py,sha256=_3rRDsnJzEIBvLmKD2o7COt4CxLqg3vH4iqYBuubmps,138334 +ezdxf/tools/analyze.py,sha256=NiuNYcfN-88yRleDvBKwq6EIhIVp7oVEsr8-VpOyzjs,19135 +ezdxf/tools/binarydata.py,sha256=KaE2Rd9nNgkA8k69zmza9qdjMbNZE9UKc2txrMmc7lA,19834 +ezdxf/tools/clipping_portal.py,sha256=rZR20d84u39x-2KgRtkkYyw7ZiToz02KnXfvW80Tr6w,15572 +ezdxf/tools/codepage.py,sha256=x6tiVdQrH-J2OAfjnw6xi32hIZrH-rSb3ExOi3DV87E,2840 +ezdxf/tools/complex_ltype.py,sha256=07wBNpGKlk75yhQyIltcIaQd-YsWde5OxQpSZtCzz2w,7399 +ezdxf/tools/crypt.py,sha256=TraGUeqr5GxWZZDFaGAt-OOCaK3ris7sysXN-Y0LAcY,1724 +ezdxf/tools/debug.py,sha256=ihcvmzs8xIFxhjssU-kfgx9rGjzXUu1THzwvy949y3E,1457 +ezdxf/tools/difftags.py,sha256=Cw_LjNHj3hP4n1vUZG2CxMwF6YytTXems9QnVxtS-qs,2245 +ezdxf/tools/handle.py,sha256=2uQRFyZIKKuuikjYPuv4-HU6bryVWsPg6AvIuHDibd8,1187 +ezdxf/tools/indexing.py,sha256=C1sfLJ1nZO_N0tXq48wEFAsTBtnQD54TbcyoViRB5-k,751 +ezdxf/tools/juliandate.py,sha256=UHS3NGzKx8RG2I4Gt3KkUkHMTrv9dxQm-6Zpz-EO_58,2074 +ezdxf/tools/pattern.py,sha256=CRvNvLOV4VEWwRWD9rdkGnPeA8oDaOoEm3Xi54cqfAg,5976 +ezdxf/tools/rawloader.py,sha256=ZIoHnVEqkrtoQkdrmPxw_UWA1yNQF7-iXmOLPyysr1c,1188 +ezdxf/tools/standards.py,sha256=87ZL9qjWIxCSWP5qdeuOHR-Gs9f2W2I0KX-qeABMU0A,125172 +ezdxf/tools/strip.py,sha256=K9CR9D3ExdkU2c52LgbbsiG-xq2Hc1OQTRNArPGYN30,5995 +ezdxf/tools/test.py,sha256=fjmi86mgIeQbDvQsB9uTVI9w6iqH0oAxw3Q2SUzcomI,1416 +ezdxf/tools/text.py,sha256=aX1bVFd1IWV1lahw5c_BXQYMaiRC3eRL2PRcA6AvaYw,64190 +ezdxf/tools/text_layout.py,sha256=49dYkSwr1Y2b6UyEDOi2O3Exh-gJASao_DWQcOwIUEU,52992 +ezdxf/tools/text_size.py,sha256=ouOyGWoPVdE_s0_i04Kny9XouS07jfhtKjOjjgKVNpQ,6627 +ezdxf/tools/zipmanager.py,sha256=Xj49FFPIdfcmybOhBDXnQPcfdUBGXLnd4LNpjLhTBqI,3029 +ezdxf/transform.py,sha256=KOXATb6aHsyiCyY5IRYYPhC_j4cQNxZfKmwVfVqE1uA,12450 +ezdxf/units.py,sha256=mp6NP__Z4j1CgGZa1-T6rbmA3SBvMYiQwy14wqJ-Y_w,5503 +ezdxf/upright.py,sha256=E76ySqkDTjamXdCtytfEzcOWC-POj8czBaLvLmRwiu4,8010 +ezdxf/urecord.py,sha256=K1U0a6B8Uc5uYdWm4Zwc9ydF_gtt4Vp4pMdtAx7LK40,9573 +ezdxf/version.py,sha256=Zxqc2bkizOXYmvi_Okq-5XrGdKCBqccnvNUZISPCFF0,999 +ezdxf/xclip.py,sha256=W7MHUDcZ987I6dAJEilTqlH4Ln6xpF55sxR49XkCF1s,17847 +ezdxf/xref.py,sha256=_VXPTufKBO6-YHCPznyXWQ4aWlYOgawBck7lnlMZF-c,64075 +ezdxf/zoom.py,sha256=nl_sLzPPEDK3ZXkT8qYU3lJWpXspio8rLnFAUK0wktg,2773 diff --git a/data/miniconda3/lib/python3.13/site-packages/ezdxf-1.4.3.dist-info/REQUESTED b/data/miniconda3/lib/python3.13/site-packages/ezdxf-1.4.3.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/lib/python3.13/site-packages/ezdxf-1.4.3.dist-info/WHEEL b/data/miniconda3/lib/python3.13/site-packages/ezdxf-1.4.3.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..3e58ef3a521ad90a85fbf2e444a183313b422fee --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ezdxf-1.4.3.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: false +Tag: cp313-cp313-manylinux_2_17_x86_64 +Tag: cp313-cp313-manylinux2014_x86_64 + diff --git a/data/miniconda3/lib/python3.13/site-packages/ezdxf-1.4.3.dist-info/entry_points.txt b/data/miniconda3/lib/python3.13/site-packages/ezdxf-1.4.3.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..07f59a9f970e19e771a0cadb8abd8a08227d3a75 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ezdxf-1.4.3.dist-info/entry_points.txt @@ -0,0 +1,2 @@ +[console_scripts] +ezdxf = ezdxf.__main__:main diff --git a/data/miniconda3/lib/python3.13/site-packages/ezdxf-1.4.3.dist-info/top_level.txt b/data/miniconda3/lib/python3.13/site-packages/ezdxf-1.4.3.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..fb8b6e112f30e2dd8ce2e63638e2bfc1c109210a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ezdxf-1.4.3.dist-info/top_level.txt @@ -0,0 +1 @@ +ezdxf diff --git a/data/miniconda3/lib/python3.13/site-packages/frozendict-2.4.6.dist-info/INSTALLER b/data/miniconda3/lib/python3.13/site-packages/frozendict-2.4.6.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..f79e4cb9aaf0b2d9e8ba78861e2071317b2384b3 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/frozendict-2.4.6.dist-info/INSTALLER @@ -0,0 +1 @@ +conda \ No newline at end of file diff --git a/data/miniconda3/lib/python3.13/site-packages/frozendict-2.4.6.dist-info/METADATA b/data/miniconda3/lib/python3.13/site-packages/frozendict-2.4.6.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..d4f35f66db434927c61f44d5eacf25fc2eb0b91f --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/frozendict-2.4.6.dist-info/METADATA @@ -0,0 +1,496 @@ +Metadata-Version: 2.4 +Name: frozendict +Version: 2.4.6 +Summary: A simple immutable dictionary +Home-page: https://github.com/Marco-Sulla/python-frozendict +Author: Marco Sulla +Author-email: marcosullaroma@gmail.com +License: LGPL v3 +Project-URL: Bug Reports, https://github.com/Marco-Sulla/python-frozendict/issues +Project-URL: Source, https://github.com/Marco-Sulla/python-frozendict +Keywords: immutable hashable picklable frozendict dict dictionary map Mapping MappingProxyType developers stable utility +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3) +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.6 +Classifier: Natural Language :: English +Classifier: Operating System :: OS Independent +Classifier: Topic :: Software Development :: Libraries +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Topic :: Utilities +Requires-Python: >=3.6 +Description-Content-Type: text/markdown +License-File: LICENSE.txt +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: description-content-type +Dynamic: home-page +Dynamic: keywords +Dynamic: license +Dynamic: license-file +Dynamic: project-url +Dynamic: requires-python +Dynamic: summary + +# frozendict +### Table of Contents +* [Introduction](#introduction) +* [Install](#install) +* [API](#api) + * [frozendict API](#frozendict-api) + * [deepfreeze API](#deepfreeze-api) +* [Examples](#examples) + * [frozendict examples](#frozendict-examples) + * [deepfreeze examples](#deepfreeze-examples) +* [Building](#building) +* [Benchmarks](#benchmarks) + +# Introduction +Welcome, fellow programmer, to the house of `frozendict` and +[deepfreeze](#deepfreeze-api)! + +`frozendict` is a simple immutable dictionary. It's fast as `dict`, and +[sometimes faster](https://github.com/Marco-Sulla/python-frozendict#benchmarks)! + +Unlike other similar implementations, immutability is guaranteed: you can't +change the internal variables of the class, and they are all immutable +objects. Reinvoking `__init__` does not alter the object. + +The API is the same as `dict`, without methods that can change the +immutability. So it supports also `fromkeys`, unlike other implementations. +Furthermore, it can be `pickle`d, un`pickle`d and have a hash, if all values +are hashable. + +You can also add any `dict` to a `frozendict` using the `|` operator. The result is a new `frozendict`. + +# Install + +You can install `frozendict` by simply typing in a command line: + +```bash +pip install frozendict +``` + +The C Extension is optional by default from version 2.3.5. You can make it mandatory using: + +```bash +CIBUILDWHEEL=1 pip install frozendict +``` + +On the contrary, if you want the pure py implementation: + +```bash +FROZENDICT_PURE_PY=1 pip install frozendict +``` + +# API + +## frozendict API +The API is the same of `dict` of Python 3.10, without the methods and operands which alter the map. Additionally, `frozendict` supports these methods: + +### `__hash__()` + +If all the values of the `frozendict` are hashable, returns a hash, otherwise raises a TypeError. + +### `set(key, value)` + +It returns a new `frozendict`. If key is already in the original `frozendict`, the new one will have it with the new value associated. Otherwise, the new `frozendict` will contain the new (key, value) item. + +### `delete(key)` + +It returns a new `frozendict` without the item corresponding to the key. If the key is not present, a KeyError is raised. + +### `setdefault(key[, default])` + +If key is already in `frozendict`, the object itself is returned unchanged. Otherwise, the new `frozendict` will contain the new (key, default) item. The parameter default defaults to None. + +### `key([index])` + +It returns the key at the specified index (determined by the insertion order). If index is not passed, it defaults to 0. If the index is negative, the position will be the size of the `frozendict` + index + +### `value([index])` +Same as `key(index)`, but it returns the value at the given index. + +### `item([index])` +Same as `key(index)`, but it returns a tuple with (key, value) at the given index. + +## deepfreeze API + +The `frozendict` _module_ has also these static methods: + +### `frozendict.deepfreeze(o, custom_converters = None, custom_inverse_converters = None)` +Converts the object and all the objects nested in it, into their immutable +counterparts. + +The conversion map is in `getFreezeConversionMap()`. + +You can register a new conversion using `register()` You can also +pass a map of custom converters with `custom_converters` and a map +of custom inverse converters with `custom_inverse_converters`, +without using `register()`. + +By default, if the type is not registered and has a `__dict__` +attribute, it's converted to the `frozendict` of that `__dict__`. + +This function assumes that hashable == immutable (that is not +always true). + +This function uses recursion, with all the limits of recursions in +Python. + +Where is a good old tail call when you need it? + +### `frozendict.register(to_convert, converter, *, inverse = False)` + +Adds a `converter` for a type `to_convert`. `converter` +must be callable. The new converter will be used by `deepfreeze()` +and has precedence over any previous converter. + +If `to_covert` has already a converter, a FreezeWarning is raised. + +If `inverse` is True, the conversion is considered from an immutable +type to a mutable one. This make it possible to convert mutable +objects nested in the registered immutable one. + +### `frozendict.unregister(type, inverse = False)` +Unregister a type from custom conversion. If `inverse` is `True`, +the unregistered conversion is an inverse conversion +(see `register()`). + +# Examples + +## frozendict examples +```python +from frozendict import frozendict + +fd = frozendict(Guzzanti = "Corrado", Hicks = "Bill") + +print(fd) +# frozendict({'Guzzanti': 'Corrado', 'Hicks': 'Bill'}) + +frozendict({"Guzzanti": "Corrado", "Hicks": "Bill"}) +# frozendict({'Guzzanti': 'Corrado', 'Hicks': 'Bill'}) + +hash(fd) +# 5833699487320513741 + +fd_unhashable = frozendict({1: []}) +hash(fd_unhashable) +# TypeError: Not all values are hashable. + +frozendict({frozendict(nested = 4, key = 2): 42}) +# frozendict({frozendict({'nested': 4, 'key': 2}): 42}) + +fd | {1: 2} +# frozendict({'Guzzanti': 'Corrado', 'Hicks': 'Bill', 1: 2}) + +fd.set(1, 2) +# frozendict.frozendict({'Guzzanti': 'Corrado', 'Hicks': 'Bill', 1: 2}) + +fd.set("Guzzanti", "Sabina") +# frozendict.frozendict({'Guzzanti': 'Sabina', 'Hicks': 'Bill'}) + +fd.delete("Guzzanti") +# frozendict.frozendict({'Hicks': 'Bill'}) + +fd.setdefault("Guzzanti", "Sabina") +# frozendict.frozendict({'Guzzanti': 'Corrado', 'Hicks': 'Bill'}) + +fd.setdefault(1, 2) +# frozendict.frozendict({'Guzzanti': 'Corrado', 'Hicks': 'Bill', 1: 2}) + +fd.key() +# 'Guzzanti' + +fd.value(1) +# 'Bill' + +fd.item(-1) +# (1, 2) + +print(fd["Guzzanti"]) +# Corrado + +fd["Brignano"] +# KeyError: 'Brignano' + +len(fd) +# 2 + +"Guzzanti" in fd +# True + +"Guzzanti" not in fd +# False + +"Brignano" in fd +# False + +fd5 = frozendict(fd) +id_fd5 = id(fd5) +fd5 |= {1: 2} +fd5 +# frozendict.frozendict({'Guzzanti': 'Corrado', 'Hicks': 'Bill', 1: 2}) +id(fd5) != id_fd5 +# True + +fd2 = fd.copy() +fd2 == fd +# True + +fd3 = frozendict(fd) +fd3 == fd +# True + +fd4 = frozendict({"Hicks": "Bill", "Guzzanti": "Corrado"}) + +print(fd4) +# frozendict({'Hicks': 'Bill', 'Guzzanti': 'Corrado'}) + +fd4 == fd +# True + +import pickle +fd_unpickled = pickle.loads(pickle.dumps(fd)) +print(fd_unpickled) +# frozendict({'Guzzanti': 'Corrado', 'Hicks': 'Bill'}) +fd_unpickled == fd +# True + +frozendict(Guzzanti="Corrado", Hicks="Bill") +# frozendict({'Guzzanti': 'Corrado', 'Hicks': 'Bill'} + +fd.get("Guzzanti") +# 'Corrado' + +print(fd.get("Brignano")) +# None + +tuple(fd.keys()) +# ('Guzzanti', 'Hicks') + +tuple(fd.values()) +# ('Corrado', 'Bill') + +tuple(fd.items()) +# (('Guzzanti', 'Corrado'), ('Hicks', 'Bill')) + +frozendict.fromkeys(["Corrado", "Sabina"], "Guzzanti") +# frozendict({'Corrado': 'Guzzanti', 'Sabina': 'Guzzanti'}) + +iter(fd) +# + +fd["Guzzanti"] = "Caterina" +# TypeError: 'frozendict' object doesn't support item assignment +``` + +## deepfreeze examples +```python +import frozendict as cool + +from frozendict import frozendict +from array import array +from collections import OrderedDict +from types import MappingProxyType + +class A: + def __init__(self, x): + self.x = x + +a = A(3) + +o = {"x": [ + 5, + frozendict(y = {5, "b", memoryview(b"b")}), + array("B", (0, 1, 2)), + OrderedDict(a=bytearray(b"a")), + MappingProxyType({2: []}), + a +]} + +cool.deepfreeze(o) +# frozendict(x = ( +# 5, +# frozendict(y = frozenset({5, "b", memoryview(b"b")})), +# (0, 1, 2), +# frozendict(a = b'a'), +# MappingProxyType({2: ()}), +# frozendict(x = 3), +# )) + +``` + +# Building +You can build `frozendict` directly from the code, using + +``` +python3 setup.py bdist_wheel +``` + +The C Extension is optional by default from version 2.3.5. You can make it mandatory by passing the environment variable `CIBUILDWHEEL` with value `1` + +On the contrary, if you want the pure py implementation, you can pass the env var `FROZENDICT_PURE_PY` with value `1` + +# Benchmarks + +Some benchmarks between `dict` and `frozendict`[1]: + +``` +################################################################################ +//////////////////////////////////////////////////////////////////////////////// +Name: `constructor(d)`; Size: 5; Keys: str; Type: dict; Time: 8.02e-08; Sigma: 4e-09 +Name: `constructor(d)`; Size: 5; Keys: str; Type: frozendict; Time: 8.81e-08; Sigma: 3e-09 +//////////////////////////////////////////////////////////////////////////////// +Name: `constructor(d)`; Size: 5; Keys: int; Type: dict; Time: 7.96e-08; Sigma: 5e-09 +Name: `constructor(d)`; Size: 5; Keys: int; Type: frozendict; Time: 8.97e-08; Sigma: 2e-09 +//////////////////////////////////////////////////////////////////////////////// +Name: `constructor(d)`; Size: 1000; Keys: str; Type: dict; Time: 6.38e-06; Sigma: 9e-08 +Name: `constructor(d)`; Size: 1000; Keys: str; Type: frozendict; Time: 6.21e-06; Sigma: 2e-07 +//////////////////////////////////////////////////////////////////////////////// +Name: `constructor(d)`; Size: 1000; Keys: int; Type: dict; Time: 3.49e-06; Sigma: 3e-07 +Name: `constructor(d)`; Size: 1000; Keys: int; Type: frozendict; Time: 3.48e-06; Sigma: 2e-07 +################################################################################ +//////////////////////////////////////////////////////////////////////////////// +Name: `constructor(kwargs)`; Size: 5; Keys: str; Type: dict; Time: 2.40e-07; Sigma: 1e-09 +Name: `constructor(kwargs)`; Size: 5; Keys: str; Type: frozendict; Time: 2.48e-07; Sigma: 2e-09 +//////////////////////////////////////////////////////////////////////////////// +Name: `constructor(kwargs)`; Size: 1000; Keys: str; Type: dict; Time: 4.80e-05; Sigma: 1e-06 +Name: `constructor(kwargs)`; Size: 1000; Keys: str; Type: frozendict; Time: 2.90e-05; Sigma: 7e-07 +################################################################################ +//////////////////////////////////////////////////////////////////////////////// +Name: `constructor(seq2)`; Size: 5; Keys: str; Type: dict; Time: 2.01e-07; Sigma: 9e-10 +Name: `constructor(seq2)`; Size: 5; Keys: str; Type: frozendict; Time: 2.50e-07; Sigma: 1e-09 +//////////////////////////////////////////////////////////////////////////////// +Name: `constructor(seq2)`; Size: 5; Keys: int; Type: dict; Time: 2.18e-07; Sigma: 2e-09 +Name: `constructor(seq2)`; Size: 5; Keys: int; Type: frozendict; Time: 2.73e-07; Sigma: 1e-09 +//////////////////////////////////////////////////////////////////////////////// +Name: `constructor(seq2)`; Size: 1000; Keys: str; Type: dict; Time: 4.29e-05; Sigma: 6e-07 +Name: `constructor(seq2)`; Size: 1000; Keys: str; Type: frozendict; Time: 4.33e-05; Sigma: 6e-07 +//////////////////////////////////////////////////////////////////////////////// +Name: `constructor(seq2)`; Size: 1000; Keys: int; Type: dict; Time: 3.04e-05; Sigma: 4e-07 +Name: `constructor(seq2)`; Size: 1000; Keys: int; Type: frozendict; Time: 3.45e-05; Sigma: 4e-07 +################################################################################ +//////////////////////////////////////////////////////////////////////////////// +Name: `constructor(o)`; Size: 5; Keys: str; Type: dict; Time: 7.93e-08; Sigma: 3e-09 +Name: `constructor(o)`; Size: 5; Keys: str; Type: frozendict; Time: 2.41e-08; Sigma: 6e-10 +//////////////////////////////////////////////////////////////////////////////// +Name: `constructor(o)`; Size: 5; Keys: int; Type: dict; Time: 7.94e-08; Sigma: 5e-09 +Name: `constructor(o)`; Size: 5; Keys: int; Type: frozendict; Time: 2.41e-08; Sigma: 6e-10 +//////////////////////////////////////////////////////////////////////////////// +Name: `constructor(o)`; Size: 1000; Keys: str; Type: dict; Time: 6.18e-06; Sigma: 3e-07 +Name: `constructor(o)`; Size: 1000; Keys: str; Type: frozendict; Time: 2.41e-08; Sigma: 6e-10 +//////////////////////////////////////////////////////////////////////////////// +Name: `constructor(o)`; Size: 1000; Keys: int; Type: dict; Time: 3.47e-06; Sigma: 2e-07 +Name: `constructor(o)`; Size: 1000; Keys: int; Type: frozendict; Time: 2.41e-08; Sigma: 6e-10 +################################################################################ +//////////////////////////////////////////////////////////////////////////////// +Name: `o.copy()`; Size: 5; Keys: str; Type: dict; Time: 7.28e-08; Sigma: 2e-09 +Name: `o.copy()`; Size: 5; Keys: str; Type: frozendict; Time: 3.18e-08; Sigma: 2e-09 +//////////////////////////////////////////////////////////////////////////////// +Name: `o.copy()`; Size: 5; Keys: int; Type: dict; Time: 7.21e-08; Sigma: 4e-09 +Name: `o.copy()`; Size: 5; Keys: int; Type: frozendict; Time: 3.32e-08; Sigma: 2e-09 +//////////////////////////////////////////////////////////////////////////////// +Name: `o.copy()`; Size: 1000; Keys: str; Type: dict; Time: 6.16e-06; Sigma: 3e-07 +Name: `o.copy()`; Size: 1000; Keys: str; Type: frozendict; Time: 3.18e-08; Sigma: 2e-09 +//////////////////////////////////////////////////////////////////////////////// +Name: `o.copy()`; Size: 1000; Keys: int; Type: dict; Time: 3.46e-06; Sigma: 1e-07 +Name: `o.copy()`; Size: 1000; Keys: int; Type: frozendict; Time: 3.18e-08; Sigma: 2e-09 +################################################################################ +//////////////////////////////////////////////////////////////////////////////// +Name: `o == o`; Size: 5; Keys: str; Type: dict; Time: 7.23e-08; Sigma: 8e-10 +Name: `o == o`; Size: 5; Keys: str; Type: frozendict; Time: 2.44e-08; Sigma: 2e-09 +//////////////////////////////////////////////////////////////////////////////// +Name: `o == o`; Size: 5; Keys: int; Type: dict; Time: 7.30e-08; Sigma: 1e-09 +Name: `o == o`; Size: 5; Keys: int; Type: frozendict; Time: 2.44e-08; Sigma: 2e-09 +//////////////////////////////////////////////////////////////////////////////// +Name: `o == o`; Size: 1000; Keys: str; Type: dict; Time: 1.38e-05; Sigma: 1e-07 +Name: `o == o`; Size: 1000; Keys: str; Type: frozendict; Time: 2.44e-08; Sigma: 2e-09 +//////////////////////////////////////////////////////////////////////////////// +Name: `o == o`; Size: 1000; Keys: int; Type: dict; Time: 1.05e-05; Sigma: 7e-08 +Name: `o == o`; Size: 1000; Keys: int; Type: frozendict; Time: 2.44e-08; Sigma: 2e-09 +################################################################################ +//////////////////////////////////////////////////////////////////////////////// +Name: `for x in o`; Size: 5; Keys: str; Type: dict; Time: 7.33e-08; Sigma: 2e-09 +Name: `for x in o`; Size: 5; Keys: str; Type: frozendict; Time: 6.70e-08; Sigma: 1e-09 +//////////////////////////////////////////////////////////////////////////////// +Name: `for x in o`; Size: 5; Keys: int; Type: dict; Time: 7.33e-08; Sigma: 2e-09 +Name: `for x in o`; Size: 5; Keys: int; Type: frozendict; Time: 6.70e-08; Sigma: 1e-09 +//////////////////////////////////////////////////////////////////////////////// +Name: `for x in o`; Size: 1000; Keys: str; Type: dict; Time: 8.84e-06; Sigma: 5e-08 +Name: `for x in o`; Size: 1000; Keys: str; Type: frozendict; Time: 7.06e-06; Sigma: 6e-08 +//////////////////////////////////////////////////////////////////////////////// +Name: `for x in o`; Size: 1000; Keys: int; Type: dict; Time: 8.67e-06; Sigma: 7e-08 +Name: `for x in o`; Size: 1000; Keys: int; Type: frozendict; Time: 6.94e-06; Sigma: 3e-08 +################################################################################ +//////////////////////////////////////////////////////////////////////////////// +Name: `for x in o.values()`; Size: 5; Keys: str; Type: dict; Time: 7.28e-08; Sigma: 9e-10 +Name: `for x in o.values()`; Size: 5; Keys: str; Type: frozendict; Time: 6.48e-08; Sigma: 8e-10 +//////////////////////////////////////////////////////////////////////////////// +Name: `for x in o.values()`; Size: 5; Keys: int; Type: dict; Time: 7.25e-08; Sigma: 1e-09 +Name: `for x in o.values()`; Size: 5; Keys: int; Type: frozendict; Time: 6.45e-08; Sigma: 1e-09 +//////////////////////////////////////////////////////////////////////////////// +Name: `for x in o.values()`; Size: 1000; Keys: str; Type: dict; Time: 9.06e-06; Sigma: 5e-07 +Name: `for x in o.values()`; Size: 1000; Keys: str; Type: frozendict; Time: 7.04e-06; Sigma: 4e-08 +//////////////////////////////////////////////////////////////////////////////// +Name: `for x in o.values()`; Size: 1000; Keys: int; Type: dict; Time: 9.53e-06; Sigma: 3e-08 +Name: `for x in o.values()`; Size: 1000; Keys: int; Type: frozendict; Time: 6.97e-06; Sigma: 3e-08 +################################################################################ +//////////////////////////////////////////////////////////////////////////////// +Name: `for x in o.items()`; Size: 5; Keys: str; Type: dict; Time: 1.13e-07; Sigma: 3e-09 +Name: `for x in o.items()`; Size: 5; Keys: str; Type: frozendict; Time: 1.16e-07; Sigma: 2e-09 +//////////////////////////////////////////////////////////////////////////////// +Name: `for x in o.items()`; Size: 5; Keys: int; Type: dict; Time: 1.14e-07; Sigma: 3e-09 +Name: `for x in o.items()`; Size: 5; Keys: int; Type: frozendict; Time: 1.17e-07; Sigma: 2e-09 +//////////////////////////////////////////////////////////////////////////////// +Name: `for x in o.items()`; Size: 1000; Keys: str; Type: dict; Time: 1.53e-05; Sigma: 3e-07 +Name: `for x in o.items()`; Size: 1000; Keys: str; Type: frozendict; Time: 1.53e-05; Sigma: 4e-07 +//////////////////////////////////////////////////////////////////////////////// +Name: `for x in o.items()`; Size: 1000; Keys: int; Type: dict; Time: 1.53e-05; Sigma: 3e-07 +Name: `for x in o.items()`; Size: 1000; Keys: int; Type: frozendict; Time: 1.55e-05; Sigma: 4e-07 +################################################################################ +//////////////////////////////////////////////////////////////////////////////// +Name: `pickle.dumps(o)`; Size: 5; Keys: str; Type: dict; Time: 6.82e-07; Sigma: 2e-08 +Name: `pickle.dumps(o)`; Size: 5; Keys: str; Type: frozendict; Time: 2.86e-06; Sigma: 1e-07 +//////////////////////////////////////////////////////////////////////////////// +Name: `pickle.dumps(o)`; Size: 5; Keys: int; Type: dict; Time: 4.77e-07; Sigma: 2e-08 +Name: `pickle.dumps(o)`; Size: 5; Keys: int; Type: frozendict; Time: 2.72e-06; Sigma: 8e-08 +//////////////////////////////////////////////////////////////////////////////// +Name: `pickle.dumps(o)`; Size: 1000; Keys: str; Type: dict; Time: 1.24e-04; Sigma: 4e-06 +Name: `pickle.dumps(o)`; Size: 1000; Keys: str; Type: frozendict; Time: 1.92e-04; Sigma: 5e-06 +//////////////////////////////////////////////////////////////////////////////// +Name: `pickle.dumps(o)`; Size: 1000; Keys: int; Type: dict; Time: 2.81e-05; Sigma: 6e-07 +Name: `pickle.dumps(o)`; Size: 1000; Keys: int; Type: frozendict; Time: 7.37e-05; Sigma: 1e-06 +################################################################################ +//////////////////////////////////////////////////////////////////////////////// +Name: `pickle.loads(dump)`; Size: 5; Keys: str; Type: dict; Time: 9.08e-07; Sigma: 6e-09 +Name: `pickle.loads(dump)`; Size: 5; Keys: str; Type: frozendict; Time: 1.79e-06; Sigma: 9e-08 +//////////////////////////////////////////////////////////////////////////////// +Name: `pickle.loads(dump)`; Size: 5; Keys: int; Type: dict; Time: 4.46e-07; Sigma: 6e-09 +Name: `pickle.loads(dump)`; Size: 5; Keys: int; Type: frozendict; Time: 1.32e-06; Sigma: 7e-08 +//////////////////////////////////////////////////////////////////////////////// +Name: `pickle.loads(dump)`; Size: 1000; Keys: str; Type: dict; Time: 1.57e-04; Sigma: 8e-06 +Name: `pickle.loads(dump)`; Size: 1000; Keys: str; Type: frozendict; Time: 1.69e-04; Sigma: 7e-06 +//////////////////////////////////////////////////////////////////////////////// +Name: `pickle.loads(dump)`; Size: 1000; Keys: int; Type: dict; Time: 5.97e-05; Sigma: 5e-06 +Name: `pickle.loads(dump)`; Size: 1000; Keys: int; Type: frozendict; Time: 6.68e-05; Sigma: 2e-06 +################################################################################ +//////////////////////////////////////////////////////////////////////////////// +Name: `class.fromkeys()`; Size: 5; Keys: str; Type: dict; Time: 1.88e-07; Sigma: 1e-09 +Name: `class.fromkeys()`; Size: 5; Keys: str; Type: frozendict; Time: 2.22e-07; Sigma: 7e-09 +//////////////////////////////////////////////////////////////////////////////// +Name: `class.fromkeys()`; Size: 5; Keys: int; Type: dict; Time: 2.08e-07; Sigma: 6e-09 +Name: `class.fromkeys()`; Size: 5; Keys: int; Type: frozendict; Time: 2.44e-07; Sigma: 2e-09 +//////////////////////////////////////////////////////////////////////////////// +Name: `class.fromkeys()`; Size: 1000; Keys: str; Type: dict; Time: 4.05e-05; Sigma: 4e-06 +Name: `class.fromkeys()`; Size: 1000; Keys: str; Type: frozendict; Time: 3.84e-05; Sigma: 5e-07 +//////////////////////////////////////////////////////////////////////////////// +Name: `class.fromkeys()`; Size: 1000; Keys: int; Type: dict; Time: 2.93e-05; Sigma: 7e-07 +Name: `class.fromkeys()`; Size: 1000; Keys: int; Type: frozendict; Time: 3.08e-05; Sigma: 2e-06 +################################################################################ +``` + +[1] Benchmarks done under Linux 64 bit, Python 3.10.2, using the C Extension. diff --git a/data/miniconda3/lib/python3.13/site-packages/frozendict-2.4.6.dist-info/RECORD b/data/miniconda3/lib/python3.13/site-packages/frozendict-2.4.6.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..073f301224c8fe2f335755f745afde15fff9c4b2 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/frozendict-2.4.6.dist-info/RECORD @@ -0,0 +1,22 @@ +frozendict-2.4.6.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +frozendict-2.4.6.dist-info/METADATA,sha256=I0VwJ6xVgjMHmQkFHBS1-FWvd1D1OA7mGRTqZ2nkmcs,23571 +frozendict-2.4.6.dist-info/RECORD,, +frozendict-2.4.6.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +frozendict-2.4.6.dist-info/WHEEL,sha256=edS7gZHRaM8x-3M3xoAkSxyeLfZjWAhIur1iLsXkBLo,104 +frozendict-2.4.6.dist-info/direct_url.json,sha256=Op4a8RLHC5Mfjxv6oiUUbnaruB2BOMf_Lv0TwrITf5s,100 +frozendict-2.4.6.dist-info/licenses/LICENSE.txt,sha256=46mU2C5kSwOnkqkw9XQAJlhBL2JAf1_uCD8lVcXyMRg,7652 +frozendict-2.4.6.dist-info/top_level.txt,sha256=H0x_yOfp00xK1WR_JMHct-wr-7Ht9uC9iQR2aHNL_uw,11 +frozendict/__init__.py,sha256=vKuhOMwKqDKItL2vkPl7yfQyjM3zQW4gHXq8GLN9_vk,1533 +frozendict/__init__.pyi,sha256=yjX57g8jPjs-sNYf1ipFeEQ1GW8VYy1fgQXRWFeCa_w,3748 +frozendict/__pycache__/__init__.cpython-313.pyc,, +frozendict/__pycache__/_frozendict_py.cpython-313.pyc,, +frozendict/__pycache__/cool.cpython-313.pyc,, +frozendict/__pycache__/core.cpython-313.pyc,, +frozendict/__pycache__/monkeypatch.cpython-313.pyc,, +frozendict/__pycache__/version.cpython-313.pyc,, +frozendict/_frozendict_py.py,sha256=ecP3xmaqMojMKVPx5XwAyYKN8VWWu_7BkRAcX_qvfhQ,6510 +frozendict/cool.py,sha256=YyAMQ9hJDAZPZZkgrul6SWnTd-JeOum3j6YsZfoUiDE,8601 +frozendict/core.py,sha256=ZHj6y3awRhHRJpgD7qCFjhY7U_jjvjUdOUVWn1kpZ5Y,218 +frozendict/monkeypatch.py,sha256=TH553x_gli-L4x6LeaiHkBWrUqaAby90klJopLJL8f4,6063 +frozendict/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +frozendict/version.py,sha256=iKGBHv5jYa0-BnxopXKqD4p9V74VMi5EjS1PPZxSmBg,18 diff --git a/data/miniconda3/lib/python3.13/site-packages/frozendict-2.4.6.dist-info/REQUESTED b/data/miniconda3/lib/python3.13/site-packages/frozendict-2.4.6.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/lib/python3.13/site-packages/frozendict-2.4.6.dist-info/WHEEL b/data/miniconda3/lib/python3.13/site-packages/frozendict-2.4.6.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..69b458e365fc9b069c1677d11d9130ee3a8f7392 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/frozendict-2.4.6.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: false +Tag: cp313-cp313-linux_x86_64 + diff --git a/data/miniconda3/lib/python3.13/site-packages/frozendict-2.4.6.dist-info/direct_url.json b/data/miniconda3/lib/python3.13/site-packages/frozendict-2.4.6.dist-info/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..6482d51384009f6dfa210e8947a41d75660f46c8 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/frozendict-2.4.6.dist-info/direct_url.json @@ -0,0 +1 @@ +{"dir_info": {}, "url": "file:///home/task_176175049677026/conda-bld/frozendict_1761750665451/work"} \ No newline at end of file diff --git a/data/miniconda3/lib/python3.13/site-packages/frozendict-2.4.6.dist-info/top_level.txt b/data/miniconda3/lib/python3.13/site-packages/frozendict-2.4.6.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..302328f60e50663123555344652eff53a3ced359 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/frozendict-2.4.6.dist-info/top_level.txt @@ -0,0 +1 @@ +frozendict diff --git a/data/miniconda3/lib/python3.13/site-packages/frozendict/__init__.py b/data/miniconda3/lib/python3.13/site-packages/frozendict/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0164eef7218b3466564df64c69121b680ec637da --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/frozendict/__init__.py @@ -0,0 +1,61 @@ +r""" +Provides frozendict, a simple immutable dictionary. +""" + +try: # pragma: no cover + from ._frozendict import * + c_ext = True + # noinspection PyUnresolvedReferences + del _frozendict +except ImportError: + from ._frozendict_py import * + c_ext = False + +from .version import version as __version__ +from . import monkeypatch +from .cool import * +from . import cool + + +def _getFrozendictJsonEncoder(BaseJsonEncoder = None): + if BaseJsonEncoder is None: # pragma: no cover + from json.encoder import JSONEncoder + + BaseJsonEncoder = JSONEncoder + + class FrozendictJsonEncoderInternal(BaseJsonEncoder): + def default(self, obj): + if isinstance(obj, frozendict): # pragma: no cover + # TODO create a C serializer + return dict(obj) + + return BaseJsonEncoder.default( + self, + obj + ) # pragma: no cover + + return FrozendictJsonEncoderInternal + + +FrozendictJsonEncoder = _getFrozendictJsonEncoder() +monkeypatch.patchOrUnpatchAll(patch = True, warn = False) + + +from collections.abc import Mapping + +# noinspection PyUnresolvedReferences +Mapping.register(frozendict) +del Mapping + + +if c_ext: # pragma: no cover + __all__ = (frozendict.__name__, ) +else: + __all__ = _frozendict_py.__all__ + del _frozendict_py + +# TODO deprecated, to remove in future versions +FrozenOrderedDict = frozendict + +__all__ += cool.__all__ +__all__ += (FrozendictJsonEncoder.__name__, "FrozenOrderedDict") diff --git a/data/miniconda3/lib/python3.13/site-packages/frozendict/__init__.pyi b/data/miniconda3/lib/python3.13/site-packages/frozendict/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..0f0217ea311becd1d1135dc27f5e86cd5e3d8e0e --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/frozendict/__init__.pyi @@ -0,0 +1,123 @@ +from __future__ import annotations + +from typing import ( + TypeVar, + overload, + Optional, + Union, + Any, + Dict, + Callable, +) + +from collections.abc import Hashable + +try: + from typing import Mapping, Iterable, Iterator, Tuple, Type +except ImportError: + from collections.abc import Mapping, Iterable, Iterator + Tuple = tuple + Type = type + +K = TypeVar("K") +V = TypeVar("V", covariant=True) +K2 = TypeVar("K2") +V2 = TypeVar("V2", covariant=True) +SelfT = TypeVar("SelfT", bound=frozendict[K, V]) + +# noinspection PyPep8Naming +class frozendict(Mapping[K, V]): + @overload + def __new__(cls: Type[SelfT]) -> SelfT: ... + @overload + def __new__(cls: Type[SelfT], **kwargs: V) -> frozendict[str, V]: ... + @overload + def __new__(cls: Type[SelfT], mapping: Mapping[K, V]) -> SelfT: ... + @overload + def __new__(cls: Type[SelfT], iterable: Iterable[Tuple[K, V]]) -> SelfT: ... + + def __getitem__(self: SelfT, key: K) -> V: ... + def __len__(self: SelfT) -> int: ... + def __iter__(self: SelfT) -> Iterator[K]: ... + def __hash__(self: SelfT) -> int: ... + def __reversed__(self: SelfT) -> Iterator[K]: ... + def copy(self: SelfT) -> SelfT: ... + def __copy__(self: SelfT) -> SelfT: ... + def __deepcopy__(self: SelfT) -> SelfT: ... + def delete(self: SelfT, key: K) -> SelfT: ... + @overload + def key(self: SelfT, index: int) -> K: ... + @overload + def key(self: SelfT) -> K: ... + @overload + def value(self: SelfT, index: int) -> V: ... + @overload + def value(self: SelfT) -> V: ... + @overload + def item(self: SelfT, index: int) -> Tuple[K, V]: ... + @overload + def item(self: SelfT) -> Tuple[K, V]: ... + @overload + def __or__(self: SelfT, other: Mapping[K, V]) -> SelfT: ... + @overload + def __or__(self: SelfT, other: Mapping[K2, V]) -> frozendict[Union[K, K2], V]: ... + @overload + def __or__(self: SelfT, other: Mapping[K, V2]) -> frozendict[K, Union[V, V2]]: ... + @overload + def __or__(self: SelfT, other: Mapping[K2, V2]) -> frozendict[Union[K, K2], Union[V, V2]]: ... + @overload + def set(self: SelfT, key: K, value: V) -> SelfT: ... + @overload + def set(self: SelfT, key: K2, value: V) -> frozendict[Union[K, K2], V]: ... + @overload + def set(self: SelfT, key: K, value: V2) -> frozendict[K, Union[V, V2]]: ... + @overload + def set(self: SelfT, key: K2, value: V2) -> frozendict[Union[K, K2], Union[V, V2]]: ... + @overload + def setdefault(self: SelfT, key: K) -> SelfT: ... + @overload + def setdefault(self: SelfT, key: K2) -> SelfT: ... + @overload + def setdefault(self: SelfT, key: K, default: V) -> SelfT: ... + @overload + def setdefault(self: SelfT, key: K2, default: V) -> frozendict[Union[K, K2], V]: ... + @overload + def setdefault(self: SelfT, key: K, default: V2) -> frozendict[K, Union[V, V2]]: ... + @overload + def setdefault(self: SelfT, key: K2, default: V2) -> frozendict[Union[K, K2], Union[V, V2]]: ... + + @classmethod + def fromkeys( + cls: Type[SelfT], + seq: Iterable[K], + value: Optional[V] = None + ) -> SelfT: ... + + +FrozenOrderedDict = frozendict +c_ext: bool + +class FreezeError(Exception): pass + + +class FreezeWarning(UserWarning): pass + +# PyCharm complains about returning Hashable, because +# it's not subscriptable +def deepfreeze( + o: Any, + custom_converters: Optional[Dict[Any, Callable[[Any], Hashable]]] = None, + custom_inverse_converters: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: ... + +def register( + to_convert: Any, + converter: Callable[[Any], Any], + *, + inverse: bool = False +) -> None: ... + +def unregister( + type: Any, + inverse: bool = False +) -> None: ... diff --git a/data/miniconda3/lib/python3.13/site-packages/frozendict/_frozendict_py.py b/data/miniconda3/lib/python3.13/site-packages/frozendict/_frozendict_py.py new file mode 100644 index 0000000000000000000000000000000000000000..fec912579d0ede1915dc428dd3445915aa4195b1 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/frozendict/_frozendict_py.py @@ -0,0 +1,254 @@ +from copy import deepcopy + + +def immutable(self, *_args, **_kwargs): + r""" + Function for not implemented method since the object is immutable + """ + + raise AttributeError( + f"'{self.__class__.__name__}' object is read-only" + ) + + +_empty_frozendict = None +_module_name = "frozendict" + + +# noinspection PyPep8Naming +class frozendict(dict): + r""" + A simple immutable dictionary. + + The API is the same as `dict`, without methods that can change the + immutability. In addition, it supports __hash__(). + """ + + __slots__ = ( + "_hash", + ) + + @classmethod + def fromkeys(cls, *args, **kwargs): + r""" + Identical to dict.fromkeys(). + """ + + return cls(dict.fromkeys(*args, **kwargs)) + + # noinspection PyMethodParameters + def __new__(e4b37cdf_d78a_4632_bade_6f0579d8efac, *args, **kwargs): + cls = e4b37cdf_d78a_4632_bade_6f0579d8efac + + has_kwargs = bool(kwargs) + continue_creation = True + self = None + + # check if there's only an argument and it's of the same class + if len(args) == 1 and not has_kwargs: + it = args[0] + + # no isinstance, to avoid subclassing problems + if it.__class__ == frozendict and cls == frozendict: + self = it + continue_creation = False + + if continue_creation: + self = dict.__new__(cls, *args, **kwargs) + + dict.__init__(self, *args, **kwargs) + + # empty singleton - start + + if self.__class__ == frozendict and not len(self): + global _empty_frozendict + + if _empty_frozendict is None: + _empty_frozendict = self + else: + self = _empty_frozendict + continue_creation = False + + # empty singleton - end + + if continue_creation: + object.__setattr__(self, "_hash", -1) + + return self + + # noinspection PyMissingConstructor + def __init__(self, *args, **kwargs): + pass + + def __hash__(self, *args, **kwargs): + r""" + Calculates the hash if all values are hashable, otherwise + raises a TypeError. + """ + + if self._hash != -1: + _hash = self._hash + else: + fs = frozenset(self.items()) + _hash = hash(fs) + + object.__setattr__(self, "_hash", _hash) + + return _hash + + def __repr__(self, *args, **kwargs): + r""" + Identical to dict.__repr__(). + """ + + body = super().__repr__(*args, **kwargs) + klass = self.__class__ + + if klass == frozendict: + name = f"{_module_name}.{klass.__name__}" + else: + name = klass.__name__ + + return f"{name}({body})" + + def copy(self): + r""" + Return the object itself, as it's an immutable. + """ + + klass = self.__class__ + + if klass == frozendict: + return self + + return klass(self) + + def __copy__(self, *args, **kwargs): + r""" + See copy(). + """ + + return self.copy() + + def __deepcopy__(self, memo, *args, **kwargs): + r""" + As for tuples, if hashable, see copy(); otherwise, it returns a + deepcopy. + """ + + klass = self.__class__ + return_copy = klass == frozendict + + if return_copy: + try: + hash(self) + except TypeError: + return_copy = False + + if return_copy: + return self.copy() + + tmp = deepcopy(dict(self)) + + return klass(tmp) + + def __reduce__(self, *args, **kwargs): + r""" + Support for `pickle`. + """ + + return (self.__class__, (dict(self),)) + + def set(self, key, val): + new_self = dict(self) + new_self[key] = val + + return self.__class__(new_self) + + def setdefault(self, key, default=None): + if key in self: + return self + + new_self = dict(self) + + new_self[key] = default + + return self.__class__(new_self) + + def delete(self, key): + new_self = dict(self) + del new_self[key] + + if new_self: + return self.__class__(new_self) + + return self.__class__() + + def _get_by_index(self, collection, index): + try: + return collection[index] + except IndexError: + maxindex = len(collection) - 1 + name = self.__class__.__name__ + raise IndexError( + f"{name} index {index} out of range {maxindex}" + ) from None + + def key(self, index=0): + collection = tuple(self.keys()) + + return self._get_by_index(collection, index) + + def value(self, index=0): + collection = tuple(self.values()) + + return self._get_by_index(collection, index) + + def item(self, index=0): + collection = tuple(self.items()) + + return self._get_by_index(collection, index) + + def __setitem__(self, key, val, *args, **kwargs): + raise TypeError( + f"'{self.__class__.__name__}' object doesn't support item " + "assignment" + ) + + def __delitem__(self, key, *args, **kwargs): + raise TypeError( + f"'{self.__class__.__name__}' object doesn't support item " + "deletion" + ) + + +def frozendict_or(self, other, *_args, **_kwargs): + res = {} + res.update(self) + res.update(other) + + return self.__class__(res) + + +frozendict.__or__ = frozendict_or +frozendict.__ior__ = frozendict_or + +try: + # noinspection PyStatementEffect + frozendict.__reversed__ +except AttributeError: # pragma: no cover + def frozendict_reversed(self, *_args, **_kwargs): + return reversed(tuple(self)) + + + frozendict.__reversed__ = frozendict_reversed + +frozendict.clear = immutable +frozendict.pop = immutable +frozendict.popitem = immutable +frozendict.update = immutable +frozendict.__delattr__ = immutable +frozendict.__setattr__ = immutable +frozendict.__module__ = _module_name + +__all__ = (frozendict.__name__,) diff --git a/data/miniconda3/lib/python3.13/site-packages/frozendict/cool.py b/data/miniconda3/lib/python3.13/site-packages/frozendict/cool.py new file mode 100644 index 0000000000000000000000000000000000000000..6c928354a10ec63aeaf669ff5c80b936f905fdf9 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/frozendict/cool.py @@ -0,0 +1,327 @@ +from types import MappingProxyType +from array import array +from frozendict import frozendict +from collections.abc import MutableMapping, MutableSequence, MutableSet +from enum import Enum + +# fix for python 3.9- + +# coverage does not work here! +if not issubclass(array, MutableSequence): # pragma: no cover + # noinspection PyUnresolvedReferences + MutableSequence.register(array) + + +def isIterableNotString(o): + from collections import abc + + return ( + isinstance(o, abc.Iterable) and + not isinstance(o, memoryview) and + not hasattr(o, "isalpha") + ) + + +def getItems(o): + from collections import abc + + if not isinstance(o, abc.Iterable): + raise TypeError("object must be an iterable") + + if isinstance(o, abc.Mapping): + return dict.items + + return enumerate + + +def nil(x): + return x + + +_freeze_conversion_map = frozendict({ + MutableMapping: frozendict, + bytearray: bytes, + MutableSequence: tuple, + MutableSet: frozenset, + Enum: nil, +}) + +_freeze_conversion_map_custom = {} + + +class FreezeError(Exception): + pass + + +class FreezeWarning(UserWarning): + pass + + +def register(to_convert, converter, *, inverse = False): + r""" + Adds a `converter` for a type `to_convert`. `converter` + must be callable. The new converter will be used by `deepfreeze()` + and has precedence over any previous converter. + + If `to_covert` has already a converter, a FreezeWarning is raised. + + If `inverse` is True, the conversion is considered from an immutable + type to a mutable one. This make it possible to convert mutable + objects nested in the registered immutable one. + """ + + if not issubclass(type(to_convert), type): + raise ValueError( + f"`to_convert` parameter must be a type, {to_convert} found" + ) + + try: + converter.__call__ + except AttributeError: + raise ValueError( + f"`converter` parameter must be a callable, {converter}" + + "found" + ) + + if inverse: + freeze_conversion_map = getFreezeConversionInverseMap() + else: + freeze_conversion_map = getFreezeConversionMap() + + if to_convert in freeze_conversion_map: + import warnings + + warnings.warn( + f"{to_convert.__name__} is already in the conversion map", + FreezeWarning + ) + + if inverse: + freeze_conversion_map = _freeze_conversion_inverse_map_custom + else: + freeze_conversion_map = _freeze_conversion_map_custom + + freeze_conversion_map[to_convert] = converter + + +def unregister(type, inverse = False): + r""" + Unregister a type from custom conversion. If `inverse` is `True`, + the unregistered conversion is an inverse conversion + (see `register()`). + """ + + if inverse: + freeze_conversion_map = _freeze_conversion_inverse_map_custom + else: + freeze_conversion_map = _freeze_conversion_map_custom + + try: + del freeze_conversion_map[type] + except KeyError: + raise FreezeError(f"{type.__name__} is not registered") + + +def getFreezeConversionMap(): + return _freeze_conversion_map | _freeze_conversion_map_custom + + +_freeze_conversion_inverse_map = frozendict({ + frozendict: dict, + MappingProxyType: dict, + tuple: list, +}) + +_freeze_conversion_inverse_map_custom = {} + + +def getFreezeConversionInverseMap(): + return ( + _freeze_conversion_inverse_map | + _freeze_conversion_inverse_map_custom + ) + + +_freeze_types = ( + [x for x in _freeze_conversion_map] + + [x for x in _freeze_conversion_inverse_map] +) + + +def getFreezeTypes(): + return (tuple( + _freeze_types + + [x for x in _freeze_conversion_map_custom] + + [x for x in _freeze_conversion_inverse_map_custom] + )) + + +_freeze_types_plain = (MutableSet, bytearray, array) + + +def deepfreeze( + o, + custom_converters = None, + custom_inverse_converters = None +): + r""" + Converts the object and all the objects nested in it in its + immutable counterparts. + + The conversion map is in getFreezeConversionMap(). + + You can register a new conversion using `register()` You can also + pass a map of custom converters with `custom_converters` and a map + of custom inverse converters with `custom_inverse_converters`, + without using `register()`. + + By default, if the type is not registered and has a `__dict__` + attribute, it's converted to the `frozendict` of that `__dict__`. + + This function assumes that hashable == immutable (that is not + always true). + + This function uses recursion, with all the limits of recursions in + Python. + + Where is a good old tail call when you need it? + """ + + from frozendict import frozendict + + if custom_converters is None: + custom_converters = frozendict() + + if custom_inverse_converters is None: + custom_inverse_converters = frozendict() + + for type_i, converter in custom_converters.items(): + if not issubclass(type(type_i), type): + raise ValueError( + f"{type_i} in `custom_converters` parameter is not a " + + "type" + ) + + try: + converter.__call__ + except AttributeError: + raise ValueError( + f"converter for {type_i} in `custom_converters` " + + "parameter is not a callable" + ) + + for type_i, converter in custom_inverse_converters.items(): + if not issubclass(type(type_i), type): + raise ValueError( + f"{type_i} in `custom_inverse_converters` parameter " + + "is not a type" + ) + + try: + converter.__call__ + except AttributeError: + raise ValueError( + f"converter for {type_i} in " + + "`custom_inverse_converters`parameter is not a callable" + ) + + type_o = type(o) + + freeze_types = tuple(custom_converters.keys()) + getFreezeTypes() + + base_type_o = None + + for freeze_type in freeze_types: + if isinstance(o, freeze_type): + base_type_o = freeze_type + break + + if base_type_o is None: + # this is before hash check because all object in Python are + # hashable by default, if not explicitly suppressed + try: + o.__dict__ + except AttributeError: + pass + else: + return frozendict(o.__dict__) + + try: + hash(o) + except TypeError: + pass + else: + # without a converter, we can only hope that + # hashable == immutable + return o + + supported_types = ", ".join((x.__name__ for x in freeze_types)) + + err = ( + f"type {type_o} is not hashable or is not equal or a " + + f"subclass of the supported types: {supported_types}" + ) + + raise TypeError(err) + + freeze_conversion_map = getFreezeConversionMap() + + freeze_conversion_map = freeze_conversion_map | custom_converters + + if base_type_o in _freeze_types_plain: + return freeze_conversion_map[base_type_o](o) + + if not isIterableNotString(o): + return freeze_conversion_map[base_type_o](o) + + freeze_conversion_inverse_map = getFreezeConversionInverseMap() + + freeze_conversion_inverse_map = ( + freeze_conversion_inverse_map | + custom_inverse_converters + ) + + frozen_type = base_type_o in freeze_conversion_inverse_map + + if frozen_type: + o = freeze_conversion_inverse_map[base_type_o](o) + + from copy import copy + + o_copy = copy(o) + + for k, v in getItems(o_copy)(o_copy): + o_copy[k] = deepfreeze( + v, + custom_converters = custom_converters, + custom_inverse_converters = custom_inverse_converters + ) + + try: + freeze = freeze_conversion_map[base_type_o] + except KeyError: + if frozen_type: + freeze = type_o + else: # pragma: no cover + raise + + return freeze(o_copy) + + +__all__ = ( + deepfreeze.__name__, + register.__name__, + unregister.__name__, + getFreezeConversionMap.__name__, + getFreezeConversionInverseMap.__name__, + FreezeError.__name__, + FreezeWarning.__name__, +) + +del MappingProxyType +del array +del frozendict +del MutableMapping +del MutableSequence +del MutableSet +del Enum diff --git a/data/miniconda3/lib/python3.13/site-packages/frozendict/core.py b/data/miniconda3/lib/python3.13/site-packages/frozendict/core.py new file mode 100644 index 0000000000000000000000000000000000000000..298d8fa7e2ad5822afb25391aa0862f719dfd649 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/frozendict/core.py @@ -0,0 +1,6 @@ +# this provides compatibility for older pickles +# created on a python-only implementation that +# specifically mention frozendict.core.frozendict + +# noinspection PyUnresolvedReferences +from frozendict import frozendict diff --git a/data/miniconda3/lib/python3.13/site-packages/frozendict/monkeypatch.py b/data/miniconda3/lib/python3.13/site-packages/frozendict/monkeypatch.py new file mode 100644 index 0000000000000000000000000000000000000000..3f52ef8175ab69f15eb43038d48326b89f7ac01b --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/frozendict/monkeypatch.py @@ -0,0 +1,207 @@ +_OldJsonEncoder = None +_oldOrjsonDumps = None +_oldMutableMappingSubclasshook = None + + +class MonkeypatchWarning(UserWarning): + pass + + +def checkCExtension(*, warn, warn_c = False): + import frozendict as cool + + res = cool.c_ext + + if warn and res == warn_c: + if warn_c: # pragma: no cover + msg = "C Extension version, monkeypatch will be not applied" + else: + msg = "Pure Python version, monkeypatch will be not applied" + + import warnings + + warnings.warn(msg, MonkeypatchWarning) + + return res + + +def patchOrUnpatchJson(*, patch, warn = True): # pragma: no cover + if not checkCExtension(warn = warn): + return + + from importlib import import_module + self = import_module(__name__) + import frozendict as cool + import json + + OldJsonEncoder = self._OldJsonEncoder + + # noinspection PyUnresolvedReferences, PyProtectedMember + FrozendictJsonEncoder = cool._getFrozendictJsonEncoder( + OldJsonEncoder + ) + + if patch: + DefaultJsonEncoder = FrozendictJsonEncoder + else: + DefaultJsonEncoder = OldJsonEncoder + + if DefaultJsonEncoder is None: + default_json_encoder = None + else: + default_json_encoder = DefaultJsonEncoder( + skipkeys = False, + ensure_ascii = True, + check_circular = True, + allow_nan = True, + indent = None, + separators = None, + default = None, + ) + + if patch: + if OldJsonEncoder is None: + self._OldJsonEncoder = json.encoder.JSONEncoder + else: + if OldJsonEncoder is None: + raise ValueError( + "Old json encoder is None " + + "(maybe you already unpatched json?)" + ) + + self._OldJsonEncoder = None + + cool.FrozendictJsonEncoder = FrozendictJsonEncoder + + json.JSONEncoder = DefaultJsonEncoder + json.encoder.JSONEncoder = DefaultJsonEncoder + json._default_encoder = default_json_encoder + + +def patchOrUnpatchOrjson(*, patch, warn = True): # pragma: no cover + if not checkCExtension(warn = warn): + return + + from importlib import import_module + self = import_module(__name__) + # noinspection PyUnresolvedReferences + import orjson + + if self._oldOrjsonDumps is None: + if not patch: + raise ValueError( + "Old orjson encoder is None " + + "(maybe you already unpatched orjson?)" + ) + + oldOrjsonDumps = orjson.dumps + else: + oldOrjsonDumps = self._oldOrjsonDumps + + if patch: + from frozendict import frozendict + + def frozendictOrjsonDumps(obj, *args, **kwargs): + if isinstance(obj, frozendict): + obj = dict(obj) + + return oldOrjsonDumps(obj, *args, **kwargs) + + defaultOrjsonDumps = frozendictOrjsonDumps + newOldOrjsonDumps = oldOrjsonDumps + else: + defaultOrjsonDumps = oldOrjsonDumps + newOldOrjsonDumps = None + + self._oldOrjsonDumps = newOldOrjsonDumps + orjson.dumps = defaultOrjsonDumps + orjson.orjson.dumps = defaultOrjsonDumps + + +def patchOrUnpatchMutableMappingSubclasshook( + *, + patch, + warn = True +): # pragma: no cover + warn_c = True + + if checkCExtension(warn = warn, warn_c = warn_c): + return + + from importlib import import_module + self = import_module(__name__) + from collections.abc import MutableMapping + from frozendict import frozendict + + if self._oldMutableMappingSubclasshook is None: + if not patch: + raise ValueError( + "Old MutableMapping subclasshook is None " + + "(maybe you already unpatched MutableMapping?)" + ) + + oldMutableMappingSubclasshook = MutableMapping.__subclasshook__ + else: + oldMutableMappingSubclasshook = self._oldMutableMappingSubclasshook + + if patch: + # noinspection PyDecorator + @classmethod + def frozendictMutableMappingSubclasshook( + klass, + subclass, + *args, + **kwargs + ): + if klass == MutableMapping: + if issubclass(subclass, frozendict): + return False + + return oldMutableMappingSubclasshook( + subclass, + *args, + **kwargs + ) + + return NotImplemented + + defaultMutableMappingSubclasshook = frozendictMutableMappingSubclasshook + newOldMutableMappingSubclasshook = oldMutableMappingSubclasshook + else: + defaultMutableMappingSubclasshook = oldMutableMappingSubclasshook + newOldMutableMappingSubclasshook = None + + self._oldMutableMappingSubclasshook = newOldMutableMappingSubclasshook + MutableMapping.__subclasshook__ = defaultMutableMappingSubclasshook + + try: + # noinspection PyUnresolvedReferences, PyProtectedMember + MutableMapping._abc_caches_clear() + except AttributeError: + # noinspection PyUnresolvedReferences, PyProtectedMember + MutableMapping._abc_cache.discard(frozendict) + # noinspection PyUnresolvedReferences, PyProtectedMember + MutableMapping._abc_negative_cache.discard(frozendict) + + +def patchOrUnpatchAll(*, patch, warn = True, raise_orjson = False): + patchOrUnpatchJson(patch = patch, warn = warn) + + try: + import orjson + except ImportError: # pragma: no cover + if raise_orjson: + raise + else: # pragma: no cover + patchOrUnpatchOrjson(patch = patch, warn = warn) + + patchOrUnpatchMutableMappingSubclasshook(patch = patch, warn = warn) + + +__all__ = ( + patchOrUnpatchJson.__name__, + patchOrUnpatchOrjson.__name__, + patchOrUnpatchMutableMappingSubclasshook.__name__, + patchOrUnpatchAll.__name__, + MonkeypatchWarning.__name__, +) diff --git a/data/miniconda3/lib/python3.13/site-packages/frozendict/py.typed b/data/miniconda3/lib/python3.13/site-packages/frozendict/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/lib/python3.13/site-packages/frozendict/version.py b/data/miniconda3/lib/python3.13/site-packages/frozendict/version.py new file mode 100644 index 0000000000000000000000000000000000000000..0be68d9f178bc3042ee3fa4838e2aba600f8a573 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/frozendict/version.py @@ -0,0 +1 @@ +version = "2.4.6" diff --git a/data/miniconda3/lib/python3.13/site-packages/h11-0.16.0.dist-info/INSTALLER b/data/miniconda3/lib/python3.13/site-packages/h11-0.16.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/h11-0.16.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/data/miniconda3/lib/python3.13/site-packages/h11-0.16.0.dist-info/METADATA b/data/miniconda3/lib/python3.13/site-packages/h11-0.16.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..8a2f639061cc4a203f7109d8335d28076442c61d --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/h11-0.16.0.dist-info/METADATA @@ -0,0 +1,202 @@ +Metadata-Version: 2.4 +Name: h11 +Version: 0.16.0 +Summary: A pure-Python, bring-your-own-I/O implementation of HTTP/1.1 +Home-page: https://github.com/python-hyper/h11 +Author: Nathaniel J. Smith +Author-email: njs@pobox.com +License: MIT +Classifier: Development Status :: 3 - Alpha +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Topic :: Internet :: WWW/HTTP +Classifier: Topic :: System :: Networking +Requires-Python: >=3.8 +License-File: LICENSE.txt +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: home-page +Dynamic: license +Dynamic: license-file +Dynamic: requires-python +Dynamic: summary + +h11 +=== + +.. image:: https://travis-ci.org/python-hyper/h11.svg?branch=master + :target: https://travis-ci.org/python-hyper/h11 + :alt: Automated test status + +.. image:: https://codecov.io/gh/python-hyper/h11/branch/master/graph/badge.svg + :target: https://codecov.io/gh/python-hyper/h11 + :alt: Test coverage + +.. image:: https://readthedocs.org/projects/h11/badge/?version=latest + :target: http://h11.readthedocs.io/en/latest/?badge=latest + :alt: Documentation Status + +This is a little HTTP/1.1 library written from scratch in Python, +heavily inspired by `hyper-h2 `_. + +It's a "bring-your-own-I/O" library; h11 contains no IO code +whatsoever. This means you can hook h11 up to your favorite network +API, and that could be anything you want: synchronous, threaded, +asynchronous, or your own implementation of `RFC 6214 +`_ -- h11 won't judge you. +(Compare this to the current state of the art, where every time a `new +network API `_ comes along then someone +gets to start over reimplementing the entire HTTP protocol from +scratch.) Cory Benfield made an `excellent blog post describing the +benefits of this approach +`_, or if you like video +then here's his `PyCon 2016 talk on the same theme +`_. + +This also means that h11 is not immediately useful out of the box: +it's a toolkit for building programs that speak HTTP, not something +that could directly replace ``requests`` or ``twisted.web`` or +whatever. But h11 makes it much easier to implement something like +``requests`` or ``twisted.web``. + +At a high level, working with h11 goes like this: + +1) First, create an ``h11.Connection`` object to track the state of a + single HTTP/1.1 connection. + +2) When you read data off the network, pass it to + ``conn.receive_data(...)``; you'll get back a list of objects + representing high-level HTTP "events". + +3) When you want to send a high-level HTTP event, create the + corresponding "event" object and pass it to ``conn.send(...)``; + this will give you back some bytes that you can then push out + through the network. + +For example, a client might instantiate and then send a +``h11.Request`` object, then zero or more ``h11.Data`` objects for the +request body (e.g., if this is a POST), and then a +``h11.EndOfMessage`` to indicate the end of the message. Then the +server would then send back a ``h11.Response``, some ``h11.Data``, and +its own ``h11.EndOfMessage``. If either side violates the protocol, +you'll get a ``h11.ProtocolError`` exception. + +h11 is suitable for implementing both servers and clients, and has a +pleasantly symmetric API: the events you send as a client are exactly +the ones that you receive as a server and vice-versa. + +`Here's an example of a tiny HTTP client +`_ + +It also has `a fine manual `_. + +FAQ +--- + +*Whyyyyy?* + +I wanted to play with HTTP in `Curio +`__ and `Trio +`__, which at the time didn't have any +HTTP libraries. So I thought, no big deal, Python has, like, a dozen +different implementations of HTTP, surely I can find one that's +reusable. I didn't find one, but I did find Cory's call-to-arms +blog-post. So I figured, well, fine, if I have to implement HTTP from +scratch, at least I can make sure no-one *else* has to ever again. + +*Should I use it?* + +Maybe. You should be aware that it's a very young project. But, it's +feature complete and has an exhaustive test-suite and complete docs, +so the next step is for people to try using it and see how it goes +:-). If you do then please let us know -- if nothing else we'll want +to talk to you before making any incompatible changes! + +*What are the features/limitations?* + +Roughly speaking, it's trying to be a robust, complete, and non-hacky +implementation of the first "chapter" of the HTTP/1.1 spec: `RFC 7230: +HTTP/1.1 Message Syntax and Routing +`_. That is, it mostly focuses on +implementing HTTP at the level of taking bytes on and off the wire, +and the headers related to that, and tries to be anal about spec +conformance. It doesn't know about higher-level concerns like URL +routing, conditional GETs, cross-origin cookie policies, or content +negotiation. But it does know how to take care of framing, +cross-version differences in keep-alive handling, and the "obsolete +line folding" rule, so you can focus your energies on the hard / +interesting parts for your application, and it tries to support the +full specification in the sense that any useful HTTP/1.1 conformant +application should be able to use h11. + +It's pure Python, and has no dependencies outside of the standard +library. + +It has a test suite with 100.0% coverage for both statements and +branches. + +Currently it supports Python 3 (testing on 3.8-3.12) and PyPy 3. +The last Python 2-compatible version was h11 0.11.x. +(Originally it had a Cython wrapper for `http-parser +`_ and a beautiful nested state +machine implemented with ``yield from`` to postprocess the output. But +I had to take these out -- the new *parser* needs fewer lines-of-code +than the old *parser wrapper*, is written in pure Python, uses no +exotic language syntax, and has more features. It's sad, really; that +old state machine was really slick. I just need a few sentences here +to mourn that.) + +I don't know how fast it is. I haven't benchmarked or profiled it yet, +so it's probably got a few pointless hot spots, and I've been trying +to err on the side of simplicity and robustness instead of +micro-optimization. But at the architectural level I tried hard to +avoid fundamentally bad decisions, e.g., I believe that all the +parsing algorithms remain linear-time even in the face of pathological +input like slowloris, and there are no byte-by-byte loops. (I also +believe that it maintains bounded memory usage in the face of +arbitrary/pathological input.) + +The whole library is ~800 lines-of-code. You can read and understand +the whole thing in less than an hour. Most of the energy invested in +this so far has been spent on trying to keep things simple by +minimizing special-cases and ad hoc state manipulation; even though it +is now quite small and simple, I'm still annoyed that I haven't +figured out how to make it even smaller and simpler. (Unfortunately, +HTTP does not lend itself to simplicity.) + +The API is ~feature complete and I don't expect the general outlines +to change much, but you can't judge an API's ergonomics until you +actually document and use it, so I'd expect some changes in the +details. + +*How do I try it?* + +.. code-block:: sh + + $ pip install h11 + $ git clone git@github.com:python-hyper/h11 + $ cd h11/examples + $ python basic-client.py + +and go from there. + +*License?* + +MIT + +*Code of conduct?* + +Contributors are requested to follow our `code of conduct +`_ in +all project spaces. diff --git a/data/miniconda3/lib/python3.13/site-packages/h11-0.16.0.dist-info/RECORD b/data/miniconda3/lib/python3.13/site-packages/h11-0.16.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..dee4864da26e11320bae425074d7c1b64dac1f95 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/h11-0.16.0.dist-info/RECORD @@ -0,0 +1,29 @@ +h11-0.16.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +h11-0.16.0.dist-info/METADATA,sha256=KPMmCYrAn8unm48YD5YIfIQf4kViFct7hyqcfVzRnWQ,8348 +h11-0.16.0.dist-info/RECORD,, +h11-0.16.0.dist-info/WHEEL,sha256=CmyFI0kx5cdEMTLiONQRbGQwjIoR1aIYB7eCAQ4KPJ0,91 +h11-0.16.0.dist-info/licenses/LICENSE.txt,sha256=N9tbuFkm2yikJ6JYZ_ELEjIAOuob5pzLhRE4rbjm82E,1124 +h11-0.16.0.dist-info/top_level.txt,sha256=F7dC4jl3zeh8TGHEPaWJrMbeuoWbS379Gwdi-Yvdcis,4 +h11/__init__.py,sha256=iO1KzkSO42yZ6ffg-VMgbx_ZVTWGUY00nRYEWn-s3kY,1507 +h11/__pycache__/__init__.cpython-313.pyc,, +h11/__pycache__/_abnf.cpython-313.pyc,, +h11/__pycache__/_connection.cpython-313.pyc,, +h11/__pycache__/_events.cpython-313.pyc,, +h11/__pycache__/_headers.cpython-313.pyc,, +h11/__pycache__/_readers.cpython-313.pyc,, +h11/__pycache__/_receivebuffer.cpython-313.pyc,, +h11/__pycache__/_state.cpython-313.pyc,, +h11/__pycache__/_util.cpython-313.pyc,, +h11/__pycache__/_version.cpython-313.pyc,, +h11/__pycache__/_writers.cpython-313.pyc,, +h11/_abnf.py,sha256=ybixr0xsupnkA6GFAyMubuXF6Tc1lb_hF890NgCsfNc,4815 +h11/_connection.py,sha256=k9YRVf6koZqbttBW36xSWaJpWdZwa-xQVU9AHEo9DuI,26863 +h11/_events.py,sha256=I97aXoal1Wu7dkL548BANBUCkOIbe-x5CioYA9IBY14,11792 +h11/_headers.py,sha256=P7D-lBNxHwdLZPLimmYwrPG-9ZkjElvvJZJdZAgSP-4,10412 +h11/_readers.py,sha256=a4RypORUCC3d0q_kxPuBIM7jTD8iLt5X91TH0FsduN4,8590 +h11/_receivebuffer.py,sha256=xrspsdsNgWFxRfQcTXxR8RrdjRXXTK0Io5cQYWpJ1Ws,5252 +h11/_state.py,sha256=_5LG_BGR8FCcFQeBPH-TMHgm_-B-EUcWCnQof_9XjFE,13231 +h11/_util.py,sha256=LWkkjXyJaFlAy6Lt39w73UStklFT5ovcvo0TkY7RYuk,4888 +h11/_version.py,sha256=GVSsbPSPDcOuF6ptfIiXnVJoaEm3ygXbMnqlr_Giahw,686 +h11/_writers.py,sha256=oFKm6PtjeHfbj4RLX7VB7KDc1gIY53gXG3_HR9ltmTA,5081 +h11/py.typed,sha256=sow9soTwP9T_gEAQSVh7Gb8855h04Nwmhs2We-JRgZM,7 diff --git a/data/miniconda3/lib/python3.13/site-packages/h11-0.16.0.dist-info/WHEEL b/data/miniconda3/lib/python3.13/site-packages/h11-0.16.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..1eb3c49d99559863120cfb8433fc8738fba43ba9 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/h11-0.16.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (78.1.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/data/miniconda3/lib/python3.13/site-packages/h11-0.16.0.dist-info/top_level.txt b/data/miniconda3/lib/python3.13/site-packages/h11-0.16.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..0d24def711344ec6f4da2108f7d5c9261eb35f8b --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/h11-0.16.0.dist-info/top_level.txt @@ -0,0 +1 @@ +h11 diff --git a/data/miniconda3/lib/python3.13/site-packages/h11/__init__.py b/data/miniconda3/lib/python3.13/site-packages/h11/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..989e92c3458681a6f0be72ae4105ea742750d328 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/h11/__init__.py @@ -0,0 +1,62 @@ +# A highish-level implementation of the HTTP/1.1 wire protocol (RFC 7230), +# containing no networking code at all, loosely modelled on hyper-h2's generic +# implementation of HTTP/2 (and in particular the h2.connection.H2Connection +# class). There's still a bunch of subtle details you need to get right if you +# want to make this actually useful, because it doesn't implement all the +# semantics to check that what you're asking to write to the wire is sensible, +# but at least it gets you out of dealing with the wire itself. + +from h11._connection import Connection, NEED_DATA, PAUSED +from h11._events import ( + ConnectionClosed, + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from h11._state import ( + CLIENT, + CLOSED, + DONE, + ERROR, + IDLE, + MIGHT_SWITCH_PROTOCOL, + MUST_CLOSE, + SEND_BODY, + SEND_RESPONSE, + SERVER, + SWITCHED_PROTOCOL, +) +from h11._util import LocalProtocolError, ProtocolError, RemoteProtocolError +from h11._version import __version__ + +PRODUCT_ID = "python-h11/" + __version__ + + +__all__ = ( + "Connection", + "NEED_DATA", + "PAUSED", + "ConnectionClosed", + "Data", + "EndOfMessage", + "Event", + "InformationalResponse", + "Request", + "Response", + "CLIENT", + "CLOSED", + "DONE", + "ERROR", + "IDLE", + "MUST_CLOSE", + "SEND_BODY", + "SEND_RESPONSE", + "SERVER", + "SWITCHED_PROTOCOL", + "ProtocolError", + "LocalProtocolError", + "RemoteProtocolError", +) diff --git a/data/miniconda3/lib/python3.13/site-packages/h11/_abnf.py b/data/miniconda3/lib/python3.13/site-packages/h11/_abnf.py new file mode 100644 index 0000000000000000000000000000000000000000..933587fba22290d7eb7df4c88e12f1e61702b8ce --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/h11/_abnf.py @@ -0,0 +1,132 @@ +# We use native strings for all the re patterns, to take advantage of string +# formatting, and then convert to bytestrings when compiling the final re +# objects. + +# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#whitespace +# OWS = *( SP / HTAB ) +# ; optional whitespace +OWS = r"[ \t]*" + +# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#rule.token.separators +# token = 1*tchar +# +# tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" +# / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" +# / DIGIT / ALPHA +# ; any VCHAR, except delimiters +token = r"[-!#$%&'*+.^_`|~0-9a-zA-Z]+" + +# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#header.fields +# field-name = token +field_name = token + +# The standard says: +# +# field-value = *( field-content / obs-fold ) +# field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] +# field-vchar = VCHAR / obs-text +# obs-fold = CRLF 1*( SP / HTAB ) +# ; obsolete line folding +# ; see Section 3.2.4 +# +# https://tools.ietf.org/html/rfc5234#appendix-B.1 +# +# VCHAR = %x21-7E +# ; visible (printing) characters +# +# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#rule.quoted-string +# obs-text = %x80-FF +# +# However, the standard definition of field-content is WRONG! It disallows +# fields containing a single visible character surrounded by whitespace, +# e.g. "foo a bar". +# +# See: https://www.rfc-editor.org/errata_search.php?rfc=7230&eid=4189 +# +# So our definition of field_content attempts to fix it up... +# +# Also, we allow lots of control characters, because apparently people assume +# that they're legal in practice (e.g., google analytics makes cookies with +# \x01 in them!): +# https://github.com/python-hyper/h11/issues/57 +# We still don't allow NUL or whitespace, because those are often treated as +# meta-characters and letting them through can lead to nasty issues like SSRF. +vchar = r"[\x21-\x7e]" +vchar_or_obs_text = r"[^\x00\s]" +field_vchar = vchar_or_obs_text +field_content = r"{field_vchar}+(?:[ \t]+{field_vchar}+)*".format(**globals()) + +# We handle obs-fold at a different level, and our fixed-up field_content +# already grows to swallow the whole value, so ? instead of * +field_value = r"({field_content})?".format(**globals()) + +# header-field = field-name ":" OWS field-value OWS +header_field = ( + r"(?P{field_name})" + r":" + r"{OWS}" + r"(?P{field_value})" + r"{OWS}".format(**globals()) +) + +# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#request.line +# +# request-line = method SP request-target SP HTTP-version CRLF +# method = token +# HTTP-version = HTTP-name "/" DIGIT "." DIGIT +# HTTP-name = %x48.54.54.50 ; "HTTP", case-sensitive +# +# request-target is complicated (see RFC 7230 sec 5.3) -- could be path, full +# URL, host+port (for connect), or even "*", but in any case we are guaranteed +# that it contists of the visible printing characters. +method = token +request_target = r"{vchar}+".format(**globals()) +http_version = r"HTTP/(?P[0-9]\.[0-9])" +request_line = ( + r"(?P{method})" + r" " + r"(?P{request_target})" + r" " + r"{http_version}".format(**globals()) +) + +# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#status.line +# +# status-line = HTTP-version SP status-code SP reason-phrase CRLF +# status-code = 3DIGIT +# reason-phrase = *( HTAB / SP / VCHAR / obs-text ) +status_code = r"[0-9]{3}" +reason_phrase = r"([ \t]|{vchar_or_obs_text})*".format(**globals()) +status_line = ( + r"{http_version}" + r" " + r"(?P{status_code})" + # However, there are apparently a few too many servers out there that just + # leave out the reason phrase: + # https://github.com/scrapy/scrapy/issues/345#issuecomment-281756036 + # https://github.com/seanmonstar/httparse/issues/29 + # so make it optional. ?: is a non-capturing group. + r"(?: (?P{reason_phrase}))?".format(**globals()) +) + +HEXDIG = r"[0-9A-Fa-f]" +# Actually +# +# chunk-size = 1*HEXDIG +# +# but we impose an upper-limit to avoid ridiculosity. len(str(2**64)) == 20 +chunk_size = r"({HEXDIG}){{1,20}}".format(**globals()) +# Actually +# +# chunk-ext = *( ";" chunk-ext-name [ "=" chunk-ext-val ] ) +# +# but we aren't parsing the things so we don't really care. +chunk_ext = r";.*" +chunk_header = ( + r"(?P{chunk_size})" + r"(?P{chunk_ext})?" + r"{OWS}\r\n".format( + **globals() + ) # Even though the specification does not allow for extra whitespaces, + # we are lenient with trailing whitespaces because some servers on the wild use it. +) diff --git a/data/miniconda3/lib/python3.13/site-packages/h11/_connection.py b/data/miniconda3/lib/python3.13/site-packages/h11/_connection.py new file mode 100644 index 0000000000000000000000000000000000000000..e37d82a82a882c072cb938a90eb4486b51cdad99 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/h11/_connection.py @@ -0,0 +1,659 @@ +# This contains the main Connection class. Everything in h11 revolves around +# this. +from typing import ( + Any, + Callable, + cast, + Dict, + List, + Optional, + overload, + Tuple, + Type, + Union, +) + +from ._events import ( + ConnectionClosed, + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from ._headers import get_comma_header, has_expect_100_continue, set_comma_header +from ._readers import READERS, ReadersType +from ._receivebuffer import ReceiveBuffer +from ._state import ( + _SWITCH_CONNECT, + _SWITCH_UPGRADE, + CLIENT, + ConnectionState, + DONE, + ERROR, + MIGHT_SWITCH_PROTOCOL, + SEND_BODY, + SERVER, + SWITCHED_PROTOCOL, +) +from ._util import ( # Import the internal things we need + LocalProtocolError, + RemoteProtocolError, + Sentinel, +) +from ._writers import WRITERS, WritersType + +# Everything in __all__ gets re-exported as part of the h11 public API. +__all__ = ["Connection", "NEED_DATA", "PAUSED"] + + +class NEED_DATA(Sentinel, metaclass=Sentinel): + pass + + +class PAUSED(Sentinel, metaclass=Sentinel): + pass + + +# If we ever have this much buffered without it making a complete parseable +# event, we error out. The only time we really buffer is when reading the +# request/response line + headers together, so this is effectively the limit on +# the size of that. +# +# Some precedents for defaults: +# - node.js: 80 * 1024 +# - tomcat: 8 * 1024 +# - IIS: 16 * 1024 +# - Apache: <8 KiB per line> +DEFAULT_MAX_INCOMPLETE_EVENT_SIZE = 16 * 1024 + + +# RFC 7230's rules for connection lifecycles: +# - If either side says they want to close the connection, then the connection +# must close. +# - HTTP/1.1 defaults to keep-alive unless someone says Connection: close +# - HTTP/1.0 defaults to close unless both sides say Connection: keep-alive +# (and even this is a mess -- e.g. if you're implementing a proxy then +# sending Connection: keep-alive is forbidden). +# +# We simplify life by simply not supporting keep-alive with HTTP/1.0 peers. So +# our rule is: +# - If someone says Connection: close, we will close +# - If someone uses HTTP/1.0, we will close. +def _keep_alive(event: Union[Request, Response]) -> bool: + connection = get_comma_header(event.headers, b"connection") + if b"close" in connection: + return False + if getattr(event, "http_version", b"1.1") < b"1.1": + return False + return True + + +def _body_framing( + request_method: bytes, event: Union[Request, Response] +) -> Tuple[str, Union[Tuple[()], Tuple[int]]]: + # Called when we enter SEND_BODY to figure out framing information for + # this body. + # + # These are the only two events that can trigger a SEND_BODY state: + assert type(event) in (Request, Response) + # Returns one of: + # + # ("content-length", count) + # ("chunked", ()) + # ("http/1.0", ()) + # + # which are (lookup key, *args) for constructing body reader/writer + # objects. + # + # Reference: https://tools.ietf.org/html/rfc7230#section-3.3.3 + # + # Step 1: some responses always have an empty body, regardless of what the + # headers say. + if type(event) is Response: + if ( + event.status_code in (204, 304) + or request_method == b"HEAD" + or (request_method == b"CONNECT" and 200 <= event.status_code < 300) + ): + return ("content-length", (0,)) + # Section 3.3.3 also lists another case -- responses with status_code + # < 200. For us these are InformationalResponses, not Responses, so + # they can't get into this function in the first place. + assert event.status_code >= 200 + + # Step 2: check for Transfer-Encoding (T-E beats C-L): + transfer_encodings = get_comma_header(event.headers, b"transfer-encoding") + if transfer_encodings: + assert transfer_encodings == [b"chunked"] + return ("chunked", ()) + + # Step 3: check for Content-Length + content_lengths = get_comma_header(event.headers, b"content-length") + if content_lengths: + return ("content-length", (int(content_lengths[0]),)) + + # Step 4: no applicable headers; fallback/default depends on type + if type(event) is Request: + return ("content-length", (0,)) + else: + return ("http/1.0", ()) + + +################################################################ +# +# The main Connection class +# +################################################################ + + +class Connection: + """An object encapsulating the state of an HTTP connection. + + Args: + our_role: If you're implementing a client, pass :data:`h11.CLIENT`. If + you're implementing a server, pass :data:`h11.SERVER`. + + max_incomplete_event_size (int): + The maximum number of bytes we're willing to buffer of an + incomplete event. In practice this mostly sets a limit on the + maximum size of the request/response line + headers. If this is + exceeded, then :meth:`next_event` will raise + :exc:`RemoteProtocolError`. + + """ + + def __init__( + self, + our_role: Type[Sentinel], + max_incomplete_event_size: int = DEFAULT_MAX_INCOMPLETE_EVENT_SIZE, + ) -> None: + self._max_incomplete_event_size = max_incomplete_event_size + # State and role tracking + if our_role not in (CLIENT, SERVER): + raise ValueError(f"expected CLIENT or SERVER, not {our_role!r}") + self.our_role = our_role + self.their_role: Type[Sentinel] + if our_role is CLIENT: + self.their_role = SERVER + else: + self.their_role = CLIENT + self._cstate = ConnectionState() + + # Callables for converting data->events or vice-versa given the + # current state + self._writer = self._get_io_object(self.our_role, None, WRITERS) + self._reader = self._get_io_object(self.their_role, None, READERS) + + # Holds any unprocessed received data + self._receive_buffer = ReceiveBuffer() + # If this is true, then it indicates that the incoming connection was + # closed *after* the end of whatever's in self._receive_buffer: + self._receive_buffer_closed = False + + # Extra bits of state that don't fit into the state machine. + # + # These two are only used to interpret framing headers for figuring + # out how to read/write response bodies. their_http_version is also + # made available as a convenient public API. + self.their_http_version: Optional[bytes] = None + self._request_method: Optional[bytes] = None + # This is pure flow-control and doesn't at all affect the set of legal + # transitions, so no need to bother ConnectionState with it: + self.client_is_waiting_for_100_continue = False + + @property + def states(self) -> Dict[Type[Sentinel], Type[Sentinel]]: + """A dictionary like:: + + {CLIENT: , SERVER: } + + See :ref:`state-machine` for details. + + """ + return dict(self._cstate.states) + + @property + def our_state(self) -> Type[Sentinel]: + """The current state of whichever role we are playing. See + :ref:`state-machine` for details. + """ + return self._cstate.states[self.our_role] + + @property + def their_state(self) -> Type[Sentinel]: + """The current state of whichever role we are NOT playing. See + :ref:`state-machine` for details. + """ + return self._cstate.states[self.their_role] + + @property + def they_are_waiting_for_100_continue(self) -> bool: + return self.their_role is CLIENT and self.client_is_waiting_for_100_continue + + def start_next_cycle(self) -> None: + """Attempt to reset our connection state for a new request/response + cycle. + + If both client and server are in :data:`DONE` state, then resets them + both to :data:`IDLE` state in preparation for a new request/response + cycle on this same connection. Otherwise, raises a + :exc:`LocalProtocolError`. + + See :ref:`keepalive-and-pipelining`. + + """ + old_states = dict(self._cstate.states) + self._cstate.start_next_cycle() + self._request_method = None + # self.their_http_version gets left alone, since it presumably lasts + # beyond a single request/response cycle + assert not self.client_is_waiting_for_100_continue + self._respond_to_state_changes(old_states) + + def _process_error(self, role: Type[Sentinel]) -> None: + old_states = dict(self._cstate.states) + self._cstate.process_error(role) + self._respond_to_state_changes(old_states) + + def _server_switch_event(self, event: Event) -> Optional[Type[Sentinel]]: + if type(event) is InformationalResponse and event.status_code == 101: + return _SWITCH_UPGRADE + if type(event) is Response: + if ( + _SWITCH_CONNECT in self._cstate.pending_switch_proposals + and 200 <= event.status_code < 300 + ): + return _SWITCH_CONNECT + return None + + # All events go through here + def _process_event(self, role: Type[Sentinel], event: Event) -> None: + # First, pass the event through the state machine to make sure it + # succeeds. + old_states = dict(self._cstate.states) + if role is CLIENT and type(event) is Request: + if event.method == b"CONNECT": + self._cstate.process_client_switch_proposal(_SWITCH_CONNECT) + if get_comma_header(event.headers, b"upgrade"): + self._cstate.process_client_switch_proposal(_SWITCH_UPGRADE) + server_switch_event = None + if role is SERVER: + server_switch_event = self._server_switch_event(event) + self._cstate.process_event(role, type(event), server_switch_event) + + # Then perform the updates triggered by it. + + if type(event) is Request: + self._request_method = event.method + + if role is self.their_role and type(event) in ( + Request, + Response, + InformationalResponse, + ): + event = cast(Union[Request, Response, InformationalResponse], event) + self.their_http_version = event.http_version + + # Keep alive handling + # + # RFC 7230 doesn't really say what one should do if Connection: close + # shows up on a 1xx InformationalResponse. I think the idea is that + # this is not supposed to happen. In any case, if it does happen, we + # ignore it. + if type(event) in (Request, Response) and not _keep_alive( + cast(Union[Request, Response], event) + ): + self._cstate.process_keep_alive_disabled() + + # 100-continue + if type(event) is Request and has_expect_100_continue(event): + self.client_is_waiting_for_100_continue = True + if type(event) in (InformationalResponse, Response): + self.client_is_waiting_for_100_continue = False + if role is CLIENT and type(event) in (Data, EndOfMessage): + self.client_is_waiting_for_100_continue = False + + self._respond_to_state_changes(old_states, event) + + def _get_io_object( + self, + role: Type[Sentinel], + event: Optional[Event], + io_dict: Union[ReadersType, WritersType], + ) -> Optional[Callable[..., Any]]: + # event may be None; it's only used when entering SEND_BODY + state = self._cstate.states[role] + if state is SEND_BODY: + # Special case: the io_dict has a dict of reader/writer factories + # that depend on the request/response framing. + framing_type, args = _body_framing( + cast(bytes, self._request_method), cast(Union[Request, Response], event) + ) + return io_dict[SEND_BODY][framing_type](*args) # type: ignore[index] + else: + # General case: the io_dict just has the appropriate reader/writer + # for this state + return io_dict.get((role, state)) # type: ignore[return-value] + + # This must be called after any action that might have caused + # self._cstate.states to change. + def _respond_to_state_changes( + self, + old_states: Dict[Type[Sentinel], Type[Sentinel]], + event: Optional[Event] = None, + ) -> None: + # Update reader/writer + if self.our_state != old_states[self.our_role]: + self._writer = self._get_io_object(self.our_role, event, WRITERS) + if self.their_state != old_states[self.their_role]: + self._reader = self._get_io_object(self.their_role, event, READERS) + + @property + def trailing_data(self) -> Tuple[bytes, bool]: + """Data that has been received, but not yet processed, represented as + a tuple with two elements, where the first is a byte-string containing + the unprocessed data itself, and the second is a bool that is True if + the receive connection was closed. + + See :ref:`switching-protocols` for discussion of why you'd want this. + """ + return (bytes(self._receive_buffer), self._receive_buffer_closed) + + def receive_data(self, data: bytes) -> None: + """Add data to our internal receive buffer. + + This does not actually do any processing on the data, just stores + it. To trigger processing, you have to call :meth:`next_event`. + + Args: + data (:term:`bytes-like object`): + The new data that was just received. + + Special case: If *data* is an empty byte-string like ``b""``, + then this indicates that the remote side has closed the + connection (end of file). Normally this is convenient, because + standard Python APIs like :meth:`file.read` or + :meth:`socket.recv` use ``b""`` to indicate end-of-file, while + other failures to read are indicated using other mechanisms + like raising :exc:`TimeoutError`. When using such an API you + can just blindly pass through whatever you get from ``read`` + to :meth:`receive_data`, and everything will work. + + But, if you have an API where reading an empty string is a + valid non-EOF condition, then you need to be aware of this and + make sure to check for such strings and avoid passing them to + :meth:`receive_data`. + + Returns: + Nothing, but after calling this you should call :meth:`next_event` + to parse the newly received data. + + Raises: + RuntimeError: + Raised if you pass an empty *data*, indicating EOF, and then + pass a non-empty *data*, indicating more data that somehow + arrived after the EOF. + + (Calling ``receive_data(b"")`` multiple times is fine, + and equivalent to calling it once.) + + """ + if data: + if self._receive_buffer_closed: + raise RuntimeError("received close, then received more data?") + self._receive_buffer += data + else: + self._receive_buffer_closed = True + + def _extract_next_receive_event( + self, + ) -> Union[Event, Type[NEED_DATA], Type[PAUSED]]: + state = self.their_state + # We don't pause immediately when they enter DONE, because even in + # DONE state we can still process a ConnectionClosed() event. But + # if we have data in our buffer, then we definitely aren't getting + # a ConnectionClosed() immediately and we need to pause. + if state is DONE and self._receive_buffer: + return PAUSED + if state is MIGHT_SWITCH_PROTOCOL or state is SWITCHED_PROTOCOL: + return PAUSED + assert self._reader is not None + event = self._reader(self._receive_buffer) + if event is None: + if not self._receive_buffer and self._receive_buffer_closed: + # In some unusual cases (basically just HTTP/1.0 bodies), EOF + # triggers an actual protocol event; in that case, we want to + # return that event, and then the state will change and we'll + # get called again to generate the actual ConnectionClosed(). + if hasattr(self._reader, "read_eof"): + event = self._reader.read_eof() + else: + event = ConnectionClosed() + if event is None: + event = NEED_DATA + return event # type: ignore[no-any-return] + + def next_event(self) -> Union[Event, Type[NEED_DATA], Type[PAUSED]]: + """Parse the next event out of our receive buffer, update our internal + state, and return it. + + This is a mutating operation -- think of it like calling :func:`next` + on an iterator. + + Returns: + : One of three things: + + 1) An event object -- see :ref:`events`. + + 2) The special constant :data:`NEED_DATA`, which indicates that + you need to read more data from your socket and pass it to + :meth:`receive_data` before this method will be able to return + any more events. + + 3) The special constant :data:`PAUSED`, which indicates that we + are not in a state where we can process incoming data (usually + because the peer has finished their part of the current + request/response cycle, and you have not yet called + :meth:`start_next_cycle`). See :ref:`flow-control` for details. + + Raises: + RemoteProtocolError: + The peer has misbehaved. You should close the connection + (possibly after sending some kind of 4xx response). + + Once this method returns :class:`ConnectionClosed` once, then all + subsequent calls will also return :class:`ConnectionClosed`. + + If this method raises any exception besides :exc:`RemoteProtocolError` + then that's a bug -- if it happens please file a bug report! + + If this method raises any exception then it also sets + :attr:`Connection.their_state` to :data:`ERROR` -- see + :ref:`error-handling` for discussion. + + """ + + if self.their_state is ERROR: + raise RemoteProtocolError("Can't receive data when peer state is ERROR") + try: + event = self._extract_next_receive_event() + if event not in [NEED_DATA, PAUSED]: + self._process_event(self.their_role, cast(Event, event)) + if event is NEED_DATA: + if len(self._receive_buffer) > self._max_incomplete_event_size: + # 431 is "Request header fields too large" which is pretty + # much the only situation where we can get here + raise RemoteProtocolError( + "Receive buffer too long", error_status_hint=431 + ) + if self._receive_buffer_closed: + # We're still trying to complete some event, but that's + # never going to happen because no more data is coming + raise RemoteProtocolError("peer unexpectedly closed connection") + return event + except BaseException as exc: + self._process_error(self.their_role) + if isinstance(exc, LocalProtocolError): + exc._reraise_as_remote_protocol_error() + else: + raise + + @overload + def send(self, event: ConnectionClosed) -> None: + ... + + @overload + def send( + self, event: Union[Request, InformationalResponse, Response, Data, EndOfMessage] + ) -> bytes: + ... + + @overload + def send(self, event: Event) -> Optional[bytes]: + ... + + def send(self, event: Event) -> Optional[bytes]: + """Convert a high-level event into bytes that can be sent to the peer, + while updating our internal state machine. + + Args: + event: The :ref:`event ` to send. + + Returns: + If ``type(event) is ConnectionClosed``, then returns + ``None``. Otherwise, returns a :term:`bytes-like object`. + + Raises: + LocalProtocolError: + Sending this event at this time would violate our + understanding of the HTTP/1.1 protocol. + + If this method raises any exception then it also sets + :attr:`Connection.our_state` to :data:`ERROR` -- see + :ref:`error-handling` for discussion. + + """ + data_list = self.send_with_data_passthrough(event) + if data_list is None: + return None + else: + return b"".join(data_list) + + def send_with_data_passthrough(self, event: Event) -> Optional[List[bytes]]: + """Identical to :meth:`send`, except that in situations where + :meth:`send` returns a single :term:`bytes-like object`, this instead + returns a list of them -- and when sending a :class:`Data` event, this + list is guaranteed to contain the exact object you passed in as + :attr:`Data.data`. See :ref:`sendfile` for discussion. + + """ + if self.our_state is ERROR: + raise LocalProtocolError("Can't send data when our state is ERROR") + try: + if type(event) is Response: + event = self._clean_up_response_headers_for_sending(event) + # We want to call _process_event before calling the writer, + # because if someone tries to do something invalid then this will + # give a sensible error message, while our writers all just assume + # they will only receive valid events. But, _process_event might + # change self._writer. So we have to do a little dance: + writer = self._writer + self._process_event(self.our_role, event) + if type(event) is ConnectionClosed: + return None + else: + # In any situation where writer is None, process_event should + # have raised ProtocolError + assert writer is not None + data_list: List[bytes] = [] + writer(event, data_list.append) + return data_list + except: + self._process_error(self.our_role) + raise + + def send_failed(self) -> None: + """Notify the state machine that we failed to send the data it gave + us. + + This causes :attr:`Connection.our_state` to immediately become + :data:`ERROR` -- see :ref:`error-handling` for discussion. + + """ + self._process_error(self.our_role) + + # When sending a Response, we take responsibility for a few things: + # + # - Sometimes you MUST set Connection: close. We take care of those + # times. (You can also set it yourself if you want, and if you do then + # we'll respect that and close the connection at the right time. But you + # don't have to worry about that unless you want to.) + # + # - The user has to set Content-Length if they want it. Otherwise, for + # responses that have bodies (e.g. not HEAD), then we will automatically + # select the right mechanism for streaming a body of unknown length, + # which depends on depending on the peer's HTTP version. + # + # This function's *only* responsibility is making sure headers are set up + # right -- everything downstream just looks at the headers. There are no + # side channels. + def _clean_up_response_headers_for_sending(self, response: Response) -> Response: + assert type(response) is Response + + headers = response.headers + need_close = False + + # HEAD requests need some special handling: they always act like they + # have Content-Length: 0, and that's how _body_framing treats + # them. But their headers are supposed to match what we would send if + # the request was a GET. (Technically there is one deviation allowed: + # we're allowed to leave out the framing headers -- see + # https://tools.ietf.org/html/rfc7231#section-4.3.2 . But it's just as + # easy to get them right.) + method_for_choosing_headers = cast(bytes, self._request_method) + if method_for_choosing_headers == b"HEAD": + method_for_choosing_headers = b"GET" + framing_type, _ = _body_framing(method_for_choosing_headers, response) + if framing_type in ("chunked", "http/1.0"): + # This response has a body of unknown length. + # If our peer is HTTP/1.1, we use Transfer-Encoding: chunked + # If our peer is HTTP/1.0, we use no framing headers, and close the + # connection afterwards. + # + # Make sure to clear Content-Length (in principle user could have + # set both and then we ignored Content-Length b/c + # Transfer-Encoding overwrote it -- this would be naughty of them, + # but the HTTP spec says that if our peer does this then we have + # to fix it instead of erroring out, so we'll accord the user the + # same respect). + headers = set_comma_header(headers, b"content-length", []) + if self.their_http_version is None or self.their_http_version < b"1.1": + # Either we never got a valid request and are sending back an + # error (their_http_version is None), so we assume the worst; + # or else we did get a valid HTTP/1.0 request, so we know that + # they don't understand chunked encoding. + headers = set_comma_header(headers, b"transfer-encoding", []) + # This is actually redundant ATM, since currently we + # unconditionally disable keep-alive when talking to HTTP/1.0 + # peers. But let's be defensive just in case we add + # Connection: keep-alive support later: + if self._request_method != b"HEAD": + need_close = True + else: + headers = set_comma_header(headers, b"transfer-encoding", [b"chunked"]) + + if not self._cstate.keep_alive or need_close: + # Make sure Connection: close is set + connection = set(get_comma_header(headers, b"connection")) + connection.discard(b"keep-alive") + connection.add(b"close") + headers = set_comma_header(headers, b"connection", sorted(connection)) + + return Response( + headers=headers, + status_code=response.status_code, + http_version=response.http_version, + reason=response.reason, + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/h11/_events.py b/data/miniconda3/lib/python3.13/site-packages/h11/_events.py new file mode 100644 index 0000000000000000000000000000000000000000..ca1c3adbde2c4e7710482a18e3471f91f1da610e --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/h11/_events.py @@ -0,0 +1,369 @@ +# High level events that make up HTTP/1.1 conversations. Loosely inspired by +# the corresponding events in hyper-h2: +# +# http://python-hyper.org/h2/en/stable/api.html#events +# +# Don't subclass these. Stuff will break. + +import re +from abc import ABC +from dataclasses import dataclass +from typing import List, Tuple, Union + +from ._abnf import method, request_target +from ._headers import Headers, normalize_and_validate +from ._util import bytesify, LocalProtocolError, validate + +# Everything in __all__ gets re-exported as part of the h11 public API. +__all__ = [ + "Event", + "Request", + "InformationalResponse", + "Response", + "Data", + "EndOfMessage", + "ConnectionClosed", +] + +method_re = re.compile(method.encode("ascii")) +request_target_re = re.compile(request_target.encode("ascii")) + + +class Event(ABC): + """ + Base class for h11 events. + """ + + __slots__ = () + + +@dataclass(init=False, frozen=True) +class Request(Event): + """The beginning of an HTTP request. + + Fields: + + .. attribute:: method + + An HTTP method, e.g. ``b"GET"`` or ``b"POST"``. Always a byte + string. :term:`Bytes-like objects ` and native + strings containing only ascii characters will be automatically + converted to byte strings. + + .. attribute:: target + + The target of an HTTP request, e.g. ``b"/index.html"``, or one of the + more exotic formats described in `RFC 7320, section 5.3 + `_. Always a byte + string. :term:`Bytes-like objects ` and native + strings containing only ascii characters will be automatically + converted to byte strings. + + .. attribute:: headers + + Request headers, represented as a list of (name, value) pairs. See + :ref:`the header normalization rules ` for details. + + .. attribute:: http_version + + The HTTP protocol version, represented as a byte string like + ``b"1.1"``. See :ref:`the HTTP version normalization rules + ` for details. + + """ + + __slots__ = ("method", "headers", "target", "http_version") + + method: bytes + headers: Headers + target: bytes + http_version: bytes + + def __init__( + self, + *, + method: Union[bytes, str], + headers: Union[Headers, List[Tuple[bytes, bytes]], List[Tuple[str, str]]], + target: Union[bytes, str], + http_version: Union[bytes, str] = b"1.1", + _parsed: bool = False, + ) -> None: + super().__init__() + if isinstance(headers, Headers): + object.__setattr__(self, "headers", headers) + else: + object.__setattr__( + self, "headers", normalize_and_validate(headers, _parsed=_parsed) + ) + if not _parsed: + object.__setattr__(self, "method", bytesify(method)) + object.__setattr__(self, "target", bytesify(target)) + object.__setattr__(self, "http_version", bytesify(http_version)) + else: + object.__setattr__(self, "method", method) + object.__setattr__(self, "target", target) + object.__setattr__(self, "http_version", http_version) + + # "A server MUST respond with a 400 (Bad Request) status code to any + # HTTP/1.1 request message that lacks a Host header field and to any + # request message that contains more than one Host header field or a + # Host header field with an invalid field-value." + # -- https://tools.ietf.org/html/rfc7230#section-5.4 + host_count = 0 + for name, value in self.headers: + if name == b"host": + host_count += 1 + if self.http_version == b"1.1" and host_count == 0: + raise LocalProtocolError("Missing mandatory Host: header") + if host_count > 1: + raise LocalProtocolError("Found multiple Host: headers") + + validate(method_re, self.method, "Illegal method characters") + validate(request_target_re, self.target, "Illegal target characters") + + # This is an unhashable type. + __hash__ = None # type: ignore + + +@dataclass(init=False, frozen=True) +class _ResponseBase(Event): + __slots__ = ("headers", "http_version", "reason", "status_code") + + headers: Headers + http_version: bytes + reason: bytes + status_code: int + + def __init__( + self, + *, + headers: Union[Headers, List[Tuple[bytes, bytes]], List[Tuple[str, str]]], + status_code: int, + http_version: Union[bytes, str] = b"1.1", + reason: Union[bytes, str] = b"", + _parsed: bool = False, + ) -> None: + super().__init__() + if isinstance(headers, Headers): + object.__setattr__(self, "headers", headers) + else: + object.__setattr__( + self, "headers", normalize_and_validate(headers, _parsed=_parsed) + ) + if not _parsed: + object.__setattr__(self, "reason", bytesify(reason)) + object.__setattr__(self, "http_version", bytesify(http_version)) + if not isinstance(status_code, int): + raise LocalProtocolError("status code must be integer") + # Because IntEnum objects are instances of int, but aren't + # duck-compatible (sigh), see gh-72. + object.__setattr__(self, "status_code", int(status_code)) + else: + object.__setattr__(self, "reason", reason) + object.__setattr__(self, "http_version", http_version) + object.__setattr__(self, "status_code", status_code) + + self.__post_init__() + + def __post_init__(self) -> None: + pass + + # This is an unhashable type. + __hash__ = None # type: ignore + + +@dataclass(init=False, frozen=True) +class InformationalResponse(_ResponseBase): + """An HTTP informational response. + + Fields: + + .. attribute:: status_code + + The status code of this response, as an integer. For an + :class:`InformationalResponse`, this is always in the range [100, + 200). + + .. attribute:: headers + + Request headers, represented as a list of (name, value) pairs. See + :ref:`the header normalization rules ` for + details. + + .. attribute:: http_version + + The HTTP protocol version, represented as a byte string like + ``b"1.1"``. See :ref:`the HTTP version normalization rules + ` for details. + + .. attribute:: reason + + The reason phrase of this response, as a byte string. For example: + ``b"OK"``, or ``b"Not Found"``. + + """ + + def __post_init__(self) -> None: + if not (100 <= self.status_code < 200): + raise LocalProtocolError( + "InformationalResponse status_code should be in range " + "[100, 200), not {}".format(self.status_code) + ) + + # This is an unhashable type. + __hash__ = None # type: ignore + + +@dataclass(init=False, frozen=True) +class Response(_ResponseBase): + """The beginning of an HTTP response. + + Fields: + + .. attribute:: status_code + + The status code of this response, as an integer. For an + :class:`Response`, this is always in the range [200, + 1000). + + .. attribute:: headers + + Request headers, represented as a list of (name, value) pairs. See + :ref:`the header normalization rules ` for details. + + .. attribute:: http_version + + The HTTP protocol version, represented as a byte string like + ``b"1.1"``. See :ref:`the HTTP version normalization rules + ` for details. + + .. attribute:: reason + + The reason phrase of this response, as a byte string. For example: + ``b"OK"``, or ``b"Not Found"``. + + """ + + def __post_init__(self) -> None: + if not (200 <= self.status_code < 1000): + raise LocalProtocolError( + "Response status_code should be in range [200, 1000), not {}".format( + self.status_code + ) + ) + + # This is an unhashable type. + __hash__ = None # type: ignore + + +@dataclass(init=False, frozen=True) +class Data(Event): + """Part of an HTTP message body. + + Fields: + + .. attribute:: data + + A :term:`bytes-like object` containing part of a message body. Or, if + using the ``combine=False`` argument to :meth:`Connection.send`, then + any object that your socket writing code knows what to do with, and for + which calling :func:`len` returns the number of bytes that will be + written -- see :ref:`sendfile` for details. + + .. attribute:: chunk_start + + A marker that indicates whether this data object is from the start of a + chunked transfer encoding chunk. This field is ignored when when a Data + event is provided to :meth:`Connection.send`: it is only valid on + events emitted from :meth:`Connection.next_event`. You probably + shouldn't use this attribute at all; see + :ref:`chunk-delimiters-are-bad` for details. + + .. attribute:: chunk_end + + A marker that indicates whether this data object is the last for a + given chunked transfer encoding chunk. This field is ignored when when + a Data event is provided to :meth:`Connection.send`: it is only valid + on events emitted from :meth:`Connection.next_event`. You probably + shouldn't use this attribute at all; see + :ref:`chunk-delimiters-are-bad` for details. + + """ + + __slots__ = ("data", "chunk_start", "chunk_end") + + data: bytes + chunk_start: bool + chunk_end: bool + + def __init__( + self, data: bytes, chunk_start: bool = False, chunk_end: bool = False + ) -> None: + object.__setattr__(self, "data", data) + object.__setattr__(self, "chunk_start", chunk_start) + object.__setattr__(self, "chunk_end", chunk_end) + + # This is an unhashable type. + __hash__ = None # type: ignore + + +# XX FIXME: "A recipient MUST ignore (or consider as an error) any fields that +# are forbidden to be sent in a trailer, since processing them as if they were +# present in the header section might bypass external security filters." +# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#chunked.trailer.part +# Unfortunately, the list of forbidden fields is long and vague :-/ +@dataclass(init=False, frozen=True) +class EndOfMessage(Event): + """The end of an HTTP message. + + Fields: + + .. attribute:: headers + + Default value: ``[]`` + + Any trailing headers attached to this message, represented as a list of + (name, value) pairs. See :ref:`the header normalization rules + ` for details. + + Must be empty unless ``Transfer-Encoding: chunked`` is in use. + + """ + + __slots__ = ("headers",) + + headers: Headers + + def __init__( + self, + *, + headers: Union[ + Headers, List[Tuple[bytes, bytes]], List[Tuple[str, str]], None + ] = None, + _parsed: bool = False, + ) -> None: + super().__init__() + if headers is None: + headers = Headers([]) + elif not isinstance(headers, Headers): + headers = normalize_and_validate(headers, _parsed=_parsed) + + object.__setattr__(self, "headers", headers) + + # This is an unhashable type. + __hash__ = None # type: ignore + + +@dataclass(frozen=True) +class ConnectionClosed(Event): + """This event indicates that the sender has closed their outgoing + connection. + + Note that this does not necessarily mean that they can't *receive* further + data, because TCP connections are composed to two one-way channels which + can be closed independently. See :ref:`closing` for details. + + No fields. + """ + + pass diff --git a/data/miniconda3/lib/python3.13/site-packages/h11/_headers.py b/data/miniconda3/lib/python3.13/site-packages/h11/_headers.py new file mode 100644 index 0000000000000000000000000000000000000000..31da3e2b23b55a624b36f105e62a6902e63286aa --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/h11/_headers.py @@ -0,0 +1,282 @@ +import re +from typing import AnyStr, cast, List, overload, Sequence, Tuple, TYPE_CHECKING, Union + +from ._abnf import field_name, field_value +from ._util import bytesify, LocalProtocolError, validate + +if TYPE_CHECKING: + from ._events import Request + +try: + from typing import Literal +except ImportError: + from typing_extensions import Literal # type: ignore + +CONTENT_LENGTH_MAX_DIGITS = 20 # allow up to 1 billion TB - 1 + + +# Facts +# ----- +# +# Headers are: +# keys: case-insensitive ascii +# values: mixture of ascii and raw bytes +# +# "Historically, HTTP has allowed field content with text in the ISO-8859-1 +# charset [ISO-8859-1], supporting other charsets only through use of +# [RFC2047] encoding. In practice, most HTTP header field values use only a +# subset of the US-ASCII charset [USASCII]. Newly defined header fields SHOULD +# limit their field values to US-ASCII octets. A recipient SHOULD treat other +# octets in field content (obs-text) as opaque data." +# And it deprecates all non-ascii values +# +# Leading/trailing whitespace in header names is forbidden +# +# Values get leading/trailing whitespace stripped +# +# Content-Disposition actually needs to contain unicode semantically; to +# accomplish this it has a terrifically weird way of encoding the filename +# itself as ascii (and even this still has lots of cross-browser +# incompatibilities) +# +# Order is important: +# "a proxy MUST NOT change the order of these field values when forwarding a +# message" +# (and there are several headers where the order indicates a preference) +# +# Multiple occurences of the same header: +# "A sender MUST NOT generate multiple header fields with the same field name +# in a message unless either the entire field value for that header field is +# defined as a comma-separated list [or the header is Set-Cookie which gets a +# special exception]" - RFC 7230. (cookies are in RFC 6265) +# +# So every header aside from Set-Cookie can be merged by b", ".join if it +# occurs repeatedly. But, of course, they can't necessarily be split by +# .split(b","), because quoting. +# +# Given all this mess (case insensitive, duplicates allowed, order is +# important, ...), there doesn't appear to be any standard way to handle +# headers in Python -- they're almost like dicts, but... actually just +# aren't. For now we punt and just use a super simple representation: headers +# are a list of pairs +# +# [(name1, value1), (name2, value2), ...] +# +# where all entries are bytestrings, names are lowercase and have no +# leading/trailing whitespace, and values are bytestrings with no +# leading/trailing whitespace. Searching and updating are done via naive O(n) +# methods. +# +# Maybe a dict-of-lists would be better? + +_content_length_re = re.compile(rb"[0-9]+") +_field_name_re = re.compile(field_name.encode("ascii")) +_field_value_re = re.compile(field_value.encode("ascii")) + + +class Headers(Sequence[Tuple[bytes, bytes]]): + """ + A list-like interface that allows iterating over headers as byte-pairs + of (lowercased-name, value). + + Internally we actually store the representation as three-tuples, + including both the raw original casing, in order to preserve casing + over-the-wire, and the lowercased name, for case-insensitive comparisions. + + r = Request( + method="GET", + target="/", + headers=[("Host", "example.org"), ("Connection", "keep-alive")], + http_version="1.1", + ) + assert r.headers == [ + (b"host", b"example.org"), + (b"connection", b"keep-alive") + ] + assert r.headers.raw_items() == [ + (b"Host", b"example.org"), + (b"Connection", b"keep-alive") + ] + """ + + __slots__ = "_full_items" + + def __init__(self, full_items: List[Tuple[bytes, bytes, bytes]]) -> None: + self._full_items = full_items + + def __bool__(self) -> bool: + return bool(self._full_items) + + def __eq__(self, other: object) -> bool: + return list(self) == list(other) # type: ignore + + def __len__(self) -> int: + return len(self._full_items) + + def __repr__(self) -> str: + return "" % repr(list(self)) + + def __getitem__(self, idx: int) -> Tuple[bytes, bytes]: # type: ignore[override] + _, name, value = self._full_items[idx] + return (name, value) + + def raw_items(self) -> List[Tuple[bytes, bytes]]: + return [(raw_name, value) for raw_name, _, value in self._full_items] + + +HeaderTypes = Union[ + List[Tuple[bytes, bytes]], + List[Tuple[bytes, str]], + List[Tuple[str, bytes]], + List[Tuple[str, str]], +] + + +@overload +def normalize_and_validate(headers: Headers, _parsed: Literal[True]) -> Headers: + ... + + +@overload +def normalize_and_validate(headers: HeaderTypes, _parsed: Literal[False]) -> Headers: + ... + + +@overload +def normalize_and_validate( + headers: Union[Headers, HeaderTypes], _parsed: bool = False +) -> Headers: + ... + + +def normalize_and_validate( + headers: Union[Headers, HeaderTypes], _parsed: bool = False +) -> Headers: + new_headers = [] + seen_content_length = None + saw_transfer_encoding = False + for name, value in headers: + # For headers coming out of the parser, we can safely skip some steps, + # because it always returns bytes and has already run these regexes + # over the data: + if not _parsed: + name = bytesify(name) + value = bytesify(value) + validate(_field_name_re, name, "Illegal header name {!r}", name) + validate(_field_value_re, value, "Illegal header value {!r}", value) + assert isinstance(name, bytes) + assert isinstance(value, bytes) + + raw_name = name + name = name.lower() + if name == b"content-length": + lengths = {length.strip() for length in value.split(b",")} + if len(lengths) != 1: + raise LocalProtocolError("conflicting Content-Length headers") + value = lengths.pop() + validate(_content_length_re, value, "bad Content-Length") + if len(value) > CONTENT_LENGTH_MAX_DIGITS: + raise LocalProtocolError("bad Content-Length") + if seen_content_length is None: + seen_content_length = value + new_headers.append((raw_name, name, value)) + elif seen_content_length != value: + raise LocalProtocolError("conflicting Content-Length headers") + elif name == b"transfer-encoding": + # "A server that receives a request message with a transfer coding + # it does not understand SHOULD respond with 501 (Not + # Implemented)." + # https://tools.ietf.org/html/rfc7230#section-3.3.1 + if saw_transfer_encoding: + raise LocalProtocolError( + "multiple Transfer-Encoding headers", error_status_hint=501 + ) + # "All transfer-coding names are case-insensitive" + # -- https://tools.ietf.org/html/rfc7230#section-4 + value = value.lower() + if value != b"chunked": + raise LocalProtocolError( + "Only Transfer-Encoding: chunked is supported", + error_status_hint=501, + ) + saw_transfer_encoding = True + new_headers.append((raw_name, name, value)) + else: + new_headers.append((raw_name, name, value)) + return Headers(new_headers) + + +def get_comma_header(headers: Headers, name: bytes) -> List[bytes]: + # Should only be used for headers whose value is a list of + # comma-separated, case-insensitive values. + # + # The header name `name` is expected to be lower-case bytes. + # + # Connection: meets these criteria (including cast insensitivity). + # + # Content-Length: technically is just a single value (1*DIGIT), but the + # standard makes reference to implementations that do multiple values, and + # using this doesn't hurt. Ditto, case insensitivity doesn't things either + # way. + # + # Transfer-Encoding: is more complex (allows for quoted strings), so + # splitting on , is actually wrong. For example, this is legal: + # + # Transfer-Encoding: foo; options="1,2", chunked + # + # and should be parsed as + # + # foo; options="1,2" + # chunked + # + # but this naive function will parse it as + # + # foo; options="1 + # 2" + # chunked + # + # However, this is okay because the only thing we are going to do with + # any Transfer-Encoding is reject ones that aren't just "chunked", so + # both of these will be treated the same anyway. + # + # Expect: the only legal value is the literal string + # "100-continue". Splitting on commas is harmless. Case insensitive. + # + out: List[bytes] = [] + for _, found_name, found_raw_value in headers._full_items: + if found_name == name: + found_raw_value = found_raw_value.lower() + for found_split_value in found_raw_value.split(b","): + found_split_value = found_split_value.strip() + if found_split_value: + out.append(found_split_value) + return out + + +def set_comma_header(headers: Headers, name: bytes, new_values: List[bytes]) -> Headers: + # The header name `name` is expected to be lower-case bytes. + # + # Note that when we store the header we use title casing for the header + # names, in order to match the conventional HTTP header style. + # + # Simply calling `.title()` is a blunt approach, but it's correct + # here given the cases where we're using `set_comma_header`... + # + # Connection, Content-Length, Transfer-Encoding. + new_headers: List[Tuple[bytes, bytes]] = [] + for found_raw_name, found_name, found_raw_value in headers._full_items: + if found_name != name: + new_headers.append((found_raw_name, found_raw_value)) + for new_value in new_values: + new_headers.append((name.title(), new_value)) + return normalize_and_validate(new_headers) + + +def has_expect_100_continue(request: "Request") -> bool: + # https://tools.ietf.org/html/rfc7231#section-5.1.1 + # "A server that receives a 100-continue expectation in an HTTP/1.0 request + # MUST ignore that expectation." + if request.http_version < b"1.1": + return False + expect = get_comma_header(request.headers, b"expect") + return b"100-continue" in expect diff --git a/data/miniconda3/lib/python3.13/site-packages/h11/_readers.py b/data/miniconda3/lib/python3.13/site-packages/h11/_readers.py new file mode 100644 index 0000000000000000000000000000000000000000..576804cc282032526e0a932c9853d586a094bad0 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/h11/_readers.py @@ -0,0 +1,250 @@ +# Code to read HTTP data +# +# Strategy: each reader is a callable which takes a ReceiveBuffer object, and +# either: +# 1) consumes some of it and returns an Event +# 2) raises a LocalProtocolError (for consistency -- e.g. we call validate() +# and it might raise a LocalProtocolError, so simpler just to always use +# this) +# 3) returns None, meaning "I need more data" +# +# If they have a .read_eof attribute, then this will be called if an EOF is +# received -- but this is optional. Either way, the actual ConnectionClosed +# event will be generated afterwards. +# +# READERS is a dict describing how to pick a reader. It maps states to either: +# - a reader +# - or, for body readers, a dict of per-framing reader factories + +import re +from typing import Any, Callable, Dict, Iterable, NoReturn, Optional, Tuple, Type, Union + +from ._abnf import chunk_header, header_field, request_line, status_line +from ._events import Data, EndOfMessage, InformationalResponse, Request, Response +from ._receivebuffer import ReceiveBuffer +from ._state import ( + CLIENT, + CLOSED, + DONE, + IDLE, + MUST_CLOSE, + SEND_BODY, + SEND_RESPONSE, + SERVER, +) +from ._util import LocalProtocolError, RemoteProtocolError, Sentinel, validate + +__all__ = ["READERS"] + +header_field_re = re.compile(header_field.encode("ascii")) +obs_fold_re = re.compile(rb"[ \t]+") + + +def _obsolete_line_fold(lines: Iterable[bytes]) -> Iterable[bytes]: + it = iter(lines) + last: Optional[bytes] = None + for line in it: + match = obs_fold_re.match(line) + if match: + if last is None: + raise LocalProtocolError("continuation line at start of headers") + if not isinstance(last, bytearray): + # Cast to a mutable type, avoiding copy on append to ensure O(n) time + last = bytearray(last) + last += b" " + last += line[match.end() :] + else: + if last is not None: + yield last + last = line + if last is not None: + yield last + + +def _decode_header_lines( + lines: Iterable[bytes], +) -> Iterable[Tuple[bytes, bytes]]: + for line in _obsolete_line_fold(lines): + matches = validate(header_field_re, line, "illegal header line: {!r}", line) + yield (matches["field_name"], matches["field_value"]) + + +request_line_re = re.compile(request_line.encode("ascii")) + + +def maybe_read_from_IDLE_client(buf: ReceiveBuffer) -> Optional[Request]: + lines = buf.maybe_extract_lines() + if lines is None: + if buf.is_next_line_obviously_invalid_request_line(): + raise LocalProtocolError("illegal request line") + return None + if not lines: + raise LocalProtocolError("no request line received") + matches = validate( + request_line_re, lines[0], "illegal request line: {!r}", lines[0] + ) + return Request( + headers=list(_decode_header_lines(lines[1:])), _parsed=True, **matches + ) + + +status_line_re = re.compile(status_line.encode("ascii")) + + +def maybe_read_from_SEND_RESPONSE_server( + buf: ReceiveBuffer, +) -> Union[InformationalResponse, Response, None]: + lines = buf.maybe_extract_lines() + if lines is None: + if buf.is_next_line_obviously_invalid_request_line(): + raise LocalProtocolError("illegal request line") + return None + if not lines: + raise LocalProtocolError("no response line received") + matches = validate(status_line_re, lines[0], "illegal status line: {!r}", lines[0]) + http_version = ( + b"1.1" if matches["http_version"] is None else matches["http_version"] + ) + reason = b"" if matches["reason"] is None else matches["reason"] + status_code = int(matches["status_code"]) + class_: Union[Type[InformationalResponse], Type[Response]] = ( + InformationalResponse if status_code < 200 else Response + ) + return class_( + headers=list(_decode_header_lines(lines[1:])), + _parsed=True, + status_code=status_code, + reason=reason, + http_version=http_version, + ) + + +class ContentLengthReader: + def __init__(self, length: int) -> None: + self._length = length + self._remaining = length + + def __call__(self, buf: ReceiveBuffer) -> Union[Data, EndOfMessage, None]: + if self._remaining == 0: + return EndOfMessage() + data = buf.maybe_extract_at_most(self._remaining) + if data is None: + return None + self._remaining -= len(data) + return Data(data=data) + + def read_eof(self) -> NoReturn: + raise RemoteProtocolError( + "peer closed connection without sending complete message body " + "(received {} bytes, expected {})".format( + self._length - self._remaining, self._length + ) + ) + + +chunk_header_re = re.compile(chunk_header.encode("ascii")) + + +class ChunkedReader: + def __init__(self) -> None: + self._bytes_in_chunk = 0 + # After reading a chunk, we have to throw away the trailing \r\n. + # This tracks the bytes that we need to match and throw away. + self._bytes_to_discard = b"" + self._reading_trailer = False + + def __call__(self, buf: ReceiveBuffer) -> Union[Data, EndOfMessage, None]: + if self._reading_trailer: + lines = buf.maybe_extract_lines() + if lines is None: + return None + return EndOfMessage(headers=list(_decode_header_lines(lines))) + if self._bytes_to_discard: + data = buf.maybe_extract_at_most(len(self._bytes_to_discard)) + if data is None: + return None + if data != self._bytes_to_discard[: len(data)]: + raise LocalProtocolError( + f"malformed chunk footer: {data!r} (expected {self._bytes_to_discard!r})" + ) + self._bytes_to_discard = self._bytes_to_discard[len(data) :] + if self._bytes_to_discard: + return None + # else, fall through and read some more + assert self._bytes_to_discard == b"" + if self._bytes_in_chunk == 0: + # We need to refill our chunk count + chunk_header = buf.maybe_extract_next_line() + if chunk_header is None: + return None + matches = validate( + chunk_header_re, + chunk_header, + "illegal chunk header: {!r}", + chunk_header, + ) + # XX FIXME: we discard chunk extensions. Does anyone care? + self._bytes_in_chunk = int(matches["chunk_size"], base=16) + if self._bytes_in_chunk == 0: + self._reading_trailer = True + return self(buf) + chunk_start = True + else: + chunk_start = False + assert self._bytes_in_chunk > 0 + data = buf.maybe_extract_at_most(self._bytes_in_chunk) + if data is None: + return None + self._bytes_in_chunk -= len(data) + if self._bytes_in_chunk == 0: + self._bytes_to_discard = b"\r\n" + chunk_end = True + else: + chunk_end = False + return Data(data=data, chunk_start=chunk_start, chunk_end=chunk_end) + + def read_eof(self) -> NoReturn: + raise RemoteProtocolError( + "peer closed connection without sending complete message body " + "(incomplete chunked read)" + ) + + +class Http10Reader: + def __call__(self, buf: ReceiveBuffer) -> Optional[Data]: + data = buf.maybe_extract_at_most(999999999) + if data is None: + return None + return Data(data=data) + + def read_eof(self) -> EndOfMessage: + return EndOfMessage() + + +def expect_nothing(buf: ReceiveBuffer) -> None: + if buf: + raise LocalProtocolError("Got data when expecting EOF") + return None + + +ReadersType = Dict[ + Union[Type[Sentinel], Tuple[Type[Sentinel], Type[Sentinel]]], + Union[Callable[..., Any], Dict[str, Callable[..., Any]]], +] + +READERS: ReadersType = { + (CLIENT, IDLE): maybe_read_from_IDLE_client, + (SERVER, IDLE): maybe_read_from_SEND_RESPONSE_server, + (SERVER, SEND_RESPONSE): maybe_read_from_SEND_RESPONSE_server, + (CLIENT, DONE): expect_nothing, + (CLIENT, MUST_CLOSE): expect_nothing, + (CLIENT, CLOSED): expect_nothing, + (SERVER, DONE): expect_nothing, + (SERVER, MUST_CLOSE): expect_nothing, + (SERVER, CLOSED): expect_nothing, + SEND_BODY: { + "chunked": ChunkedReader, + "content-length": ContentLengthReader, + "http/1.0": Http10Reader, + }, +} diff --git a/data/miniconda3/lib/python3.13/site-packages/h11/_receivebuffer.py b/data/miniconda3/lib/python3.13/site-packages/h11/_receivebuffer.py new file mode 100644 index 0000000000000000000000000000000000000000..e5c4e08a56f5081e87103f38b4add6ce1b730204 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/h11/_receivebuffer.py @@ -0,0 +1,153 @@ +import re +import sys +from typing import List, Optional, Union + +__all__ = ["ReceiveBuffer"] + + +# Operations we want to support: +# - find next \r\n or \r\n\r\n (\n or \n\n are also acceptable), +# or wait until there is one +# - read at-most-N bytes +# Goals: +# - on average, do this fast +# - worst case, do this in O(n) where n is the number of bytes processed +# Plan: +# - store bytearray, offset, how far we've searched for a separator token +# - use the how-far-we've-searched data to avoid rescanning +# - while doing a stream of uninterrupted processing, advance offset instead +# of constantly copying +# WARNING: +# - I haven't benchmarked or profiled any of this yet. +# +# Note that starting in Python 3.4, deleting the initial n bytes from a +# bytearray is amortized O(n), thanks to some excellent work by Antoine +# Martin: +# +# https://bugs.python.org/issue19087 +# +# This means that if we only supported 3.4+, we could get rid of the code here +# involving self._start and self.compress, because it's doing exactly the same +# thing that bytearray now does internally. +# +# BUT unfortunately, we still support 2.7, and reading short segments out of a +# long buffer MUST be O(bytes read) to avoid DoS issues, so we can't actually +# delete this code. Yet: +# +# https://pythonclock.org/ +# +# (Two things to double-check first though: make sure PyPy also has the +# optimization, and benchmark to make sure it's a win, since we do have a +# slightly clever thing where we delay calling compress() until we've +# processed a whole event, which could in theory be slightly more efficient +# than the internal bytearray support.) +blank_line_regex = re.compile(b"\n\r?\n", re.MULTILINE) + + +class ReceiveBuffer: + def __init__(self) -> None: + self._data = bytearray() + self._next_line_search = 0 + self._multiple_lines_search = 0 + + def __iadd__(self, byteslike: Union[bytes, bytearray]) -> "ReceiveBuffer": + self._data += byteslike + return self + + def __bool__(self) -> bool: + return bool(len(self)) + + def __len__(self) -> int: + return len(self._data) + + # for @property unprocessed_data + def __bytes__(self) -> bytes: + return bytes(self._data) + + def _extract(self, count: int) -> bytearray: + # extracting an initial slice of the data buffer and return it + out = self._data[:count] + del self._data[:count] + + self._next_line_search = 0 + self._multiple_lines_search = 0 + + return out + + def maybe_extract_at_most(self, count: int) -> Optional[bytearray]: + """ + Extract a fixed number of bytes from the buffer. + """ + out = self._data[:count] + if not out: + return None + + return self._extract(count) + + def maybe_extract_next_line(self) -> Optional[bytearray]: + """ + Extract the first line, if it is completed in the buffer. + """ + # Only search in buffer space that we've not already looked at. + search_start_index = max(0, self._next_line_search - 1) + partial_idx = self._data.find(b"\r\n", search_start_index) + + if partial_idx == -1: + self._next_line_search = len(self._data) + return None + + # + 2 is to compensate len(b"\r\n") + idx = partial_idx + 2 + + return self._extract(idx) + + def maybe_extract_lines(self) -> Optional[List[bytearray]]: + """ + Extract everything up to the first blank line, and return a list of lines. + """ + # Handle the case where we have an immediate empty line. + if self._data[:1] == b"\n": + self._extract(1) + return [] + + if self._data[:2] == b"\r\n": + self._extract(2) + return [] + + # Only search in buffer space that we've not already looked at. + match = blank_line_regex.search(self._data, self._multiple_lines_search) + if match is None: + self._multiple_lines_search = max(0, len(self._data) - 2) + return None + + # Truncate the buffer and return it. + idx = match.span(0)[-1] + out = self._extract(idx) + lines = out.split(b"\n") + + for line in lines: + if line.endswith(b"\r"): + del line[-1] + + assert lines[-2] == lines[-1] == b"" + + del lines[-2:] + + return lines + + # In theory we should wait until `\r\n` before starting to validate + # incoming data. However it's interesting to detect (very) invalid data + # early given they might not even contain `\r\n` at all (hence only + # timeout will get rid of them). + # This is not a 100% effective detection but more of a cheap sanity check + # allowing for early abort in some useful cases. + # This is especially interesting when peer is messing up with HTTPS and + # sent us a TLS stream where we were expecting plain HTTP given all + # versions of TLS so far start handshake with a 0x16 message type code. + def is_next_line_obviously_invalid_request_line(self) -> bool: + try: + # HTTP header line must not contain non-printable characters + # and should not start with a space + return self._data[0] < 0x21 + except IndexError: + return False diff --git a/data/miniconda3/lib/python3.13/site-packages/h11/_state.py b/data/miniconda3/lib/python3.13/site-packages/h11/_state.py new file mode 100644 index 0000000000000000000000000000000000000000..3ad444b043e3f3d6c05c2d9d84d5119312bfaa34 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/h11/_state.py @@ -0,0 +1,365 @@ +################################################################ +# The core state machine +################################################################ +# +# Rule 1: everything that affects the state machine and state transitions must +# live here in this file. As much as possible goes into the table-based +# representation, but for the bits that don't quite fit, the actual code and +# state must nonetheless live here. +# +# Rule 2: this file does not know about what role we're playing; it only knows +# about HTTP request/response cycles in the abstract. This ensures that we +# don't cheat and apply different rules to local and remote parties. +# +# +# Theory of operation +# =================== +# +# Possibly the simplest way to think about this is that we actually have 5 +# different state machines here. Yes, 5. These are: +# +# 1) The client state, with its complicated automaton (see the docs) +# 2) The server state, with its complicated automaton (see the docs) +# 3) The keep-alive state, with possible states {True, False} +# 4) The SWITCH_CONNECT state, with possible states {False, True} +# 5) The SWITCH_UPGRADE state, with possible states {False, True} +# +# For (3)-(5), the first state listed is the initial state. +# +# (1)-(3) are stored explicitly in member variables. The last +# two are stored implicitly in the pending_switch_proposals set as: +# (state of 4) == (_SWITCH_CONNECT in pending_switch_proposals) +# (state of 5) == (_SWITCH_UPGRADE in pending_switch_proposals) +# +# And each of these machines has two different kinds of transitions: +# +# a) Event-triggered +# b) State-triggered +# +# Event triggered is the obvious thing that you'd think it is: some event +# happens, and if it's the right event at the right time then a transition +# happens. But there are somewhat complicated rules for which machines can +# "see" which events. (As a rule of thumb, if a machine "sees" an event, this +# means two things: the event can affect the machine, and if the machine is +# not in a state where it expects that event then it's an error.) These rules +# are: +# +# 1) The client machine sees all h11.events objects emitted by the client. +# +# 2) The server machine sees all h11.events objects emitted by the server. +# +# It also sees the client's Request event. +# +# And sometimes, server events are annotated with a _SWITCH_* event. For +# example, we can have a (Response, _SWITCH_CONNECT) event, which is +# different from a regular Response event. +# +# 3) The keep-alive machine sees the process_keep_alive_disabled() event +# (which is derived from Request/Response events), and this event +# transitions it from True -> False, or from False -> False. There's no way +# to transition back. +# +# 4&5) The _SWITCH_* machines transition from False->True when we get a +# Request that proposes the relevant type of switch (via +# process_client_switch_proposals), and they go from True->False when we +# get a Response that has no _SWITCH_* annotation. +# +# So that's event-triggered transitions. +# +# State-triggered transitions are less standard. What they do here is couple +# the machines together. The way this works is, when certain *joint* +# configurations of states are achieved, then we automatically transition to a +# new *joint* state. So, for example, if we're ever in a joint state with +# +# client: DONE +# keep-alive: False +# +# then the client state immediately transitions to: +# +# client: MUST_CLOSE +# +# This is fundamentally different from an event-based transition, because it +# doesn't matter how we arrived at the {client: DONE, keep-alive: False} state +# -- maybe the client transitioned SEND_BODY -> DONE, or keep-alive +# transitioned True -> False. Either way, once this precondition is satisfied, +# this transition is immediately triggered. +# +# What if two conflicting state-based transitions get enabled at the same +# time? In practice there's only one case where this arises (client DONE -> +# MIGHT_SWITCH_PROTOCOL versus DONE -> MUST_CLOSE), and we resolve it by +# explicitly prioritizing the DONE -> MIGHT_SWITCH_PROTOCOL transition. +# +# Implementation +# -------------- +# +# The event-triggered transitions for the server and client machines are all +# stored explicitly in a table. Ditto for the state-triggered transitions that +# involve just the server and client state. +# +# The transitions for the other machines, and the state-triggered transitions +# that involve the other machines, are written out as explicit Python code. +# +# It'd be nice if there were some cleaner way to do all this. This isn't +# *too* terrible, but I feel like it could probably be better. +# +# WARNING +# ------- +# +# The script that generates the state machine diagrams for the docs knows how +# to read out the EVENT_TRIGGERED_TRANSITIONS and STATE_TRIGGERED_TRANSITIONS +# tables. But it can't automatically read the transitions that are written +# directly in Python code. So if you touch those, you need to also update the +# script to keep it in sync! +from typing import cast, Dict, Optional, Set, Tuple, Type, Union + +from ._events import * +from ._util import LocalProtocolError, Sentinel + +# Everything in __all__ gets re-exported as part of the h11 public API. +__all__ = [ + "CLIENT", + "SERVER", + "IDLE", + "SEND_RESPONSE", + "SEND_BODY", + "DONE", + "MUST_CLOSE", + "CLOSED", + "MIGHT_SWITCH_PROTOCOL", + "SWITCHED_PROTOCOL", + "ERROR", +] + + +class CLIENT(Sentinel, metaclass=Sentinel): + pass + + +class SERVER(Sentinel, metaclass=Sentinel): + pass + + +# States +class IDLE(Sentinel, metaclass=Sentinel): + pass + + +class SEND_RESPONSE(Sentinel, metaclass=Sentinel): + pass + + +class SEND_BODY(Sentinel, metaclass=Sentinel): + pass + + +class DONE(Sentinel, metaclass=Sentinel): + pass + + +class MUST_CLOSE(Sentinel, metaclass=Sentinel): + pass + + +class CLOSED(Sentinel, metaclass=Sentinel): + pass + + +class ERROR(Sentinel, metaclass=Sentinel): + pass + + +# Switch types +class MIGHT_SWITCH_PROTOCOL(Sentinel, metaclass=Sentinel): + pass + + +class SWITCHED_PROTOCOL(Sentinel, metaclass=Sentinel): + pass + + +class _SWITCH_UPGRADE(Sentinel, metaclass=Sentinel): + pass + + +class _SWITCH_CONNECT(Sentinel, metaclass=Sentinel): + pass + + +EventTransitionType = Dict[ + Type[Sentinel], + Dict[ + Type[Sentinel], + Dict[Union[Type[Event], Tuple[Type[Event], Type[Sentinel]]], Type[Sentinel]], + ], +] + +EVENT_TRIGGERED_TRANSITIONS: EventTransitionType = { + CLIENT: { + IDLE: {Request: SEND_BODY, ConnectionClosed: CLOSED}, + SEND_BODY: {Data: SEND_BODY, EndOfMessage: DONE}, + DONE: {ConnectionClosed: CLOSED}, + MUST_CLOSE: {ConnectionClosed: CLOSED}, + CLOSED: {ConnectionClosed: CLOSED}, + MIGHT_SWITCH_PROTOCOL: {}, + SWITCHED_PROTOCOL: {}, + ERROR: {}, + }, + SERVER: { + IDLE: { + ConnectionClosed: CLOSED, + Response: SEND_BODY, + # Special case: server sees client Request events, in this form + (Request, CLIENT): SEND_RESPONSE, + }, + SEND_RESPONSE: { + InformationalResponse: SEND_RESPONSE, + Response: SEND_BODY, + (InformationalResponse, _SWITCH_UPGRADE): SWITCHED_PROTOCOL, + (Response, _SWITCH_CONNECT): SWITCHED_PROTOCOL, + }, + SEND_BODY: {Data: SEND_BODY, EndOfMessage: DONE}, + DONE: {ConnectionClosed: CLOSED}, + MUST_CLOSE: {ConnectionClosed: CLOSED}, + CLOSED: {ConnectionClosed: CLOSED}, + SWITCHED_PROTOCOL: {}, + ERROR: {}, + }, +} + +StateTransitionType = Dict[ + Tuple[Type[Sentinel], Type[Sentinel]], Dict[Type[Sentinel], Type[Sentinel]] +] + +# NB: there are also some special-case state-triggered transitions hard-coded +# into _fire_state_triggered_transitions below. +STATE_TRIGGERED_TRANSITIONS: StateTransitionType = { + # (Client state, Server state) -> new states + # Protocol negotiation + (MIGHT_SWITCH_PROTOCOL, SWITCHED_PROTOCOL): {CLIENT: SWITCHED_PROTOCOL}, + # Socket shutdown + (CLOSED, DONE): {SERVER: MUST_CLOSE}, + (CLOSED, IDLE): {SERVER: MUST_CLOSE}, + (ERROR, DONE): {SERVER: MUST_CLOSE}, + (DONE, CLOSED): {CLIENT: MUST_CLOSE}, + (IDLE, CLOSED): {CLIENT: MUST_CLOSE}, + (DONE, ERROR): {CLIENT: MUST_CLOSE}, +} + + +class ConnectionState: + def __init__(self) -> None: + # Extra bits of state that don't quite fit into the state model. + + # If this is False then it enables the automatic DONE -> MUST_CLOSE + # transition. Don't set this directly; call .keep_alive_disabled() + self.keep_alive = True + + # This is a subset of {UPGRADE, CONNECT}, containing the proposals + # made by the client for switching protocols. + self.pending_switch_proposals: Set[Type[Sentinel]] = set() + + self.states: Dict[Type[Sentinel], Type[Sentinel]] = {CLIENT: IDLE, SERVER: IDLE} + + def process_error(self, role: Type[Sentinel]) -> None: + self.states[role] = ERROR + self._fire_state_triggered_transitions() + + def process_keep_alive_disabled(self) -> None: + self.keep_alive = False + self._fire_state_triggered_transitions() + + def process_client_switch_proposal(self, switch_event: Type[Sentinel]) -> None: + self.pending_switch_proposals.add(switch_event) + self._fire_state_triggered_transitions() + + def process_event( + self, + role: Type[Sentinel], + event_type: Type[Event], + server_switch_event: Optional[Type[Sentinel]] = None, + ) -> None: + _event_type: Union[Type[Event], Tuple[Type[Event], Type[Sentinel]]] = event_type + if server_switch_event is not None: + assert role is SERVER + if server_switch_event not in self.pending_switch_proposals: + raise LocalProtocolError( + "Received server _SWITCH_UPGRADE event without a pending proposal" + ) + _event_type = (event_type, server_switch_event) + if server_switch_event is None and _event_type is Response: + self.pending_switch_proposals = set() + self._fire_event_triggered_transitions(role, _event_type) + # Special case: the server state does get to see Request + # events. + if _event_type is Request: + assert role is CLIENT + self._fire_event_triggered_transitions(SERVER, (Request, CLIENT)) + self._fire_state_triggered_transitions() + + def _fire_event_triggered_transitions( + self, + role: Type[Sentinel], + event_type: Union[Type[Event], Tuple[Type[Event], Type[Sentinel]]], + ) -> None: + state = self.states[role] + try: + new_state = EVENT_TRIGGERED_TRANSITIONS[role][state][event_type] + except KeyError: + event_type = cast(Type[Event], event_type) + raise LocalProtocolError( + "can't handle event type {} when role={} and state={}".format( + event_type.__name__, role, self.states[role] + ) + ) from None + self.states[role] = new_state + + def _fire_state_triggered_transitions(self) -> None: + # We apply these rules repeatedly until converging on a fixed point + while True: + start_states = dict(self.states) + + # It could happen that both these special-case transitions are + # enabled at the same time: + # + # DONE -> MIGHT_SWITCH_PROTOCOL + # DONE -> MUST_CLOSE + # + # For example, this will always be true of a HTTP/1.0 client + # requesting CONNECT. If this happens, the protocol switch takes + # priority. From there the client will either go to + # SWITCHED_PROTOCOL, in which case it's none of our business when + # they close the connection, or else the server will deny the + # request, in which case the client will go back to DONE and then + # from there to MUST_CLOSE. + if self.pending_switch_proposals: + if self.states[CLIENT] is DONE: + self.states[CLIENT] = MIGHT_SWITCH_PROTOCOL + + if not self.pending_switch_proposals: + if self.states[CLIENT] is MIGHT_SWITCH_PROTOCOL: + self.states[CLIENT] = DONE + + if not self.keep_alive: + for role in (CLIENT, SERVER): + if self.states[role] is DONE: + self.states[role] = MUST_CLOSE + + # Tabular state-triggered transitions + joint_state = (self.states[CLIENT], self.states[SERVER]) + changes = STATE_TRIGGERED_TRANSITIONS.get(joint_state, {}) + self.states.update(changes) + + if self.states == start_states: + # Fixed point reached + return + + def start_next_cycle(self) -> None: + if self.states != {CLIENT: DONE, SERVER: DONE}: + raise LocalProtocolError( + f"not in a reusable state. self.states={self.states}" + ) + # Can't reach DONE/DONE with any of these active, but still, let's be + # sure. + assert self.keep_alive + assert not self.pending_switch_proposals + self.states = {CLIENT: IDLE, SERVER: IDLE} diff --git a/data/miniconda3/lib/python3.13/site-packages/h11/_util.py b/data/miniconda3/lib/python3.13/site-packages/h11/_util.py new file mode 100644 index 0000000000000000000000000000000000000000..6718445290770e028ea2f1f662026c9a0b0991db --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/h11/_util.py @@ -0,0 +1,135 @@ +from typing import Any, Dict, NoReturn, Pattern, Tuple, Type, TypeVar, Union + +__all__ = [ + "ProtocolError", + "LocalProtocolError", + "RemoteProtocolError", + "validate", + "bytesify", +] + + +class ProtocolError(Exception): + """Exception indicating a violation of the HTTP/1.1 protocol. + + This as an abstract base class, with two concrete base classes: + :exc:`LocalProtocolError`, which indicates that you tried to do something + that HTTP/1.1 says is illegal, and :exc:`RemoteProtocolError`, which + indicates that the remote peer tried to do something that HTTP/1.1 says is + illegal. See :ref:`error-handling` for details. + + In addition to the normal :exc:`Exception` features, it has one attribute: + + .. attribute:: error_status_hint + + This gives a suggestion as to what status code a server might use if + this error occurred as part of a request. + + For a :exc:`RemoteProtocolError`, this is useful as a suggestion for + how you might want to respond to a misbehaving peer, if you're + implementing a server. + + For a :exc:`LocalProtocolError`, this can be taken as a suggestion for + how your peer might have responded to *you* if h11 had allowed you to + continue. + + The default is 400 Bad Request, a generic catch-all for protocol + violations. + + """ + + def __init__(self, msg: str, error_status_hint: int = 400) -> None: + if type(self) is ProtocolError: + raise TypeError("tried to directly instantiate ProtocolError") + Exception.__init__(self, msg) + self.error_status_hint = error_status_hint + + +# Strategy: there are a number of public APIs where a LocalProtocolError can +# be raised (send(), all the different event constructors, ...), and only one +# public API where RemoteProtocolError can be raised +# (receive_data()). Therefore we always raise LocalProtocolError internally, +# and then receive_data will translate this into a RemoteProtocolError. +# +# Internally: +# LocalProtocolError is the generic "ProtocolError". +# Externally: +# LocalProtocolError is for local errors and RemoteProtocolError is for +# remote errors. +class LocalProtocolError(ProtocolError): + def _reraise_as_remote_protocol_error(self) -> NoReturn: + # After catching a LocalProtocolError, use this method to re-raise it + # as a RemoteProtocolError. This method must be called from inside an + # except: block. + # + # An easy way to get an equivalent RemoteProtocolError is just to + # modify 'self' in place. + self.__class__ = RemoteProtocolError # type: ignore + # But the re-raising is somewhat non-trivial -- you might think that + # now that we've modified the in-flight exception object, that just + # doing 'raise' to re-raise it would be enough. But it turns out that + # this doesn't work, because Python tracks the exception type + # (exc_info[0]) separately from the exception object (exc_info[1]), + # and we only modified the latter. So we really do need to re-raise + # the new type explicitly. + # On py3, the traceback is part of the exception object, so our + # in-place modification preserved it and we can just re-raise: + raise self + + +class RemoteProtocolError(ProtocolError): + pass + + +def validate( + regex: Pattern[bytes], data: bytes, msg: str = "malformed data", *format_args: Any +) -> Dict[str, bytes]: + match = regex.fullmatch(data) + if not match: + if format_args: + msg = msg.format(*format_args) + raise LocalProtocolError(msg) + return match.groupdict() + + +# Sentinel values +# +# - Inherit identity-based comparison and hashing from object +# - Have a nice repr +# - Have a *bonus property*: type(sentinel) is sentinel +# +# The bonus property is useful if you want to take the return value from +# next_event() and do some sort of dispatch based on type(event). + +_T_Sentinel = TypeVar("_T_Sentinel", bound="Sentinel") + + +class Sentinel(type): + def __new__( + cls: Type[_T_Sentinel], + name: str, + bases: Tuple[type, ...], + namespace: Dict[str, Any], + **kwds: Any + ) -> _T_Sentinel: + assert bases == (Sentinel,) + v = super().__new__(cls, name, bases, namespace, **kwds) + v.__class__ = v # type: ignore + return v + + def __repr__(self) -> str: + return self.__name__ + + +# Used for methods, request targets, HTTP versions, header names, and header +# values. Accepts ascii-strings, or bytes/bytearray/memoryview/..., and always +# returns bytes. +def bytesify(s: Union[bytes, bytearray, memoryview, int, str]) -> bytes: + # Fast-path: + if type(s) is bytes: + return s + if isinstance(s, str): + s = s.encode("ascii") + if isinstance(s, int): + raise TypeError("expected bytes-like object, not int") + return bytes(s) diff --git a/data/miniconda3/lib/python3.13/site-packages/h11/_version.py b/data/miniconda3/lib/python3.13/site-packages/h11/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..76e7327b8617c9d12236f511414d5eb58e98a44b --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/h11/_version.py @@ -0,0 +1,16 @@ +# This file must be kept very simple, because it is consumed from several +# places -- it is imported by h11/__init__.py, execfile'd by setup.py, etc. + +# We use a simple scheme: +# 1.0.0 -> 1.0.0+dev -> 1.1.0 -> 1.1.0+dev +# where the +dev versions are never released into the wild, they're just what +# we stick into the VCS in between releases. +# +# This is compatible with PEP 440: +# http://legacy.python.org/dev/peps/pep-0440/ +# via the use of the "local suffix" "+dev", which is disallowed on index +# servers and causes 1.0.0+dev to sort after plain 1.0.0, which is what we +# want. (Contrast with the special suffix 1.0.0.dev, which sorts *before* +# 1.0.0.) + +__version__ = "0.16.0" diff --git a/data/miniconda3/lib/python3.13/site-packages/h11/_writers.py b/data/miniconda3/lib/python3.13/site-packages/h11/_writers.py new file mode 100644 index 0000000000000000000000000000000000000000..939cdb912a9debaea07fbf3a9ac04549c44d077c --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/h11/_writers.py @@ -0,0 +1,145 @@ +# Code to read HTTP data +# +# Strategy: each writer takes an event + a write-some-bytes function, which is +# calls. +# +# WRITERS is a dict describing how to pick a reader. It maps states to either: +# - a writer +# - or, for body writers, a dict of framin-dependent writer factories + +from typing import Any, Callable, Dict, List, Tuple, Type, Union + +from ._events import Data, EndOfMessage, Event, InformationalResponse, Request, Response +from ._headers import Headers +from ._state import CLIENT, IDLE, SEND_BODY, SEND_RESPONSE, SERVER +from ._util import LocalProtocolError, Sentinel + +__all__ = ["WRITERS"] + +Writer = Callable[[bytes], Any] + + +def write_headers(headers: Headers, write: Writer) -> None: + # "Since the Host field-value is critical information for handling a + # request, a user agent SHOULD generate Host as the first header field + # following the request-line." - RFC 7230 + raw_items = headers._full_items + for raw_name, name, value in raw_items: + if name == b"host": + write(b"%s: %s\r\n" % (raw_name, value)) + for raw_name, name, value in raw_items: + if name != b"host": + write(b"%s: %s\r\n" % (raw_name, value)) + write(b"\r\n") + + +def write_request(request: Request, write: Writer) -> None: + if request.http_version != b"1.1": + raise LocalProtocolError("I only send HTTP/1.1") + write(b"%s %s HTTP/1.1\r\n" % (request.method, request.target)) + write_headers(request.headers, write) + + +# Shared between InformationalResponse and Response +def write_any_response( + response: Union[InformationalResponse, Response], write: Writer +) -> None: + if response.http_version != b"1.1": + raise LocalProtocolError("I only send HTTP/1.1") + status_bytes = str(response.status_code).encode("ascii") + # We don't bother sending ascii status messages like "OK"; they're + # optional and ignored by the protocol. (But the space after the numeric + # status code is mandatory.) + # + # XX FIXME: could at least make an effort to pull out the status message + # from stdlib's http.HTTPStatus table. Or maybe just steal their enums + # (either by import or copy/paste). We already accept them as status codes + # since they're of type IntEnum < int. + write(b"HTTP/1.1 %s %s\r\n" % (status_bytes, response.reason)) + write_headers(response.headers, write) + + +class BodyWriter: + def __call__(self, event: Event, write: Writer) -> None: + if type(event) is Data: + self.send_data(event.data, write) + elif type(event) is EndOfMessage: + self.send_eom(event.headers, write) + else: # pragma: no cover + assert False + + def send_data(self, data: bytes, write: Writer) -> None: + pass + + def send_eom(self, headers: Headers, write: Writer) -> None: + pass + + +# +# These are all careful not to do anything to 'data' except call len(data) and +# write(data). This allows us to transparently pass-through funny objects, +# like placeholder objects referring to files on disk that will be sent via +# sendfile(2). +# +class ContentLengthWriter(BodyWriter): + def __init__(self, length: int) -> None: + self._length = length + + def send_data(self, data: bytes, write: Writer) -> None: + self._length -= len(data) + if self._length < 0: + raise LocalProtocolError("Too much data for declared Content-Length") + write(data) + + def send_eom(self, headers: Headers, write: Writer) -> None: + if self._length != 0: + raise LocalProtocolError("Too little data for declared Content-Length") + if headers: + raise LocalProtocolError("Content-Length and trailers don't mix") + + +class ChunkedWriter(BodyWriter): + def send_data(self, data: bytes, write: Writer) -> None: + # if we encoded 0-length data in the naive way, it would look like an + # end-of-message. + if not data: + return + write(b"%x\r\n" % len(data)) + write(data) + write(b"\r\n") + + def send_eom(self, headers: Headers, write: Writer) -> None: + write(b"0\r\n") + write_headers(headers, write) + + +class Http10Writer(BodyWriter): + def send_data(self, data: bytes, write: Writer) -> None: + write(data) + + def send_eom(self, headers: Headers, write: Writer) -> None: + if headers: + raise LocalProtocolError("can't send trailers to HTTP/1.0 client") + # no need to close the socket ourselves, that will be taken care of by + # Connection: close machinery + + +WritersType = Dict[ + Union[Tuple[Type[Sentinel], Type[Sentinel]], Type[Sentinel]], + Union[ + Dict[str, Type[BodyWriter]], + Callable[[Union[InformationalResponse, Response], Writer], None], + Callable[[Request, Writer], None], + ], +] + +WRITERS: WritersType = { + (CLIENT, IDLE): write_request, + (SERVER, IDLE): write_any_response, + (SERVER, SEND_RESPONSE): write_any_response, + SEND_BODY: { + "chunked": ChunkedWriter, + "content-length": ContentLengthWriter, + "http/1.0": Http10Writer, + }, +} diff --git a/data/miniconda3/lib/python3.13/site-packages/h11/py.typed b/data/miniconda3/lib/python3.13/site-packages/h11/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..f5642f79f21d872f010979dcf6f0c4a415acc19d --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/h11/py.typed @@ -0,0 +1 @@ +Marker diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/__init__.py b/data/miniconda3/lib/python3.13/site-packages/httpx/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e9addde071f81758baf350c4ab6bde2556340131 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/httpx/__init__.py @@ -0,0 +1,105 @@ +from .__version__ import __description__, __title__, __version__ +from ._api import * +from ._auth import * +from ._client import * +from ._config import * +from ._content import * +from ._exceptions import * +from ._models import * +from ._status_codes import * +from ._transports import * +from ._types import * +from ._urls import * + +try: + from ._main import main +except ImportError: # pragma: no cover + + def main() -> None: # type: ignore + import sys + + print( + "The httpx command line client could not run because the required " + "dependencies were not installed.\nMake sure you've installed " + "everything with: pip install 'httpx[cli]'" + ) + sys.exit(1) + + +__all__ = [ + "__description__", + "__title__", + "__version__", + "ASGITransport", + "AsyncBaseTransport", + "AsyncByteStream", + "AsyncClient", + "AsyncHTTPTransport", + "Auth", + "BaseTransport", + "BasicAuth", + "ByteStream", + "Client", + "CloseError", + "codes", + "ConnectError", + "ConnectTimeout", + "CookieConflict", + "Cookies", + "create_ssl_context", + "DecodingError", + "delete", + "DigestAuth", + "get", + "head", + "Headers", + "HTTPError", + "HTTPStatusError", + "HTTPTransport", + "InvalidURL", + "Limits", + "LocalProtocolError", + "main", + "MockTransport", + "NetRCAuth", + "NetworkError", + "options", + "patch", + "PoolTimeout", + "post", + "ProtocolError", + "Proxy", + "ProxyError", + "put", + "QueryParams", + "ReadError", + "ReadTimeout", + "RemoteProtocolError", + "request", + "Request", + "RequestError", + "RequestNotRead", + "Response", + "ResponseNotRead", + "stream", + "StreamClosed", + "StreamConsumed", + "StreamError", + "SyncByteStream", + "Timeout", + "TimeoutException", + "TooManyRedirects", + "TransportError", + "UnsupportedProtocol", + "URL", + "USE_CLIENT_DEFAULT", + "WriteError", + "WriteTimeout", + "WSGITransport", +] + + +__locals = locals() +for __name in __all__: + if not __name.startswith("__"): + setattr(__locals[__name], "__module__", "httpx") # noqa diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/__version__.py b/data/miniconda3/lib/python3.13/site-packages/httpx/__version__.py new file mode 100644 index 0000000000000000000000000000000000000000..801bfacf671017cfbebf1ac26ec385daa02ed260 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/httpx/__version__.py @@ -0,0 +1,3 @@ +__title__ = "httpx" +__description__ = "A next generation HTTP client, for Python 3." +__version__ = "0.28.1" diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/_api.py b/data/miniconda3/lib/python3.13/site-packages/httpx/_api.py new file mode 100644 index 0000000000000000000000000000000000000000..c3cda1ecda8629edbdca2e3bc04bc51dba5e1430 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/httpx/_api.py @@ -0,0 +1,438 @@ +from __future__ import annotations + +import typing +from contextlib import contextmanager + +from ._client import Client +from ._config import DEFAULT_TIMEOUT_CONFIG +from ._models import Response +from ._types import ( + AuthTypes, + CookieTypes, + HeaderTypes, + ProxyTypes, + QueryParamTypes, + RequestContent, + RequestData, + RequestFiles, + TimeoutTypes, +) +from ._urls import URL + +if typing.TYPE_CHECKING: + import ssl # pragma: no cover + + +__all__ = [ + "delete", + "get", + "head", + "options", + "patch", + "post", + "put", + "request", + "stream", +] + + +def request( + method: str, + url: URL | str, + *, + params: QueryParamTypes | None = None, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | None = None, + proxy: ProxyTypes | None = None, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + follow_redirects: bool = False, + verify: ssl.SSLContext | str | bool = True, + trust_env: bool = True, +) -> Response: + """ + Sends an HTTP request. + + **Parameters:** + + * **method** - HTTP method for the new `Request` object: `GET`, `OPTIONS`, + `HEAD`, `POST`, `PUT`, `PATCH`, or `DELETE`. + * **url** - URL for the new `Request` object. + * **params** - *(optional)* Query parameters to include in the URL, as a + string, dictionary, or sequence of two-tuples. + * **content** - *(optional)* Binary content to include in the body of the + request, as bytes or a byte iterator. + * **data** - *(optional)* Form data to include in the body of the request, + as a dictionary. + * **files** - *(optional)* A dictionary of upload files to include in the + body of the request. + * **json** - *(optional)* A JSON serializable object to include in the body + of the request. + * **headers** - *(optional)* Dictionary of HTTP headers to include in the + request. + * **cookies** - *(optional)* Dictionary of Cookie items to include in the + request. + * **auth** - *(optional)* An authentication class to use when sending the + request. + * **proxy** - *(optional)* A proxy URL where all the traffic should be routed. + * **timeout** - *(optional)* The timeout configuration to use when sending + the request. + * **follow_redirects** - *(optional)* Enables or disables HTTP redirects. + * **verify** - *(optional)* Either `True` to use an SSL context with the + default CA bundle, `False` to disable verification, or an instance of + `ssl.SSLContext` to use a custom context. + * **trust_env** - *(optional)* Enables or disables usage of environment + variables for configuration. + + **Returns:** `Response` + + Usage: + + ``` + >>> import httpx + >>> response = httpx.request('GET', 'https://httpbin.org/get') + >>> response + + ``` + """ + with Client( + cookies=cookies, + proxy=proxy, + verify=verify, + timeout=timeout, + trust_env=trust_env, + ) as client: + return client.request( + method=method, + url=url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + auth=auth, + follow_redirects=follow_redirects, + ) + + +@contextmanager +def stream( + method: str, + url: URL | str, + *, + params: QueryParamTypes | None = None, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | None = None, + proxy: ProxyTypes | None = None, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + follow_redirects: bool = False, + verify: ssl.SSLContext | str | bool = True, + trust_env: bool = True, +) -> typing.Iterator[Response]: + """ + Alternative to `httpx.request()` that streams the response body + instead of loading it into memory at once. + + **Parameters**: See `httpx.request`. + + See also: [Streaming Responses][0] + + [0]: /quickstart#streaming-responses + """ + with Client( + cookies=cookies, + proxy=proxy, + verify=verify, + timeout=timeout, + trust_env=trust_env, + ) as client: + with client.stream( + method=method, + url=url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + auth=auth, + follow_redirects=follow_redirects, + ) as response: + yield response + + +def get( + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | None = None, + proxy: ProxyTypes | None = None, + follow_redirects: bool = False, + verify: ssl.SSLContext | str | bool = True, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + trust_env: bool = True, +) -> Response: + """ + Sends a `GET` request. + + **Parameters**: See `httpx.request`. + + Note that the `data`, `files`, `json` and `content` parameters are not available + on this function, as `GET` requests should not include a request body. + """ + return request( + "GET", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + proxy=proxy, + follow_redirects=follow_redirects, + verify=verify, + timeout=timeout, + trust_env=trust_env, + ) + + +def options( + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | None = None, + proxy: ProxyTypes | None = None, + follow_redirects: bool = False, + verify: ssl.SSLContext | str | bool = True, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + trust_env: bool = True, +) -> Response: + """ + Sends an `OPTIONS` request. + + **Parameters**: See `httpx.request`. + + Note that the `data`, `files`, `json` and `content` parameters are not available + on this function, as `OPTIONS` requests should not include a request body. + """ + return request( + "OPTIONS", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + proxy=proxy, + follow_redirects=follow_redirects, + verify=verify, + timeout=timeout, + trust_env=trust_env, + ) + + +def head( + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | None = None, + proxy: ProxyTypes | None = None, + follow_redirects: bool = False, + verify: ssl.SSLContext | str | bool = True, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + trust_env: bool = True, +) -> Response: + """ + Sends a `HEAD` request. + + **Parameters**: See `httpx.request`. + + Note that the `data`, `files`, `json` and `content` parameters are not available + on this function, as `HEAD` requests should not include a request body. + """ + return request( + "HEAD", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + proxy=proxy, + follow_redirects=follow_redirects, + verify=verify, + timeout=timeout, + trust_env=trust_env, + ) + + +def post( + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | None = None, + proxy: ProxyTypes | None = None, + follow_redirects: bool = False, + verify: ssl.SSLContext | str | bool = True, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + trust_env: bool = True, +) -> Response: + """ + Sends a `POST` request. + + **Parameters**: See `httpx.request`. + """ + return request( + "POST", + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + proxy=proxy, + follow_redirects=follow_redirects, + verify=verify, + timeout=timeout, + trust_env=trust_env, + ) + + +def put( + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | None = None, + proxy: ProxyTypes | None = None, + follow_redirects: bool = False, + verify: ssl.SSLContext | str | bool = True, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + trust_env: bool = True, +) -> Response: + """ + Sends a `PUT` request. + + **Parameters**: See `httpx.request`. + """ + return request( + "PUT", + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + proxy=proxy, + follow_redirects=follow_redirects, + verify=verify, + timeout=timeout, + trust_env=trust_env, + ) + + +def patch( + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | None = None, + proxy: ProxyTypes | None = None, + follow_redirects: bool = False, + verify: ssl.SSLContext | str | bool = True, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + trust_env: bool = True, +) -> Response: + """ + Sends a `PATCH` request. + + **Parameters**: See `httpx.request`. + """ + return request( + "PATCH", + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + proxy=proxy, + follow_redirects=follow_redirects, + verify=verify, + timeout=timeout, + trust_env=trust_env, + ) + + +def delete( + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | None = None, + proxy: ProxyTypes | None = None, + follow_redirects: bool = False, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + verify: ssl.SSLContext | str | bool = True, + trust_env: bool = True, +) -> Response: + """ + Sends a `DELETE` request. + + **Parameters**: See `httpx.request`. + + Note that the `data`, `files`, `json` and `content` parameters are not available + on this function, as `DELETE` requests should not include a request body. + """ + return request( + "DELETE", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + proxy=proxy, + follow_redirects=follow_redirects, + verify=verify, + timeout=timeout, + trust_env=trust_env, + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/_auth.py b/data/miniconda3/lib/python3.13/site-packages/httpx/_auth.py new file mode 100644 index 0000000000000000000000000000000000000000..b03971ab4b311d60790dc22ca24d9966426ec0a4 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/httpx/_auth.py @@ -0,0 +1,348 @@ +from __future__ import annotations + +import hashlib +import os +import re +import time +import typing +from base64 import b64encode +from urllib.request import parse_http_list + +from ._exceptions import ProtocolError +from ._models import Cookies, Request, Response +from ._utils import to_bytes, to_str, unquote + +if typing.TYPE_CHECKING: # pragma: no cover + from hashlib import _Hash + + +__all__ = ["Auth", "BasicAuth", "DigestAuth", "NetRCAuth"] + + +class Auth: + """ + Base class for all authentication schemes. + + To implement a custom authentication scheme, subclass `Auth` and override + the `.auth_flow()` method. + + If the authentication scheme does I/O such as disk access or network calls, or uses + synchronization primitives such as locks, you should override `.sync_auth_flow()` + and/or `.async_auth_flow()` instead of `.auth_flow()` to provide specialized + implementations that will be used by `Client` and `AsyncClient` respectively. + """ + + requires_request_body = False + requires_response_body = False + + def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]: + """ + Execute the authentication flow. + + To dispatch a request, `yield` it: + + ``` + yield request + ``` + + The client will `.send()` the response back into the flow generator. You can + access it like so: + + ``` + response = yield request + ``` + + A `return` (or reaching the end of the generator) will result in the + client returning the last response obtained from the server. + + You can dispatch as many requests as is necessary. + """ + yield request + + def sync_auth_flow( + self, request: Request + ) -> typing.Generator[Request, Response, None]: + """ + Execute the authentication flow synchronously. + + By default, this defers to `.auth_flow()`. You should override this method + when the authentication scheme does I/O and/or uses concurrency primitives. + """ + if self.requires_request_body: + request.read() + + flow = self.auth_flow(request) + request = next(flow) + + while True: + response = yield request + if self.requires_response_body: + response.read() + + try: + request = flow.send(response) + except StopIteration: + break + + async def async_auth_flow( + self, request: Request + ) -> typing.AsyncGenerator[Request, Response]: + """ + Execute the authentication flow asynchronously. + + By default, this defers to `.auth_flow()`. You should override this method + when the authentication scheme does I/O and/or uses concurrency primitives. + """ + if self.requires_request_body: + await request.aread() + + flow = self.auth_flow(request) + request = next(flow) + + while True: + response = yield request + if self.requires_response_body: + await response.aread() + + try: + request = flow.send(response) + except StopIteration: + break + + +class FunctionAuth(Auth): + """ + Allows the 'auth' argument to be passed as a simple callable function, + that takes the request, and returns a new, modified request. + """ + + def __init__(self, func: typing.Callable[[Request], Request]) -> None: + self._func = func + + def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]: + yield self._func(request) + + +class BasicAuth(Auth): + """ + Allows the 'auth' argument to be passed as a (username, password) pair, + and uses HTTP Basic authentication. + """ + + def __init__(self, username: str | bytes, password: str | bytes) -> None: + self._auth_header = self._build_auth_header(username, password) + + def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]: + request.headers["Authorization"] = self._auth_header + yield request + + def _build_auth_header(self, username: str | bytes, password: str | bytes) -> str: + userpass = b":".join((to_bytes(username), to_bytes(password))) + token = b64encode(userpass).decode() + return f"Basic {token}" + + +class NetRCAuth(Auth): + """ + Use a 'netrc' file to lookup basic auth credentials based on the url host. + """ + + def __init__(self, file: str | None = None) -> None: + # Lazily import 'netrc'. + # There's no need for us to load this module unless 'NetRCAuth' is being used. + import netrc + + self._netrc_info = netrc.netrc(file) + + def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]: + auth_info = self._netrc_info.authenticators(request.url.host) + if auth_info is None or not auth_info[2]: + # The netrc file did not have authentication credentials for this host. + yield request + else: + # Build a basic auth header with credentials from the netrc file. + request.headers["Authorization"] = self._build_auth_header( + username=auth_info[0], password=auth_info[2] + ) + yield request + + def _build_auth_header(self, username: str | bytes, password: str | bytes) -> str: + userpass = b":".join((to_bytes(username), to_bytes(password))) + token = b64encode(userpass).decode() + return f"Basic {token}" + + +class DigestAuth(Auth): + _ALGORITHM_TO_HASH_FUNCTION: dict[str, typing.Callable[[bytes], _Hash]] = { + "MD5": hashlib.md5, + "MD5-SESS": hashlib.md5, + "SHA": hashlib.sha1, + "SHA-SESS": hashlib.sha1, + "SHA-256": hashlib.sha256, + "SHA-256-SESS": hashlib.sha256, + "SHA-512": hashlib.sha512, + "SHA-512-SESS": hashlib.sha512, + } + + def __init__(self, username: str | bytes, password: str | bytes) -> None: + self._username = to_bytes(username) + self._password = to_bytes(password) + self._last_challenge: _DigestAuthChallenge | None = None + self._nonce_count = 1 + + def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]: + if self._last_challenge: + request.headers["Authorization"] = self._build_auth_header( + request, self._last_challenge + ) + + response = yield request + + if response.status_code != 401 or "www-authenticate" not in response.headers: + # If the response is not a 401 then we don't + # need to build an authenticated request. + return + + for auth_header in response.headers.get_list("www-authenticate"): + if auth_header.lower().startswith("digest "): + break + else: + # If the response does not include a 'WWW-Authenticate: Digest ...' + # header, then we don't need to build an authenticated request. + return + + self._last_challenge = self._parse_challenge(request, response, auth_header) + self._nonce_count = 1 + + request.headers["Authorization"] = self._build_auth_header( + request, self._last_challenge + ) + if response.cookies: + Cookies(response.cookies).set_cookie_header(request=request) + yield request + + def _parse_challenge( + self, request: Request, response: Response, auth_header: str + ) -> _DigestAuthChallenge: + """ + Returns a challenge from a Digest WWW-Authenticate header. + These take the form of: + `Digest realm="realm@host.com",qop="auth,auth-int",nonce="abc",opaque="xyz"` + """ + scheme, _, fields = auth_header.partition(" ") + + # This method should only ever have been called with a Digest auth header. + assert scheme.lower() == "digest" + + header_dict: dict[str, str] = {} + for field in parse_http_list(fields): + key, value = field.strip().split("=", 1) + header_dict[key] = unquote(value) + + try: + realm = header_dict["realm"].encode() + nonce = header_dict["nonce"].encode() + algorithm = header_dict.get("algorithm", "MD5") + opaque = header_dict["opaque"].encode() if "opaque" in header_dict else None + qop = header_dict["qop"].encode() if "qop" in header_dict else None + return _DigestAuthChallenge( + realm=realm, nonce=nonce, algorithm=algorithm, opaque=opaque, qop=qop + ) + except KeyError as exc: + message = "Malformed Digest WWW-Authenticate header" + raise ProtocolError(message, request=request) from exc + + def _build_auth_header( + self, request: Request, challenge: _DigestAuthChallenge + ) -> str: + hash_func = self._ALGORITHM_TO_HASH_FUNCTION[challenge.algorithm.upper()] + + def digest(data: bytes) -> bytes: + return hash_func(data).hexdigest().encode() + + A1 = b":".join((self._username, challenge.realm, self._password)) + + path = request.url.raw_path + A2 = b":".join((request.method.encode(), path)) + # TODO: implement auth-int + HA2 = digest(A2) + + nc_value = b"%08x" % self._nonce_count + cnonce = self._get_client_nonce(self._nonce_count, challenge.nonce) + self._nonce_count += 1 + + HA1 = digest(A1) + if challenge.algorithm.lower().endswith("-sess"): + HA1 = digest(b":".join((HA1, challenge.nonce, cnonce))) + + qop = self._resolve_qop(challenge.qop, request=request) + if qop is None: + # Following RFC 2069 + digest_data = [HA1, challenge.nonce, HA2] + else: + # Following RFC 2617/7616 + digest_data = [HA1, challenge.nonce, nc_value, cnonce, qop, HA2] + + format_args = { + "username": self._username, + "realm": challenge.realm, + "nonce": challenge.nonce, + "uri": path, + "response": digest(b":".join(digest_data)), + "algorithm": challenge.algorithm.encode(), + } + if challenge.opaque: + format_args["opaque"] = challenge.opaque + if qop: + format_args["qop"] = b"auth" + format_args["nc"] = nc_value + format_args["cnonce"] = cnonce + + return "Digest " + self._get_header_value(format_args) + + def _get_client_nonce(self, nonce_count: int, nonce: bytes) -> bytes: + s = str(nonce_count).encode() + s += nonce + s += time.ctime().encode() + s += os.urandom(8) + + return hashlib.sha1(s).hexdigest()[:16].encode() + + def _get_header_value(self, header_fields: dict[str, bytes]) -> str: + NON_QUOTED_FIELDS = ("algorithm", "qop", "nc") + QUOTED_TEMPLATE = '{}="{}"' + NON_QUOTED_TEMPLATE = "{}={}" + + header_value = "" + for i, (field, value) in enumerate(header_fields.items()): + if i > 0: + header_value += ", " + template = ( + QUOTED_TEMPLATE + if field not in NON_QUOTED_FIELDS + else NON_QUOTED_TEMPLATE + ) + header_value += template.format(field, to_str(value)) + + return header_value + + def _resolve_qop(self, qop: bytes | None, request: Request) -> bytes | None: + if qop is None: + return None + qops = re.split(b", ?", qop) + if b"auth" in qops: + return b"auth" + + if qops == [b"auth-int"]: + raise NotImplementedError("Digest auth-int support is not yet implemented") + + message = f'Unexpected qop value "{qop!r}" in digest auth' + raise ProtocolError(message, request=request) + + +class _DigestAuthChallenge(typing.NamedTuple): + realm: bytes + nonce: bytes + algorithm: str + opaque: bytes | None + qop: bytes | None diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/_client.py b/data/miniconda3/lib/python3.13/site-packages/httpx/_client.py new file mode 100644 index 0000000000000000000000000000000000000000..2249231f8c3b912c731ff160344d3672e2f11738 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/httpx/_client.py @@ -0,0 +1,2019 @@ +from __future__ import annotations + +import datetime +import enum +import logging +import time +import typing +import warnings +from contextlib import asynccontextmanager, contextmanager +from types import TracebackType + +from .__version__ import __version__ +from ._auth import Auth, BasicAuth, FunctionAuth +from ._config import ( + DEFAULT_LIMITS, + DEFAULT_MAX_REDIRECTS, + DEFAULT_TIMEOUT_CONFIG, + Limits, + Proxy, + Timeout, +) +from ._decoders import SUPPORTED_DECODERS +from ._exceptions import ( + InvalidURL, + RemoteProtocolError, + TooManyRedirects, + request_context, +) +from ._models import Cookies, Headers, Request, Response +from ._status_codes import codes +from ._transports.base import AsyncBaseTransport, BaseTransport +from ._transports.default import AsyncHTTPTransport, HTTPTransport +from ._types import ( + AsyncByteStream, + AuthTypes, + CertTypes, + CookieTypes, + HeaderTypes, + ProxyTypes, + QueryParamTypes, + RequestContent, + RequestData, + RequestExtensions, + RequestFiles, + SyncByteStream, + TimeoutTypes, +) +from ._urls import URL, QueryParams +from ._utils import URLPattern, get_environment_proxies + +if typing.TYPE_CHECKING: + import ssl # pragma: no cover + +__all__ = ["USE_CLIENT_DEFAULT", "AsyncClient", "Client"] + +# The type annotation for @classmethod and context managers here follows PEP 484 +# https://www.python.org/dev/peps/pep-0484/#annotating-instance-and-class-methods +T = typing.TypeVar("T", bound="Client") +U = typing.TypeVar("U", bound="AsyncClient") + + +def _is_https_redirect(url: URL, location: URL) -> bool: + """ + Return 'True' if 'location' is a HTTPS upgrade of 'url' + """ + if url.host != location.host: + return False + + return ( + url.scheme == "http" + and _port_or_default(url) == 80 + and location.scheme == "https" + and _port_or_default(location) == 443 + ) + + +def _port_or_default(url: URL) -> int | None: + if url.port is not None: + return url.port + return {"http": 80, "https": 443}.get(url.scheme) + + +def _same_origin(url: URL, other: URL) -> bool: + """ + Return 'True' if the given URLs share the same origin. + """ + return ( + url.scheme == other.scheme + and url.host == other.host + and _port_or_default(url) == _port_or_default(other) + ) + + +class UseClientDefault: + """ + For some parameters such as `auth=...` and `timeout=...` we need to be able + to indicate the default "unset" state, in a way that is distinctly different + to using `None`. + + The default "unset" state indicates that whatever default is set on the + client should be used. This is different to setting `None`, which + explicitly disables the parameter, possibly overriding a client default. + + For example we use `timeout=USE_CLIENT_DEFAULT` in the `request()` signature. + Omitting the `timeout` parameter will send a request using whatever default + timeout has been configured on the client. Including `timeout=None` will + ensure no timeout is used. + + Note that user code shouldn't need to use the `USE_CLIENT_DEFAULT` constant, + but it is used internally when a parameter is not included. + """ + + +USE_CLIENT_DEFAULT = UseClientDefault() + + +logger = logging.getLogger("httpx") + +USER_AGENT = f"python-httpx/{__version__}" +ACCEPT_ENCODING = ", ".join( + [key for key in SUPPORTED_DECODERS.keys() if key != "identity"] +) + + +class ClientState(enum.Enum): + # UNOPENED: + # The client has been instantiated, but has not been used to send a request, + # or been opened by entering the context of a `with` block. + UNOPENED = 1 + # OPENED: + # The client has either sent a request, or is within a `with` block. + OPENED = 2 + # CLOSED: + # The client has either exited the `with` block, or `close()` has + # been called explicitly. + CLOSED = 3 + + +class BoundSyncStream(SyncByteStream): + """ + A byte stream that is bound to a given response instance, and that + ensures the `response.elapsed` is set once the response is closed. + """ + + def __init__( + self, stream: SyncByteStream, response: Response, start: float + ) -> None: + self._stream = stream + self._response = response + self._start = start + + def __iter__(self) -> typing.Iterator[bytes]: + for chunk in self._stream: + yield chunk + + def close(self) -> None: + elapsed = time.perf_counter() - self._start + self._response.elapsed = datetime.timedelta(seconds=elapsed) + self._stream.close() + + +class BoundAsyncStream(AsyncByteStream): + """ + An async byte stream that is bound to a given response instance, and that + ensures the `response.elapsed` is set once the response is closed. + """ + + def __init__( + self, stream: AsyncByteStream, response: Response, start: float + ) -> None: + self._stream = stream + self._response = response + self._start = start + + async def __aiter__(self) -> typing.AsyncIterator[bytes]: + async for chunk in self._stream: + yield chunk + + async def aclose(self) -> None: + elapsed = time.perf_counter() - self._start + self._response.elapsed = datetime.timedelta(seconds=elapsed) + await self._stream.aclose() + + +EventHook = typing.Callable[..., typing.Any] + + +class BaseClient: + def __init__( + self, + *, + auth: AuthTypes | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + follow_redirects: bool = False, + max_redirects: int = DEFAULT_MAX_REDIRECTS, + event_hooks: None | (typing.Mapping[str, list[EventHook]]) = None, + base_url: URL | str = "", + trust_env: bool = True, + default_encoding: str | typing.Callable[[bytes], str] = "utf-8", + ) -> None: + event_hooks = {} if event_hooks is None else event_hooks + + self._base_url = self._enforce_trailing_slash(URL(base_url)) + + self._auth = self._build_auth(auth) + self._params = QueryParams(params) + self.headers = Headers(headers) + self._cookies = Cookies(cookies) + self._timeout = Timeout(timeout) + self.follow_redirects = follow_redirects + self.max_redirects = max_redirects + self._event_hooks = { + "request": list(event_hooks.get("request", [])), + "response": list(event_hooks.get("response", [])), + } + self._trust_env = trust_env + self._default_encoding = default_encoding + self._state = ClientState.UNOPENED + + @property + def is_closed(self) -> bool: + """ + Check if the client being closed + """ + return self._state == ClientState.CLOSED + + @property + def trust_env(self) -> bool: + return self._trust_env + + def _enforce_trailing_slash(self, url: URL) -> URL: + if url.raw_path.endswith(b"/"): + return url + return url.copy_with(raw_path=url.raw_path + b"/") + + def _get_proxy_map( + self, proxy: ProxyTypes | None, allow_env_proxies: bool + ) -> dict[str, Proxy | None]: + if proxy is None: + if allow_env_proxies: + return { + key: None if url is None else Proxy(url=url) + for key, url in get_environment_proxies().items() + } + return {} + else: + proxy = Proxy(url=proxy) if isinstance(proxy, (str, URL)) else proxy + return {"all://": proxy} + + @property + def timeout(self) -> Timeout: + return self._timeout + + @timeout.setter + def timeout(self, timeout: TimeoutTypes) -> None: + self._timeout = Timeout(timeout) + + @property + def event_hooks(self) -> dict[str, list[EventHook]]: + return self._event_hooks + + @event_hooks.setter + def event_hooks(self, event_hooks: dict[str, list[EventHook]]) -> None: + self._event_hooks = { + "request": list(event_hooks.get("request", [])), + "response": list(event_hooks.get("response", [])), + } + + @property + def auth(self) -> Auth | None: + """ + Authentication class used when none is passed at the request-level. + + See also [Authentication][0]. + + [0]: /quickstart/#authentication + """ + return self._auth + + @auth.setter + def auth(self, auth: AuthTypes) -> None: + self._auth = self._build_auth(auth) + + @property + def base_url(self) -> URL: + """ + Base URL to use when sending requests with relative URLs. + """ + return self._base_url + + @base_url.setter + def base_url(self, url: URL | str) -> None: + self._base_url = self._enforce_trailing_slash(URL(url)) + + @property + def headers(self) -> Headers: + """ + HTTP headers to include when sending requests. + """ + return self._headers + + @headers.setter + def headers(self, headers: HeaderTypes) -> None: + client_headers = Headers( + { + b"Accept": b"*/*", + b"Accept-Encoding": ACCEPT_ENCODING.encode("ascii"), + b"Connection": b"keep-alive", + b"User-Agent": USER_AGENT.encode("ascii"), + } + ) + client_headers.update(headers) + self._headers = client_headers + + @property + def cookies(self) -> Cookies: + """ + Cookie values to include when sending requests. + """ + return self._cookies + + @cookies.setter + def cookies(self, cookies: CookieTypes) -> None: + self._cookies = Cookies(cookies) + + @property + def params(self) -> QueryParams: + """ + Query parameters to include in the URL when sending requests. + """ + return self._params + + @params.setter + def params(self, params: QueryParamTypes) -> None: + self._params = QueryParams(params) + + def build_request( + self, + method: str, + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Request: + """ + Build and return a request instance. + + * The `params`, `headers` and `cookies` arguments + are merged with any values set on the client. + * The `url` argument is merged with any `base_url` set on the client. + + See also: [Request instances][0] + + [0]: /advanced/clients/#request-instances + """ + url = self._merge_url(url) + headers = self._merge_headers(headers) + cookies = self._merge_cookies(cookies) + params = self._merge_queryparams(params) + extensions = {} if extensions is None else extensions + if "timeout" not in extensions: + timeout = ( + self.timeout + if isinstance(timeout, UseClientDefault) + else Timeout(timeout) + ) + extensions = dict(**extensions, timeout=timeout.as_dict()) + return Request( + method, + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + extensions=extensions, + ) + + def _merge_url(self, url: URL | str) -> URL: + """ + Merge a URL argument together with any 'base_url' on the client, + to create the URL used for the outgoing request. + """ + merge_url = URL(url) + if merge_url.is_relative_url: + # To merge URLs we always append to the base URL. To get this + # behaviour correct we always ensure the base URL ends in a '/' + # separator, and strip any leading '/' from the merge URL. + # + # So, eg... + # + # >>> client = Client(base_url="https://www.example.com/subpath") + # >>> client.base_url + # URL('https://www.example.com/subpath/') + # >>> client.build_request("GET", "/path").url + # URL('https://www.example.com/subpath/path') + merge_raw_path = self.base_url.raw_path + merge_url.raw_path.lstrip(b"/") + return self.base_url.copy_with(raw_path=merge_raw_path) + return merge_url + + def _merge_cookies(self, cookies: CookieTypes | None = None) -> CookieTypes | None: + """ + Merge a cookies argument together with any cookies on the client, + to create the cookies used for the outgoing request. + """ + if cookies or self.cookies: + merged_cookies = Cookies(self.cookies) + merged_cookies.update(cookies) + return merged_cookies + return cookies + + def _merge_headers(self, headers: HeaderTypes | None = None) -> HeaderTypes | None: + """ + Merge a headers argument together with any headers on the client, + to create the headers used for the outgoing request. + """ + merged_headers = Headers(self.headers) + merged_headers.update(headers) + return merged_headers + + def _merge_queryparams( + self, params: QueryParamTypes | None = None + ) -> QueryParamTypes | None: + """ + Merge a queryparams argument together with any queryparams on the client, + to create the queryparams used for the outgoing request. + """ + if params or self.params: + merged_queryparams = QueryParams(self.params) + return merged_queryparams.merge(params) + return params + + def _build_auth(self, auth: AuthTypes | None) -> Auth | None: + if auth is None: + return None + elif isinstance(auth, tuple): + return BasicAuth(username=auth[0], password=auth[1]) + elif isinstance(auth, Auth): + return auth + elif callable(auth): + return FunctionAuth(func=auth) + else: + raise TypeError(f'Invalid "auth" argument: {auth!r}') + + def _build_request_auth( + self, + request: Request, + auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, + ) -> Auth: + auth = ( + self._auth if isinstance(auth, UseClientDefault) else self._build_auth(auth) + ) + + if auth is not None: + return auth + + username, password = request.url.username, request.url.password + if username or password: + return BasicAuth(username=username, password=password) + + return Auth() + + def _build_redirect_request(self, request: Request, response: Response) -> Request: + """ + Given a request and a redirect response, return a new request that + should be used to effect the redirect. + """ + method = self._redirect_method(request, response) + url = self._redirect_url(request, response) + headers = self._redirect_headers(request, url, method) + stream = self._redirect_stream(request, method) + cookies = Cookies(self.cookies) + return Request( + method=method, + url=url, + headers=headers, + cookies=cookies, + stream=stream, + extensions=request.extensions, + ) + + def _redirect_method(self, request: Request, response: Response) -> str: + """ + When being redirected we may want to change the method of the request + based on certain specs or browser behavior. + """ + method = request.method + + # https://tools.ietf.org/html/rfc7231#section-6.4.4 + if response.status_code == codes.SEE_OTHER and method != "HEAD": + method = "GET" + + # Do what the browsers do, despite standards... + # Turn 302s into GETs. + if response.status_code == codes.FOUND and method != "HEAD": + method = "GET" + + # If a POST is responded to with a 301, turn it into a GET. + # This bizarre behaviour is explained in 'requests' issue 1704. + if response.status_code == codes.MOVED_PERMANENTLY and method == "POST": + method = "GET" + + return method + + def _redirect_url(self, request: Request, response: Response) -> URL: + """ + Return the URL for the redirect to follow. + """ + location = response.headers["Location"] + + try: + url = URL(location) + except InvalidURL as exc: + raise RemoteProtocolError( + f"Invalid URL in location header: {exc}.", request=request + ) from None + + # Handle malformed 'Location' headers that are "absolute" form, have no host. + # See: https://github.com/encode/httpx/issues/771 + if url.scheme and not url.host: + url = url.copy_with(host=request.url.host) + + # Facilitate relative 'Location' headers, as allowed by RFC 7231. + # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource') + if url.is_relative_url: + url = request.url.join(url) + + # Attach previous fragment if needed (RFC 7231 7.1.2) + if request.url.fragment and not url.fragment: + url = url.copy_with(fragment=request.url.fragment) + + return url + + def _redirect_headers(self, request: Request, url: URL, method: str) -> Headers: + """ + Return the headers that should be used for the redirect request. + """ + headers = Headers(request.headers) + + if not _same_origin(url, request.url): + if not _is_https_redirect(request.url, url): + # Strip Authorization headers when responses are redirected + # away from the origin. (Except for direct HTTP to HTTPS redirects.) + headers.pop("Authorization", None) + + # Update the Host header. + headers["Host"] = url.netloc.decode("ascii") + + if method != request.method and method == "GET": + # If we've switch to a 'GET' request, then strip any headers which + # are only relevant to the request body. + headers.pop("Content-Length", None) + headers.pop("Transfer-Encoding", None) + + # We should use the client cookie store to determine any cookie header, + # rather than whatever was on the original outgoing request. + headers.pop("Cookie", None) + + return headers + + def _redirect_stream( + self, request: Request, method: str + ) -> SyncByteStream | AsyncByteStream | None: + """ + Return the body that should be used for the redirect request. + """ + if method != request.method and method == "GET": + return None + + return request.stream + + def _set_timeout(self, request: Request) -> None: + if "timeout" not in request.extensions: + timeout = ( + self.timeout + if isinstance(self.timeout, UseClientDefault) + else Timeout(self.timeout) + ) + request.extensions = dict(**request.extensions, timeout=timeout.as_dict()) + + +class Client(BaseClient): + """ + An HTTP client, with connection pooling, HTTP/2, redirects, cookie persistence, etc. + + It can be shared between threads. + + Usage: + + ```python + >>> client = httpx.Client() + >>> response = client.get('https://example.org') + ``` + + **Parameters:** + + * **auth** - *(optional)* An authentication class to use when sending + requests. + * **params** - *(optional)* Query parameters to include in request URLs, as + a string, dictionary, or sequence of two-tuples. + * **headers** - *(optional)* Dictionary of HTTP headers to include when + sending requests. + * **cookies** - *(optional)* Dictionary of Cookie items to include when + sending requests. + * **verify** - *(optional)* Either `True` to use an SSL context with the + default CA bundle, `False` to disable verification, or an instance of + `ssl.SSLContext` to use a custom context. + * **http2** - *(optional)* A boolean indicating if HTTP/2 support should be + enabled. Defaults to `False`. + * **proxy** - *(optional)* A proxy URL where all the traffic should be routed. + * **timeout** - *(optional)* The timeout configuration to use when sending + requests. + * **limits** - *(optional)* The limits configuration to use. + * **max_redirects** - *(optional)* The maximum number of redirect responses + that should be followed. + * **base_url** - *(optional)* A URL to use as the base when building + request URLs. + * **transport** - *(optional)* A transport class to use for sending requests + over the network. + * **trust_env** - *(optional)* Enables or disables usage of environment + variables for configuration. + * **default_encoding** - *(optional)* The default encoding to use for decoding + response text, if no charset information is included in a response Content-Type + header. Set to a callable for automatic character set detection. Default: "utf-8". + """ + + def __init__( + self, + *, + auth: AuthTypes | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + verify: ssl.SSLContext | str | bool = True, + cert: CertTypes | None = None, + trust_env: bool = True, + http1: bool = True, + http2: bool = False, + proxy: ProxyTypes | None = None, + mounts: None | (typing.Mapping[str, BaseTransport | None]) = None, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + follow_redirects: bool = False, + limits: Limits = DEFAULT_LIMITS, + max_redirects: int = DEFAULT_MAX_REDIRECTS, + event_hooks: None | (typing.Mapping[str, list[EventHook]]) = None, + base_url: URL | str = "", + transport: BaseTransport | None = None, + default_encoding: str | typing.Callable[[bytes], str] = "utf-8", + ) -> None: + super().__init__( + auth=auth, + params=params, + headers=headers, + cookies=cookies, + timeout=timeout, + follow_redirects=follow_redirects, + max_redirects=max_redirects, + event_hooks=event_hooks, + base_url=base_url, + trust_env=trust_env, + default_encoding=default_encoding, + ) + + if http2: + try: + import h2 # noqa + except ImportError: # pragma: no cover + raise ImportError( + "Using http2=True, but the 'h2' package is not installed. " + "Make sure to install httpx using `pip install httpx[http2]`." + ) from None + + allow_env_proxies = trust_env and transport is None + proxy_map = self._get_proxy_map(proxy, allow_env_proxies) + + self._transport = self._init_transport( + verify=verify, + cert=cert, + trust_env=trust_env, + http1=http1, + http2=http2, + limits=limits, + transport=transport, + ) + self._mounts: dict[URLPattern, BaseTransport | None] = { + URLPattern(key): None + if proxy is None + else self._init_proxy_transport( + proxy, + verify=verify, + cert=cert, + trust_env=trust_env, + http1=http1, + http2=http2, + limits=limits, + ) + for key, proxy in proxy_map.items() + } + if mounts is not None: + self._mounts.update( + {URLPattern(key): transport for key, transport in mounts.items()} + ) + + self._mounts = dict(sorted(self._mounts.items())) + + def _init_transport( + self, + verify: ssl.SSLContext | str | bool = True, + cert: CertTypes | None = None, + trust_env: bool = True, + http1: bool = True, + http2: bool = False, + limits: Limits = DEFAULT_LIMITS, + transport: BaseTransport | None = None, + ) -> BaseTransport: + if transport is not None: + return transport + + return HTTPTransport( + verify=verify, + cert=cert, + trust_env=trust_env, + http1=http1, + http2=http2, + limits=limits, + ) + + def _init_proxy_transport( + self, + proxy: Proxy, + verify: ssl.SSLContext | str | bool = True, + cert: CertTypes | None = None, + trust_env: bool = True, + http1: bool = True, + http2: bool = False, + limits: Limits = DEFAULT_LIMITS, + ) -> BaseTransport: + return HTTPTransport( + verify=verify, + cert=cert, + trust_env=trust_env, + http1=http1, + http2=http2, + limits=limits, + proxy=proxy, + ) + + def _transport_for_url(self, url: URL) -> BaseTransport: + """ + Returns the transport instance that should be used for a given URL. + This will either be the standard connection pool, or a proxy. + """ + for pattern, transport in self._mounts.items(): + if pattern.matches(url): + return self._transport if transport is None else transport + + return self._transport + + def request( + self, + method: str, + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Build and send a request. + + Equivalent to: + + ```python + request = client.build_request(...) + response = client.send(request, ...) + ``` + + See `Client.build_request()`, `Client.send()` and + [Merging of configuration][0] for how the various parameters + are merged with client-level configuration. + + [0]: /advanced/clients/#merging-of-configuration + """ + if cookies is not None: + message = ( + "Setting per-request cookies=<...> is being deprecated, because " + "the expected behaviour on cookie persistence is ambiguous. Set " + "cookies directly on the client instance instead." + ) + warnings.warn(message, DeprecationWarning, stacklevel=2) + + request = self.build_request( + method=method, + url=url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + timeout=timeout, + extensions=extensions, + ) + return self.send(request, auth=auth, follow_redirects=follow_redirects) + + @contextmanager + def stream( + self, + method: str, + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> typing.Iterator[Response]: + """ + Alternative to `httpx.request()` that streams the response body + instead of loading it into memory at once. + + **Parameters**: See `httpx.request`. + + See also: [Streaming Responses][0] + + [0]: /quickstart#streaming-responses + """ + request = self.build_request( + method=method, + url=url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + timeout=timeout, + extensions=extensions, + ) + response = self.send( + request=request, + auth=auth, + follow_redirects=follow_redirects, + stream=True, + ) + try: + yield response + finally: + response.close() + + def send( + self, + request: Request, + *, + stream: bool = False, + auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + ) -> Response: + """ + Send a request. + + The request is sent as-is, unmodified. + + Typically you'll want to build one with `Client.build_request()` + so that any client-level configuration is merged into the request, + but passing an explicit `httpx.Request()` is supported as well. + + See also: [Request instances][0] + + [0]: /advanced/clients/#request-instances + """ + if self._state == ClientState.CLOSED: + raise RuntimeError("Cannot send a request, as the client has been closed.") + + self._state = ClientState.OPENED + follow_redirects = ( + self.follow_redirects + if isinstance(follow_redirects, UseClientDefault) + else follow_redirects + ) + + self._set_timeout(request) + + auth = self._build_request_auth(request, auth) + + response = self._send_handling_auth( + request, + auth=auth, + follow_redirects=follow_redirects, + history=[], + ) + try: + if not stream: + response.read() + + return response + + except BaseException as exc: + response.close() + raise exc + + def _send_handling_auth( + self, + request: Request, + auth: Auth, + follow_redirects: bool, + history: list[Response], + ) -> Response: + auth_flow = auth.sync_auth_flow(request) + try: + request = next(auth_flow) + + while True: + response = self._send_handling_redirects( + request, + follow_redirects=follow_redirects, + history=history, + ) + try: + try: + next_request = auth_flow.send(response) + except StopIteration: + return response + + response.history = list(history) + response.read() + request = next_request + history.append(response) + + except BaseException as exc: + response.close() + raise exc + finally: + auth_flow.close() + + def _send_handling_redirects( + self, + request: Request, + follow_redirects: bool, + history: list[Response], + ) -> Response: + while True: + if len(history) > self.max_redirects: + raise TooManyRedirects( + "Exceeded maximum allowed redirects.", request=request + ) + + for hook in self._event_hooks["request"]: + hook(request) + + response = self._send_single_request(request) + try: + for hook in self._event_hooks["response"]: + hook(response) + response.history = list(history) + + if not response.has_redirect_location: + return response + + request = self._build_redirect_request(request, response) + history = history + [response] + + if follow_redirects: + response.read() + else: + response.next_request = request + return response + + except BaseException as exc: + response.close() + raise exc + + def _send_single_request(self, request: Request) -> Response: + """ + Sends a single request, without handling any redirections. + """ + transport = self._transport_for_url(request.url) + start = time.perf_counter() + + if not isinstance(request.stream, SyncByteStream): + raise RuntimeError( + "Attempted to send an async request with a sync Client instance." + ) + + with request_context(request=request): + response = transport.handle_request(request) + + assert isinstance(response.stream, SyncByteStream) + + response.request = request + response.stream = BoundSyncStream( + response.stream, response=response, start=start + ) + self.cookies.extract_cookies(response) + response.default_encoding = self._default_encoding + + logger.info( + 'HTTP Request: %s %s "%s %d %s"', + request.method, + request.url, + response.http_version, + response.status_code, + response.reason_phrase, + ) + + return response + + def get( + self, + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `GET` request. + + **Parameters**: See `httpx.request`. + """ + return self.request( + "GET", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + def options( + self, + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send an `OPTIONS` request. + + **Parameters**: See `httpx.request`. + """ + return self.request( + "OPTIONS", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + def head( + self, + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `HEAD` request. + + **Parameters**: See `httpx.request`. + """ + return self.request( + "HEAD", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + def post( + self, + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `POST` request. + + **Parameters**: See `httpx.request`. + """ + return self.request( + "POST", + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + def put( + self, + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `PUT` request. + + **Parameters**: See `httpx.request`. + """ + return self.request( + "PUT", + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + def patch( + self, + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `PATCH` request. + + **Parameters**: See `httpx.request`. + """ + return self.request( + "PATCH", + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + def delete( + self, + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `DELETE` request. + + **Parameters**: See `httpx.request`. + """ + return self.request( + "DELETE", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + def close(self) -> None: + """ + Close transport and proxies. + """ + if self._state != ClientState.CLOSED: + self._state = ClientState.CLOSED + + self._transport.close() + for transport in self._mounts.values(): + if transport is not None: + transport.close() + + def __enter__(self: T) -> T: + if self._state != ClientState.UNOPENED: + msg = { + ClientState.OPENED: "Cannot open a client instance more than once.", + ClientState.CLOSED: ( + "Cannot reopen a client instance, once it has been closed." + ), + }[self._state] + raise RuntimeError(msg) + + self._state = ClientState.OPENED + + self._transport.__enter__() + for transport in self._mounts.values(): + if transport is not None: + transport.__enter__() + return self + + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: TracebackType | None = None, + ) -> None: + self._state = ClientState.CLOSED + + self._transport.__exit__(exc_type, exc_value, traceback) + for transport in self._mounts.values(): + if transport is not None: + transport.__exit__(exc_type, exc_value, traceback) + + +class AsyncClient(BaseClient): + """ + An asynchronous HTTP client, with connection pooling, HTTP/2, redirects, + cookie persistence, etc. + + It can be shared between tasks. + + Usage: + + ```python + >>> async with httpx.AsyncClient() as client: + >>> response = await client.get('https://example.org') + ``` + + **Parameters:** + + * **auth** - *(optional)* An authentication class to use when sending + requests. + * **params** - *(optional)* Query parameters to include in request URLs, as + a string, dictionary, or sequence of two-tuples. + * **headers** - *(optional)* Dictionary of HTTP headers to include when + sending requests. + * **cookies** - *(optional)* Dictionary of Cookie items to include when + sending requests. + * **verify** - *(optional)* Either `True` to use an SSL context with the + default CA bundle, `False` to disable verification, or an instance of + `ssl.SSLContext` to use a custom context. + * **http2** - *(optional)* A boolean indicating if HTTP/2 support should be + enabled. Defaults to `False`. + * **proxy** - *(optional)* A proxy URL where all the traffic should be routed. + * **timeout** - *(optional)* The timeout configuration to use when sending + requests. + * **limits** - *(optional)* The limits configuration to use. + * **max_redirects** - *(optional)* The maximum number of redirect responses + that should be followed. + * **base_url** - *(optional)* A URL to use as the base when building + request URLs. + * **transport** - *(optional)* A transport class to use for sending requests + over the network. + * **trust_env** - *(optional)* Enables or disables usage of environment + variables for configuration. + * **default_encoding** - *(optional)* The default encoding to use for decoding + response text, if no charset information is included in a response Content-Type + header. Set to a callable for automatic character set detection. Default: "utf-8". + """ + + def __init__( + self, + *, + auth: AuthTypes | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + verify: ssl.SSLContext | str | bool = True, + cert: CertTypes | None = None, + http1: bool = True, + http2: bool = False, + proxy: ProxyTypes | None = None, + mounts: None | (typing.Mapping[str, AsyncBaseTransport | None]) = None, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + follow_redirects: bool = False, + limits: Limits = DEFAULT_LIMITS, + max_redirects: int = DEFAULT_MAX_REDIRECTS, + event_hooks: None | (typing.Mapping[str, list[EventHook]]) = None, + base_url: URL | str = "", + transport: AsyncBaseTransport | None = None, + trust_env: bool = True, + default_encoding: str | typing.Callable[[bytes], str] = "utf-8", + ) -> None: + super().__init__( + auth=auth, + params=params, + headers=headers, + cookies=cookies, + timeout=timeout, + follow_redirects=follow_redirects, + max_redirects=max_redirects, + event_hooks=event_hooks, + base_url=base_url, + trust_env=trust_env, + default_encoding=default_encoding, + ) + + if http2: + try: + import h2 # noqa + except ImportError: # pragma: no cover + raise ImportError( + "Using http2=True, but the 'h2' package is not installed. " + "Make sure to install httpx using `pip install httpx[http2]`." + ) from None + + allow_env_proxies = trust_env and transport is None + proxy_map = self._get_proxy_map(proxy, allow_env_proxies) + + self._transport = self._init_transport( + verify=verify, + cert=cert, + trust_env=trust_env, + http1=http1, + http2=http2, + limits=limits, + transport=transport, + ) + + self._mounts: dict[URLPattern, AsyncBaseTransport | None] = { + URLPattern(key): None + if proxy is None + else self._init_proxy_transport( + proxy, + verify=verify, + cert=cert, + trust_env=trust_env, + http1=http1, + http2=http2, + limits=limits, + ) + for key, proxy in proxy_map.items() + } + if mounts is not None: + self._mounts.update( + {URLPattern(key): transport for key, transport in mounts.items()} + ) + self._mounts = dict(sorted(self._mounts.items())) + + def _init_transport( + self, + verify: ssl.SSLContext | str | bool = True, + cert: CertTypes | None = None, + trust_env: bool = True, + http1: bool = True, + http2: bool = False, + limits: Limits = DEFAULT_LIMITS, + transport: AsyncBaseTransport | None = None, + ) -> AsyncBaseTransport: + if transport is not None: + return transport + + return AsyncHTTPTransport( + verify=verify, + cert=cert, + trust_env=trust_env, + http1=http1, + http2=http2, + limits=limits, + ) + + def _init_proxy_transport( + self, + proxy: Proxy, + verify: ssl.SSLContext | str | bool = True, + cert: CertTypes | None = None, + trust_env: bool = True, + http1: bool = True, + http2: bool = False, + limits: Limits = DEFAULT_LIMITS, + ) -> AsyncBaseTransport: + return AsyncHTTPTransport( + verify=verify, + cert=cert, + trust_env=trust_env, + http1=http1, + http2=http2, + limits=limits, + proxy=proxy, + ) + + def _transport_for_url(self, url: URL) -> AsyncBaseTransport: + """ + Returns the transport instance that should be used for a given URL. + This will either be the standard connection pool, or a proxy. + """ + for pattern, transport in self._mounts.items(): + if pattern.matches(url): + return self._transport if transport is None else transport + + return self._transport + + async def request( + self, + method: str, + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Build and send a request. + + Equivalent to: + + ```python + request = client.build_request(...) + response = await client.send(request, ...) + ``` + + See `AsyncClient.build_request()`, `AsyncClient.send()` + and [Merging of configuration][0] for how the various parameters + are merged with client-level configuration. + + [0]: /advanced/clients/#merging-of-configuration + """ + + if cookies is not None: # pragma: no cover + message = ( + "Setting per-request cookies=<...> is being deprecated, because " + "the expected behaviour on cookie persistence is ambiguous. Set " + "cookies directly on the client instance instead." + ) + warnings.warn(message, DeprecationWarning, stacklevel=2) + + request = self.build_request( + method=method, + url=url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + timeout=timeout, + extensions=extensions, + ) + return await self.send(request, auth=auth, follow_redirects=follow_redirects) + + @asynccontextmanager + async def stream( + self, + method: str, + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> typing.AsyncIterator[Response]: + """ + Alternative to `httpx.request()` that streams the response body + instead of loading it into memory at once. + + **Parameters**: See `httpx.request`. + + See also: [Streaming Responses][0] + + [0]: /quickstart#streaming-responses + """ + request = self.build_request( + method=method, + url=url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + timeout=timeout, + extensions=extensions, + ) + response = await self.send( + request=request, + auth=auth, + follow_redirects=follow_redirects, + stream=True, + ) + try: + yield response + finally: + await response.aclose() + + async def send( + self, + request: Request, + *, + stream: bool = False, + auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + ) -> Response: + """ + Send a request. + + The request is sent as-is, unmodified. + + Typically you'll want to build one with `AsyncClient.build_request()` + so that any client-level configuration is merged into the request, + but passing an explicit `httpx.Request()` is supported as well. + + See also: [Request instances][0] + + [0]: /advanced/clients/#request-instances + """ + if self._state == ClientState.CLOSED: + raise RuntimeError("Cannot send a request, as the client has been closed.") + + self._state = ClientState.OPENED + follow_redirects = ( + self.follow_redirects + if isinstance(follow_redirects, UseClientDefault) + else follow_redirects + ) + + self._set_timeout(request) + + auth = self._build_request_auth(request, auth) + + response = await self._send_handling_auth( + request, + auth=auth, + follow_redirects=follow_redirects, + history=[], + ) + try: + if not stream: + await response.aread() + + return response + + except BaseException as exc: + await response.aclose() + raise exc + + async def _send_handling_auth( + self, + request: Request, + auth: Auth, + follow_redirects: bool, + history: list[Response], + ) -> Response: + auth_flow = auth.async_auth_flow(request) + try: + request = await auth_flow.__anext__() + + while True: + response = await self._send_handling_redirects( + request, + follow_redirects=follow_redirects, + history=history, + ) + try: + try: + next_request = await auth_flow.asend(response) + except StopAsyncIteration: + return response + + response.history = list(history) + await response.aread() + request = next_request + history.append(response) + + except BaseException as exc: + await response.aclose() + raise exc + finally: + await auth_flow.aclose() + + async def _send_handling_redirects( + self, + request: Request, + follow_redirects: bool, + history: list[Response], + ) -> Response: + while True: + if len(history) > self.max_redirects: + raise TooManyRedirects( + "Exceeded maximum allowed redirects.", request=request + ) + + for hook in self._event_hooks["request"]: + await hook(request) + + response = await self._send_single_request(request) + try: + for hook in self._event_hooks["response"]: + await hook(response) + + response.history = list(history) + + if not response.has_redirect_location: + return response + + request = self._build_redirect_request(request, response) + history = history + [response] + + if follow_redirects: + await response.aread() + else: + response.next_request = request + return response + + except BaseException as exc: + await response.aclose() + raise exc + + async def _send_single_request(self, request: Request) -> Response: + """ + Sends a single request, without handling any redirections. + """ + transport = self._transport_for_url(request.url) + start = time.perf_counter() + + if not isinstance(request.stream, AsyncByteStream): + raise RuntimeError( + "Attempted to send an sync request with an AsyncClient instance." + ) + + with request_context(request=request): + response = await transport.handle_async_request(request) + + assert isinstance(response.stream, AsyncByteStream) + response.request = request + response.stream = BoundAsyncStream( + response.stream, response=response, start=start + ) + self.cookies.extract_cookies(response) + response.default_encoding = self._default_encoding + + logger.info( + 'HTTP Request: %s %s "%s %d %s"', + request.method, + request.url, + response.http_version, + response.status_code, + response.reason_phrase, + ) + + return response + + async def get( + self, + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `GET` request. + + **Parameters**: See `httpx.request`. + """ + return await self.request( + "GET", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + async def options( + self, + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send an `OPTIONS` request. + + **Parameters**: See `httpx.request`. + """ + return await self.request( + "OPTIONS", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + async def head( + self, + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `HEAD` request. + + **Parameters**: See `httpx.request`. + """ + return await self.request( + "HEAD", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + async def post( + self, + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `POST` request. + + **Parameters**: See `httpx.request`. + """ + return await self.request( + "POST", + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + async def put( + self, + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `PUT` request. + + **Parameters**: See `httpx.request`. + """ + return await self.request( + "PUT", + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + async def patch( + self, + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `PATCH` request. + + **Parameters**: See `httpx.request`. + """ + return await self.request( + "PATCH", + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + async def delete( + self, + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `DELETE` request. + + **Parameters**: See `httpx.request`. + """ + return await self.request( + "DELETE", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + async def aclose(self) -> None: + """ + Close transport and proxies. + """ + if self._state != ClientState.CLOSED: + self._state = ClientState.CLOSED + + await self._transport.aclose() + for proxy in self._mounts.values(): + if proxy is not None: + await proxy.aclose() + + async def __aenter__(self: U) -> U: + if self._state != ClientState.UNOPENED: + msg = { + ClientState.OPENED: "Cannot open a client instance more than once.", + ClientState.CLOSED: ( + "Cannot reopen a client instance, once it has been closed." + ), + }[self._state] + raise RuntimeError(msg) + + self._state = ClientState.OPENED + + await self._transport.__aenter__() + for proxy in self._mounts.values(): + if proxy is not None: + await proxy.__aenter__() + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: TracebackType | None = None, + ) -> None: + self._state = ClientState.CLOSED + + await self._transport.__aexit__(exc_type, exc_value, traceback) + for proxy in self._mounts.values(): + if proxy is not None: + await proxy.__aexit__(exc_type, exc_value, traceback) diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/_config.py b/data/miniconda3/lib/python3.13/site-packages/httpx/_config.py new file mode 100644 index 0000000000000000000000000000000000000000..467a6c90ae269babe3af7963d9d7c78b9f012268 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/httpx/_config.py @@ -0,0 +1,248 @@ +from __future__ import annotations + +import os +import typing + +from ._models import Headers +from ._types import CertTypes, HeaderTypes, TimeoutTypes +from ._urls import URL + +if typing.TYPE_CHECKING: + import ssl # pragma: no cover + +__all__ = ["Limits", "Proxy", "Timeout", "create_ssl_context"] + + +class UnsetType: + pass # pragma: no cover + + +UNSET = UnsetType() + + +def create_ssl_context( + verify: ssl.SSLContext | str | bool = True, + cert: CertTypes | None = None, + trust_env: bool = True, +) -> ssl.SSLContext: + import ssl + import warnings + + import certifi + + if verify is True: + if trust_env and os.environ.get("SSL_CERT_FILE"): # pragma: nocover + ctx = ssl.create_default_context(cafile=os.environ["SSL_CERT_FILE"]) + elif trust_env and os.environ.get("SSL_CERT_DIR"): # pragma: nocover + ctx = ssl.create_default_context(capath=os.environ["SSL_CERT_DIR"]) + else: + # Default case... + ctx = ssl.create_default_context(cafile=certifi.where()) + elif verify is False: + ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + ctx.check_hostname = False + ctx.verify_mode = ssl.CERT_NONE + elif isinstance(verify, str): # pragma: nocover + message = ( + "`verify=` is deprecated. " + "Use `verify=ssl.create_default_context(cafile=...)` " + "or `verify=ssl.create_default_context(capath=...)` instead." + ) + warnings.warn(message, DeprecationWarning) + if os.path.isdir(verify): + return ssl.create_default_context(capath=verify) + return ssl.create_default_context(cafile=verify) + else: + ctx = verify + + if cert: # pragma: nocover + message = ( + "`cert=...` is deprecated. Use `verify=` instead," + "with `.load_cert_chain()` to configure the certificate chain." + ) + warnings.warn(message, DeprecationWarning) + if isinstance(cert, str): + ctx.load_cert_chain(cert) + else: + ctx.load_cert_chain(*cert) + + return ctx + + +class Timeout: + """ + Timeout configuration. + + **Usage**: + + Timeout(None) # No timeouts. + Timeout(5.0) # 5s timeout on all operations. + Timeout(None, connect=5.0) # 5s timeout on connect, no other timeouts. + Timeout(5.0, connect=10.0) # 10s timeout on connect. 5s timeout elsewhere. + Timeout(5.0, pool=None) # No timeout on acquiring connection from pool. + # 5s timeout elsewhere. + """ + + def __init__( + self, + timeout: TimeoutTypes | UnsetType = UNSET, + *, + connect: None | float | UnsetType = UNSET, + read: None | float | UnsetType = UNSET, + write: None | float | UnsetType = UNSET, + pool: None | float | UnsetType = UNSET, + ) -> None: + if isinstance(timeout, Timeout): + # Passed as a single explicit Timeout. + assert connect is UNSET + assert read is UNSET + assert write is UNSET + assert pool is UNSET + self.connect = timeout.connect # type: typing.Optional[float] + self.read = timeout.read # type: typing.Optional[float] + self.write = timeout.write # type: typing.Optional[float] + self.pool = timeout.pool # type: typing.Optional[float] + elif isinstance(timeout, tuple): + # Passed as a tuple. + self.connect = timeout[0] + self.read = timeout[1] + self.write = None if len(timeout) < 3 else timeout[2] + self.pool = None if len(timeout) < 4 else timeout[3] + elif not ( + isinstance(connect, UnsetType) + or isinstance(read, UnsetType) + or isinstance(write, UnsetType) + or isinstance(pool, UnsetType) + ): + self.connect = connect + self.read = read + self.write = write + self.pool = pool + else: + if isinstance(timeout, UnsetType): + raise ValueError( + "httpx.Timeout must either include a default, or set all " + "four parameters explicitly." + ) + self.connect = timeout if isinstance(connect, UnsetType) else connect + self.read = timeout if isinstance(read, UnsetType) else read + self.write = timeout if isinstance(write, UnsetType) else write + self.pool = timeout if isinstance(pool, UnsetType) else pool + + def as_dict(self) -> dict[str, float | None]: + return { + "connect": self.connect, + "read": self.read, + "write": self.write, + "pool": self.pool, + } + + def __eq__(self, other: typing.Any) -> bool: + return ( + isinstance(other, self.__class__) + and self.connect == other.connect + and self.read == other.read + and self.write == other.write + and self.pool == other.pool + ) + + def __repr__(self) -> str: + class_name = self.__class__.__name__ + if len({self.connect, self.read, self.write, self.pool}) == 1: + return f"{class_name}(timeout={self.connect})" + return ( + f"{class_name}(connect={self.connect}, " + f"read={self.read}, write={self.write}, pool={self.pool})" + ) + + +class Limits: + """ + Configuration for limits to various client behaviors. + + **Parameters:** + + * **max_connections** - The maximum number of concurrent connections that may be + established. + * **max_keepalive_connections** - Allow the connection pool to maintain + keep-alive connections below this point. Should be less than or equal + to `max_connections`. + * **keepalive_expiry** - Time limit on idle keep-alive connections in seconds. + """ + + def __init__( + self, + *, + max_connections: int | None = None, + max_keepalive_connections: int | None = None, + keepalive_expiry: float | None = 5.0, + ) -> None: + self.max_connections = max_connections + self.max_keepalive_connections = max_keepalive_connections + self.keepalive_expiry = keepalive_expiry + + def __eq__(self, other: typing.Any) -> bool: + return ( + isinstance(other, self.__class__) + and self.max_connections == other.max_connections + and self.max_keepalive_connections == other.max_keepalive_connections + and self.keepalive_expiry == other.keepalive_expiry + ) + + def __repr__(self) -> str: + class_name = self.__class__.__name__ + return ( + f"{class_name}(max_connections={self.max_connections}, " + f"max_keepalive_connections={self.max_keepalive_connections}, " + f"keepalive_expiry={self.keepalive_expiry})" + ) + + +class Proxy: + def __init__( + self, + url: URL | str, + *, + ssl_context: ssl.SSLContext | None = None, + auth: tuple[str, str] | None = None, + headers: HeaderTypes | None = None, + ) -> None: + url = URL(url) + headers = Headers(headers) + + if url.scheme not in ("http", "https", "socks5", "socks5h"): + raise ValueError(f"Unknown scheme for proxy URL {url!r}") + + if url.username or url.password: + # Remove any auth credentials from the URL. + auth = (url.username, url.password) + url = url.copy_with(username=None, password=None) + + self.url = url + self.auth = auth + self.headers = headers + self.ssl_context = ssl_context + + @property + def raw_auth(self) -> tuple[bytes, bytes] | None: + # The proxy authentication as raw bytes. + return ( + None + if self.auth is None + else (self.auth[0].encode("utf-8"), self.auth[1].encode("utf-8")) + ) + + def __repr__(self) -> str: + # The authentication is represented with the password component masked. + auth = (self.auth[0], "********") if self.auth else None + + # Build a nice concise representation. + url_str = f"{str(self.url)!r}" + auth_str = f", auth={auth!r}" if auth else "" + headers_str = f", headers={dict(self.headers)!r}" if self.headers else "" + return f"Proxy({url_str}{auth_str}{headers_str})" + + +DEFAULT_TIMEOUT_CONFIG = Timeout(timeout=5.0) +DEFAULT_LIMITS = Limits(max_connections=100, max_keepalive_connections=20) +DEFAULT_MAX_REDIRECTS = 20 diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/_content.py b/data/miniconda3/lib/python3.13/site-packages/httpx/_content.py new file mode 100644 index 0000000000000000000000000000000000000000..6f479a0885f723b7395843d41164a87041820776 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/httpx/_content.py @@ -0,0 +1,240 @@ +from __future__ import annotations + +import inspect +import warnings +from json import dumps as json_dumps +from typing import ( + Any, + AsyncIterable, + AsyncIterator, + Iterable, + Iterator, + Mapping, +) +from urllib.parse import urlencode + +from ._exceptions import StreamClosed, StreamConsumed +from ._multipart import MultipartStream +from ._types import ( + AsyncByteStream, + RequestContent, + RequestData, + RequestFiles, + ResponseContent, + SyncByteStream, +) +from ._utils import peek_filelike_length, primitive_value_to_str + +__all__ = ["ByteStream"] + + +class ByteStream(AsyncByteStream, SyncByteStream): + def __init__(self, stream: bytes) -> None: + self._stream = stream + + def __iter__(self) -> Iterator[bytes]: + yield self._stream + + async def __aiter__(self) -> AsyncIterator[bytes]: + yield self._stream + + +class IteratorByteStream(SyncByteStream): + CHUNK_SIZE = 65_536 + + def __init__(self, stream: Iterable[bytes]) -> None: + self._stream = stream + self._is_stream_consumed = False + self._is_generator = inspect.isgenerator(stream) + + def __iter__(self) -> Iterator[bytes]: + if self._is_stream_consumed and self._is_generator: + raise StreamConsumed() + + self._is_stream_consumed = True + if hasattr(self._stream, "read"): + # File-like interfaces should use 'read' directly. + chunk = self._stream.read(self.CHUNK_SIZE) + while chunk: + yield chunk + chunk = self._stream.read(self.CHUNK_SIZE) + else: + # Otherwise iterate. + for part in self._stream: + yield part + + +class AsyncIteratorByteStream(AsyncByteStream): + CHUNK_SIZE = 65_536 + + def __init__(self, stream: AsyncIterable[bytes]) -> None: + self._stream = stream + self._is_stream_consumed = False + self._is_generator = inspect.isasyncgen(stream) + + async def __aiter__(self) -> AsyncIterator[bytes]: + if self._is_stream_consumed and self._is_generator: + raise StreamConsumed() + + self._is_stream_consumed = True + if hasattr(self._stream, "aread"): + # File-like interfaces should use 'aread' directly. + chunk = await self._stream.aread(self.CHUNK_SIZE) + while chunk: + yield chunk + chunk = await self._stream.aread(self.CHUNK_SIZE) + else: + # Otherwise iterate. + async for part in self._stream: + yield part + + +class UnattachedStream(AsyncByteStream, SyncByteStream): + """ + If a request or response is serialized using pickle, then it is no longer + attached to a stream for I/O purposes. Any stream operations should result + in `httpx.StreamClosed`. + """ + + def __iter__(self) -> Iterator[bytes]: + raise StreamClosed() + + async def __aiter__(self) -> AsyncIterator[bytes]: + raise StreamClosed() + yield b"" # pragma: no cover + + +def encode_content( + content: str | bytes | Iterable[bytes] | AsyncIterable[bytes], +) -> tuple[dict[str, str], SyncByteStream | AsyncByteStream]: + if isinstance(content, (bytes, str)): + body = content.encode("utf-8") if isinstance(content, str) else content + content_length = len(body) + headers = {"Content-Length": str(content_length)} if body else {} + return headers, ByteStream(body) + + elif isinstance(content, Iterable) and not isinstance(content, dict): + # `not isinstance(content, dict)` is a bit oddly specific, but it + # catches a case that's easy for users to make in error, and would + # otherwise pass through here, like any other bytes-iterable, + # because `dict` happens to be iterable. See issue #2491. + content_length_or_none = peek_filelike_length(content) + + if content_length_or_none is None: + headers = {"Transfer-Encoding": "chunked"} + else: + headers = {"Content-Length": str(content_length_or_none)} + return headers, IteratorByteStream(content) # type: ignore + + elif isinstance(content, AsyncIterable): + headers = {"Transfer-Encoding": "chunked"} + return headers, AsyncIteratorByteStream(content) + + raise TypeError(f"Unexpected type for 'content', {type(content)!r}") + + +def encode_urlencoded_data( + data: RequestData, +) -> tuple[dict[str, str], ByteStream]: + plain_data = [] + for key, value in data.items(): + if isinstance(value, (list, tuple)): + plain_data.extend([(key, primitive_value_to_str(item)) for item in value]) + else: + plain_data.append((key, primitive_value_to_str(value))) + body = urlencode(plain_data, doseq=True).encode("utf-8") + content_length = str(len(body)) + content_type = "application/x-www-form-urlencoded" + headers = {"Content-Length": content_length, "Content-Type": content_type} + return headers, ByteStream(body) + + +def encode_multipart_data( + data: RequestData, files: RequestFiles, boundary: bytes | None +) -> tuple[dict[str, str], MultipartStream]: + multipart = MultipartStream(data=data, files=files, boundary=boundary) + headers = multipart.get_headers() + return headers, multipart + + +def encode_text(text: str) -> tuple[dict[str, str], ByteStream]: + body = text.encode("utf-8") + content_length = str(len(body)) + content_type = "text/plain; charset=utf-8" + headers = {"Content-Length": content_length, "Content-Type": content_type} + return headers, ByteStream(body) + + +def encode_html(html: str) -> tuple[dict[str, str], ByteStream]: + body = html.encode("utf-8") + content_length = str(len(body)) + content_type = "text/html; charset=utf-8" + headers = {"Content-Length": content_length, "Content-Type": content_type} + return headers, ByteStream(body) + + +def encode_json(json: Any) -> tuple[dict[str, str], ByteStream]: + body = json_dumps( + json, ensure_ascii=False, separators=(",", ":"), allow_nan=False + ).encode("utf-8") + content_length = str(len(body)) + content_type = "application/json" + headers = {"Content-Length": content_length, "Content-Type": content_type} + return headers, ByteStream(body) + + +def encode_request( + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: Any | None = None, + boundary: bytes | None = None, +) -> tuple[dict[str, str], SyncByteStream | AsyncByteStream]: + """ + Handles encoding the given `content`, `data`, `files`, and `json`, + returning a two-tuple of (, ). + """ + if data is not None and not isinstance(data, Mapping): + # We prefer to separate `content=` + # for raw request content, and `data=
` for url encoded or + # multipart form content. + # + # However for compat with requests, we *do* still support + # `data=` usages. We deal with that case here, treating it + # as if `content=<...>` had been supplied instead. + message = "Use 'content=<...>' to upload raw bytes/text content." + warnings.warn(message, DeprecationWarning, stacklevel=2) + return encode_content(data) + + if content is not None: + return encode_content(content) + elif files: + return encode_multipart_data(data or {}, files, boundary) + elif data: + return encode_urlencoded_data(data) + elif json is not None: + return encode_json(json) + + return {}, ByteStream(b"") + + +def encode_response( + content: ResponseContent | None = None, + text: str | None = None, + html: str | None = None, + json: Any | None = None, +) -> tuple[dict[str, str], SyncByteStream | AsyncByteStream]: + """ + Handles encoding the given `content`, returning a two-tuple of + (, ). + """ + if content is not None: + return encode_content(content) + elif text is not None: + return encode_text(text) + elif html is not None: + return encode_html(html) + elif json is not None: + return encode_json(json) + + return {}, ByteStream(b"") diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/_decoders.py b/data/miniconda3/lib/python3.13/site-packages/httpx/_decoders.py new file mode 100644 index 0000000000000000000000000000000000000000..899dfada878e1181fca6d3c75a79526a076abb9e --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/httpx/_decoders.py @@ -0,0 +1,393 @@ +""" +Handlers for Content-Encoding. + +See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding +""" + +from __future__ import annotations + +import codecs +import io +import typing +import zlib + +from ._exceptions import DecodingError + +# Brotli support is optional +try: + # The C bindings in `brotli` are recommended for CPython. + import brotli +except ImportError: # pragma: no cover + try: + # The CFFI bindings in `brotlicffi` are recommended for PyPy + # and other environments. + import brotlicffi as brotli + except ImportError: + brotli = None + + +# Zstandard support is optional +try: + import zstandard +except ImportError: # pragma: no cover + zstandard = None # type: ignore + + +class ContentDecoder: + def decode(self, data: bytes) -> bytes: + raise NotImplementedError() # pragma: no cover + + def flush(self) -> bytes: + raise NotImplementedError() # pragma: no cover + + +class IdentityDecoder(ContentDecoder): + """ + Handle unencoded data. + """ + + def decode(self, data: bytes) -> bytes: + return data + + def flush(self) -> bytes: + return b"" + + +class DeflateDecoder(ContentDecoder): + """ + Handle 'deflate' decoding. + + See: https://stackoverflow.com/questions/1838699 + """ + + def __init__(self) -> None: + self.first_attempt = True + self.decompressor = zlib.decompressobj() + + def decode(self, data: bytes) -> bytes: + was_first_attempt = self.first_attempt + self.first_attempt = False + try: + return self.decompressor.decompress(data) + except zlib.error as exc: + if was_first_attempt: + self.decompressor = zlib.decompressobj(-zlib.MAX_WBITS) + return self.decode(data) + raise DecodingError(str(exc)) from exc + + def flush(self) -> bytes: + try: + return self.decompressor.flush() + except zlib.error as exc: # pragma: no cover + raise DecodingError(str(exc)) from exc + + +class GZipDecoder(ContentDecoder): + """ + Handle 'gzip' decoding. + + See: https://stackoverflow.com/questions/1838699 + """ + + def __init__(self) -> None: + self.decompressor = zlib.decompressobj(zlib.MAX_WBITS | 16) + + def decode(self, data: bytes) -> bytes: + try: + return self.decompressor.decompress(data) + except zlib.error as exc: + raise DecodingError(str(exc)) from exc + + def flush(self) -> bytes: + try: + return self.decompressor.flush() + except zlib.error as exc: # pragma: no cover + raise DecodingError(str(exc)) from exc + + +class BrotliDecoder(ContentDecoder): + """ + Handle 'brotli' decoding. + + Requires `pip install brotlipy`. See: https://brotlipy.readthedocs.io/ + or `pip install brotli`. See https://github.com/google/brotli + Supports both 'brotlipy' and 'Brotli' packages since they share an import + name. The top branches are for 'brotlipy' and bottom branches for 'Brotli' + """ + + def __init__(self) -> None: + if brotli is None: # pragma: no cover + raise ImportError( + "Using 'BrotliDecoder', but neither of the 'brotlicffi' or 'brotli' " + "packages have been installed. " + "Make sure to install httpx using `pip install httpx[brotli]`." + ) from None + + self.decompressor = brotli.Decompressor() + self.seen_data = False + self._decompress: typing.Callable[[bytes], bytes] + if hasattr(self.decompressor, "decompress"): + # The 'brotlicffi' package. + self._decompress = self.decompressor.decompress # pragma: no cover + else: + # The 'brotli' package. + self._decompress = self.decompressor.process # pragma: no cover + + def decode(self, data: bytes) -> bytes: + if not data: + return b"" + self.seen_data = True + try: + return self._decompress(data) + except brotli.error as exc: + raise DecodingError(str(exc)) from exc + + def flush(self) -> bytes: + if not self.seen_data: + return b"" + try: + if hasattr(self.decompressor, "finish"): + # Only available in the 'brotlicffi' package. + + # As the decompressor decompresses eagerly, this + # will never actually emit any data. However, it will potentially throw + # errors if a truncated or damaged data stream has been used. + self.decompressor.finish() # pragma: no cover + return b"" + except brotli.error as exc: # pragma: no cover + raise DecodingError(str(exc)) from exc + + +class ZStandardDecoder(ContentDecoder): + """ + Handle 'zstd' RFC 8878 decoding. + + Requires `pip install zstandard`. + Can be installed as a dependency of httpx using `pip install httpx[zstd]`. + """ + + # inspired by the ZstdDecoder implementation in urllib3 + def __init__(self) -> None: + if zstandard is None: # pragma: no cover + raise ImportError( + "Using 'ZStandardDecoder', ..." + "Make sure to install httpx using `pip install httpx[zstd]`." + ) from None + + self.decompressor = zstandard.ZstdDecompressor().decompressobj() + self.seen_data = False + + def decode(self, data: bytes) -> bytes: + assert zstandard is not None + self.seen_data = True + output = io.BytesIO() + try: + output.write(self.decompressor.decompress(data)) + while self.decompressor.eof and self.decompressor.unused_data: + unused_data = self.decompressor.unused_data + self.decompressor = zstandard.ZstdDecompressor().decompressobj() + output.write(self.decompressor.decompress(unused_data)) + except zstandard.ZstdError as exc: + raise DecodingError(str(exc)) from exc + return output.getvalue() + + def flush(self) -> bytes: + if not self.seen_data: + return b"" + ret = self.decompressor.flush() # note: this is a no-op + if not self.decompressor.eof: + raise DecodingError("Zstandard data is incomplete") # pragma: no cover + return bytes(ret) + + +class MultiDecoder(ContentDecoder): + """ + Handle the case where multiple encodings have been applied. + """ + + def __init__(self, children: typing.Sequence[ContentDecoder]) -> None: + """ + 'children' should be a sequence of decoders in the order in which + each was applied. + """ + # Note that we reverse the order for decoding. + self.children = list(reversed(children)) + + def decode(self, data: bytes) -> bytes: + for child in self.children: + data = child.decode(data) + return data + + def flush(self) -> bytes: + data = b"" + for child in self.children: + data = child.decode(data) + child.flush() + return data + + +class ByteChunker: + """ + Handles returning byte content in fixed-size chunks. + """ + + def __init__(self, chunk_size: int | None = None) -> None: + self._buffer = io.BytesIO() + self._chunk_size = chunk_size + + def decode(self, content: bytes) -> list[bytes]: + if self._chunk_size is None: + return [content] if content else [] + + self._buffer.write(content) + if self._buffer.tell() >= self._chunk_size: + value = self._buffer.getvalue() + chunks = [ + value[i : i + self._chunk_size] + for i in range(0, len(value), self._chunk_size) + ] + if len(chunks[-1]) == self._chunk_size: + self._buffer.seek(0) + self._buffer.truncate() + return chunks + else: + self._buffer.seek(0) + self._buffer.write(chunks[-1]) + self._buffer.truncate() + return chunks[:-1] + else: + return [] + + def flush(self) -> list[bytes]: + value = self._buffer.getvalue() + self._buffer.seek(0) + self._buffer.truncate() + return [value] if value else [] + + +class TextChunker: + """ + Handles returning text content in fixed-size chunks. + """ + + def __init__(self, chunk_size: int | None = None) -> None: + self._buffer = io.StringIO() + self._chunk_size = chunk_size + + def decode(self, content: str) -> list[str]: + if self._chunk_size is None: + return [content] if content else [] + + self._buffer.write(content) + if self._buffer.tell() >= self._chunk_size: + value = self._buffer.getvalue() + chunks = [ + value[i : i + self._chunk_size] + for i in range(0, len(value), self._chunk_size) + ] + if len(chunks[-1]) == self._chunk_size: + self._buffer.seek(0) + self._buffer.truncate() + return chunks + else: + self._buffer.seek(0) + self._buffer.write(chunks[-1]) + self._buffer.truncate() + return chunks[:-1] + else: + return [] + + def flush(self) -> list[str]: + value = self._buffer.getvalue() + self._buffer.seek(0) + self._buffer.truncate() + return [value] if value else [] + + +class TextDecoder: + """ + Handles incrementally decoding bytes into text + """ + + def __init__(self, encoding: str = "utf-8") -> None: + self.decoder = codecs.getincrementaldecoder(encoding)(errors="replace") + + def decode(self, data: bytes) -> str: + return self.decoder.decode(data) + + def flush(self) -> str: + return self.decoder.decode(b"", True) + + +class LineDecoder: + """ + Handles incrementally reading lines from text. + + Has the same behaviour as the stdllib splitlines, + but handling the input iteratively. + """ + + def __init__(self) -> None: + self.buffer: list[str] = [] + self.trailing_cr: bool = False + + def decode(self, text: str) -> list[str]: + # See https://docs.python.org/3/library/stdtypes.html#str.splitlines + NEWLINE_CHARS = "\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029" + + # We always push a trailing `\r` into the next decode iteration. + if self.trailing_cr: + text = "\r" + text + self.trailing_cr = False + if text.endswith("\r"): + self.trailing_cr = True + text = text[:-1] + + if not text: + # NOTE: the edge case input of empty text doesn't occur in practice, + # because other httpx internals filter out this value + return [] # pragma: no cover + + trailing_newline = text[-1] in NEWLINE_CHARS + lines = text.splitlines() + + if len(lines) == 1 and not trailing_newline: + # No new lines, buffer the input and continue. + self.buffer.append(lines[0]) + return [] + + if self.buffer: + # Include any existing buffer in the first portion of the + # splitlines result. + lines = ["".join(self.buffer) + lines[0]] + lines[1:] + self.buffer = [] + + if not trailing_newline: + # If the last segment of splitlines is not newline terminated, + # then drop it from our output and start a new buffer. + self.buffer = [lines.pop()] + + return lines + + def flush(self) -> list[str]: + if not self.buffer and not self.trailing_cr: + return [] + + lines = ["".join(self.buffer)] + self.buffer = [] + self.trailing_cr = False + return lines + + +SUPPORTED_DECODERS = { + "identity": IdentityDecoder, + "gzip": GZipDecoder, + "deflate": DeflateDecoder, + "br": BrotliDecoder, + "zstd": ZStandardDecoder, +} + + +if brotli is None: + SUPPORTED_DECODERS.pop("br") # pragma: no cover +if zstandard is None: + SUPPORTED_DECODERS.pop("zstd") # pragma: no cover diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/_exceptions.py b/data/miniconda3/lib/python3.13/site-packages/httpx/_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..77f45a6d3986d15626fc8a5fd459d6a3e0fbe466 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/httpx/_exceptions.py @@ -0,0 +1,379 @@ +""" +Our exception hierarchy: + +* HTTPError + x RequestError + + TransportError + - TimeoutException + · ConnectTimeout + · ReadTimeout + · WriteTimeout + · PoolTimeout + - NetworkError + · ConnectError + · ReadError + · WriteError + · CloseError + - ProtocolError + · LocalProtocolError + · RemoteProtocolError + - ProxyError + - UnsupportedProtocol + + DecodingError + + TooManyRedirects + x HTTPStatusError +* InvalidURL +* CookieConflict +* StreamError + x StreamConsumed + x StreamClosed + x ResponseNotRead + x RequestNotRead +""" + +from __future__ import annotations + +import contextlib +import typing + +if typing.TYPE_CHECKING: + from ._models import Request, Response # pragma: no cover + +__all__ = [ + "CloseError", + "ConnectError", + "ConnectTimeout", + "CookieConflict", + "DecodingError", + "HTTPError", + "HTTPStatusError", + "InvalidURL", + "LocalProtocolError", + "NetworkError", + "PoolTimeout", + "ProtocolError", + "ProxyError", + "ReadError", + "ReadTimeout", + "RemoteProtocolError", + "RequestError", + "RequestNotRead", + "ResponseNotRead", + "StreamClosed", + "StreamConsumed", + "StreamError", + "TimeoutException", + "TooManyRedirects", + "TransportError", + "UnsupportedProtocol", + "WriteError", + "WriteTimeout", +] + + +class HTTPError(Exception): + """ + Base class for `RequestError` and `HTTPStatusError`. + + Useful for `try...except` blocks when issuing a request, + and then calling `.raise_for_status()`. + + For example: + + ``` + try: + response = httpx.get("https://www.example.com") + response.raise_for_status() + except httpx.HTTPError as exc: + print(f"HTTP Exception for {exc.request.url} - {exc}") + ``` + """ + + def __init__(self, message: str) -> None: + super().__init__(message) + self._request: Request | None = None + + @property + def request(self) -> Request: + if self._request is None: + raise RuntimeError("The .request property has not been set.") + return self._request + + @request.setter + def request(self, request: Request) -> None: + self._request = request + + +class RequestError(HTTPError): + """ + Base class for all exceptions that may occur when issuing a `.request()`. + """ + + def __init__(self, message: str, *, request: Request | None = None) -> None: + super().__init__(message) + # At the point an exception is raised we won't typically have a request + # instance to associate it with. + # + # The 'request_context' context manager is used within the Client and + # Response methods in order to ensure that any raised exceptions + # have a `.request` property set on them. + self._request = request + + +class TransportError(RequestError): + """ + Base class for all exceptions that occur at the level of the Transport API. + """ + + +# Timeout exceptions... + + +class TimeoutException(TransportError): + """ + The base class for timeout errors. + + An operation has timed out. + """ + + +class ConnectTimeout(TimeoutException): + """ + Timed out while connecting to the host. + """ + + +class ReadTimeout(TimeoutException): + """ + Timed out while receiving data from the host. + """ + + +class WriteTimeout(TimeoutException): + """ + Timed out while sending data to the host. + """ + + +class PoolTimeout(TimeoutException): + """ + Timed out waiting to acquire a connection from the pool. + """ + + +# Core networking exceptions... + + +class NetworkError(TransportError): + """ + The base class for network-related errors. + + An error occurred while interacting with the network. + """ + + +class ReadError(NetworkError): + """ + Failed to receive data from the network. + """ + + +class WriteError(NetworkError): + """ + Failed to send data through the network. + """ + + +class ConnectError(NetworkError): + """ + Failed to establish a connection. + """ + + +class CloseError(NetworkError): + """ + Failed to close a connection. + """ + + +# Other transport exceptions... + + +class ProxyError(TransportError): + """ + An error occurred while establishing a proxy connection. + """ + + +class UnsupportedProtocol(TransportError): + """ + Attempted to make a request to an unsupported protocol. + + For example issuing a request to `ftp://www.example.com`. + """ + + +class ProtocolError(TransportError): + """ + The protocol was violated. + """ + + +class LocalProtocolError(ProtocolError): + """ + A protocol was violated by the client. + + For example if the user instantiated a `Request` instance explicitly, + failed to include the mandatory `Host:` header, and then issued it directly + using `client.send()`. + """ + + +class RemoteProtocolError(ProtocolError): + """ + The protocol was violated by the server. + + For example, returning malformed HTTP. + """ + + +# Other request exceptions... + + +class DecodingError(RequestError): + """ + Decoding of the response failed, due to a malformed encoding. + """ + + +class TooManyRedirects(RequestError): + """ + Too many redirects. + """ + + +# Client errors + + +class HTTPStatusError(HTTPError): + """ + The response had an error HTTP status of 4xx or 5xx. + + May be raised when calling `response.raise_for_status()` + """ + + def __init__(self, message: str, *, request: Request, response: Response) -> None: + super().__init__(message) + self.request = request + self.response = response + + +class InvalidURL(Exception): + """ + URL is improperly formed or cannot be parsed. + """ + + def __init__(self, message: str) -> None: + super().__init__(message) + + +class CookieConflict(Exception): + """ + Attempted to lookup a cookie by name, but multiple cookies existed. + + Can occur when calling `response.cookies.get(...)`. + """ + + def __init__(self, message: str) -> None: + super().__init__(message) + + +# Stream exceptions... + +# These may occur as the result of a programming error, by accessing +# the request/response stream in an invalid manner. + + +class StreamError(RuntimeError): + """ + The base class for stream exceptions. + + The developer made an error in accessing the request stream in + an invalid way. + """ + + def __init__(self, message: str) -> None: + super().__init__(message) + + +class StreamConsumed(StreamError): + """ + Attempted to read or stream content, but the content has already + been streamed. + """ + + def __init__(self) -> None: + message = ( + "Attempted to read or stream some content, but the content has " + "already been streamed. For requests, this could be due to passing " + "a generator as request content, and then receiving a redirect " + "response or a secondary request as part of an authentication flow." + "For responses, this could be due to attempting to stream the response " + "content more than once." + ) + super().__init__(message) + + +class StreamClosed(StreamError): + """ + Attempted to read or stream response content, but the request has been + closed. + """ + + def __init__(self) -> None: + message = ( + "Attempted to read or stream content, but the stream has " "been closed." + ) + super().__init__(message) + + +class ResponseNotRead(StreamError): + """ + Attempted to access streaming response content, without having called `read()`. + """ + + def __init__(self) -> None: + message = ( + "Attempted to access streaming response content," + " without having called `read()`." + ) + super().__init__(message) + + +class RequestNotRead(StreamError): + """ + Attempted to access streaming request content, without having called `read()`. + """ + + def __init__(self) -> None: + message = ( + "Attempted to access streaming request content," + " without having called `read()`." + ) + super().__init__(message) + + +@contextlib.contextmanager +def request_context( + request: Request | None = None, +) -> typing.Iterator[None]: + """ + A context manager that can be used to attach the given request context + to any `RequestError` exceptions that are raised within the block. + """ + try: + yield + except RequestError as exc: + if request is not None: + exc.request = request + raise exc diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/_main.py b/data/miniconda3/lib/python3.13/site-packages/httpx/_main.py new file mode 100644 index 0000000000000000000000000000000000000000..cffa4bb7db0f930f4db56653a061c4d7400ba4e6 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/httpx/_main.py @@ -0,0 +1,506 @@ +from __future__ import annotations + +import functools +import json +import sys +import typing + +import click +import pygments.lexers +import pygments.util +import rich.console +import rich.markup +import rich.progress +import rich.syntax +import rich.table + +from ._client import Client +from ._exceptions import RequestError +from ._models import Response +from ._status_codes import codes + +if typing.TYPE_CHECKING: + import httpcore # pragma: no cover + + +def print_help() -> None: + console = rich.console.Console() + + console.print("[bold]HTTPX :butterfly:", justify="center") + console.print() + console.print("A next generation HTTP client.", justify="center") + console.print() + console.print( + "Usage: [bold]httpx[/bold] [cyan] [OPTIONS][/cyan] ", justify="left" + ) + console.print() + + table = rich.table.Table.grid(padding=1, pad_edge=True) + table.add_column("Parameter", no_wrap=True, justify="left", style="bold") + table.add_column("Description") + table.add_row( + "-m, --method [cyan]METHOD", + "Request method, such as GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD.\n" + "[Default: GET, or POST if a request body is included]", + ) + table.add_row( + "-p, --params [cyan] ...", + "Query parameters to include in the request URL.", + ) + table.add_row( + "-c, --content [cyan]TEXT", "Byte content to include in the request body." + ) + table.add_row( + "-d, --data [cyan] ...", "Form data to include in the request body." + ) + table.add_row( + "-f, --files [cyan] ...", + "Form files to include in the request body.", + ) + table.add_row("-j, --json [cyan]TEXT", "JSON data to include in the request body.") + table.add_row( + "-h, --headers [cyan] ...", + "Include additional HTTP headers in the request.", + ) + table.add_row( + "--cookies [cyan] ...", "Cookies to include in the request." + ) + table.add_row( + "--auth [cyan]", + "Username and password to include in the request. Specify '-' for the password" + " to use a password prompt. Note that using --verbose/-v will expose" + " the Authorization header, including the password encoding" + " in a trivially reversible format.", + ) + + table.add_row( + "--proxy [cyan]URL", + "Send the request via a proxy. Should be the URL giving the proxy address.", + ) + + table.add_row( + "--timeout [cyan]FLOAT", + "Timeout value to use for network operations, such as establishing the" + " connection, reading some data, etc... [Default: 5.0]", + ) + + table.add_row("--follow-redirects", "Automatically follow redirects.") + table.add_row("--no-verify", "Disable SSL verification.") + table.add_row( + "--http2", "Send the request using HTTP/2, if the remote server supports it." + ) + + table.add_row( + "--download [cyan]FILE", + "Save the response content as a file, rather than displaying it.", + ) + + table.add_row("-v, --verbose", "Verbose output. Show request as well as response.") + table.add_row("--help", "Show this message and exit.") + console.print(table) + + +def get_lexer_for_response(response: Response) -> str: + content_type = response.headers.get("Content-Type") + if content_type is not None: + mime_type, _, _ = content_type.partition(";") + try: + return typing.cast( + str, pygments.lexers.get_lexer_for_mimetype(mime_type.strip()).name + ) + except pygments.util.ClassNotFound: # pragma: no cover + pass + return "" # pragma: no cover + + +def format_request_headers(request: httpcore.Request, http2: bool = False) -> str: + version = "HTTP/2" if http2 else "HTTP/1.1" + headers = [ + (name.lower() if http2 else name, value) for name, value in request.headers + ] + method = request.method.decode("ascii") + target = request.url.target.decode("ascii") + lines = [f"{method} {target} {version}"] + [ + f"{name.decode('ascii')}: {value.decode('ascii')}" for name, value in headers + ] + return "\n".join(lines) + + +def format_response_headers( + http_version: bytes, + status: int, + reason_phrase: bytes | None, + headers: list[tuple[bytes, bytes]], +) -> str: + version = http_version.decode("ascii") + reason = ( + codes.get_reason_phrase(status) + if reason_phrase is None + else reason_phrase.decode("ascii") + ) + lines = [f"{version} {status} {reason}"] + [ + f"{name.decode('ascii')}: {value.decode('ascii')}" for name, value in headers + ] + return "\n".join(lines) + + +def print_request_headers(request: httpcore.Request, http2: bool = False) -> None: + console = rich.console.Console() + http_text = format_request_headers(request, http2=http2) + syntax = rich.syntax.Syntax(http_text, "http", theme="ansi_dark", word_wrap=True) + console.print(syntax) + syntax = rich.syntax.Syntax("", "http", theme="ansi_dark", word_wrap=True) + console.print(syntax) + + +def print_response_headers( + http_version: bytes, + status: int, + reason_phrase: bytes | None, + headers: list[tuple[bytes, bytes]], +) -> None: + console = rich.console.Console() + http_text = format_response_headers(http_version, status, reason_phrase, headers) + syntax = rich.syntax.Syntax(http_text, "http", theme="ansi_dark", word_wrap=True) + console.print(syntax) + syntax = rich.syntax.Syntax("", "http", theme="ansi_dark", word_wrap=True) + console.print(syntax) + + +def print_response(response: Response) -> None: + console = rich.console.Console() + lexer_name = get_lexer_for_response(response) + if lexer_name: + if lexer_name.lower() == "json": + try: + data = response.json() + text = json.dumps(data, indent=4) + except ValueError: # pragma: no cover + text = response.text + else: + text = response.text + + syntax = rich.syntax.Syntax(text, lexer_name, theme="ansi_dark", word_wrap=True) + console.print(syntax) + else: + console.print(f"<{len(response.content)} bytes of binary data>") + + +_PCTRTT = typing.Tuple[typing.Tuple[str, str], ...] +_PCTRTTT = typing.Tuple[_PCTRTT, ...] +_PeerCertRetDictType = typing.Dict[str, typing.Union[str, _PCTRTTT, _PCTRTT]] + + +def format_certificate(cert: _PeerCertRetDictType) -> str: # pragma: no cover + lines = [] + for key, value in cert.items(): + if isinstance(value, (list, tuple)): + lines.append(f"* {key}:") + for item in value: + if key in ("subject", "issuer"): + for sub_item in item: + lines.append(f"* {sub_item[0]}: {sub_item[1]!r}") + elif isinstance(item, tuple) and len(item) == 2: + lines.append(f"* {item[0]}: {item[1]!r}") + else: + lines.append(f"* {item!r}") + else: + lines.append(f"* {key}: {value!r}") + return "\n".join(lines) + + +def trace( + name: str, info: typing.Mapping[str, typing.Any], verbose: bool = False +) -> None: + console = rich.console.Console() + if name == "connection.connect_tcp.started" and verbose: + host = info["host"] + console.print(f"* Connecting to {host!r}") + elif name == "connection.connect_tcp.complete" and verbose: + stream = info["return_value"] + server_addr = stream.get_extra_info("server_addr") + console.print(f"* Connected to {server_addr[0]!r} on port {server_addr[1]}") + elif name == "connection.start_tls.complete" and verbose: # pragma: no cover + stream = info["return_value"] + ssl_object = stream.get_extra_info("ssl_object") + version = ssl_object.version() + cipher = ssl_object.cipher() + server_cert = ssl_object.getpeercert() + alpn = ssl_object.selected_alpn_protocol() + console.print(f"* SSL established using {version!r} / {cipher[0]!r}") + console.print(f"* Selected ALPN protocol: {alpn!r}") + if server_cert: + console.print("* Server certificate:") + console.print(format_certificate(server_cert)) + elif name == "http11.send_request_headers.started" and verbose: + request = info["request"] + print_request_headers(request, http2=False) + elif name == "http2.send_request_headers.started" and verbose: # pragma: no cover + request = info["request"] + print_request_headers(request, http2=True) + elif name == "http11.receive_response_headers.complete": + http_version, status, reason_phrase, headers = info["return_value"] + print_response_headers(http_version, status, reason_phrase, headers) + elif name == "http2.receive_response_headers.complete": # pragma: no cover + status, headers = info["return_value"] + http_version = b"HTTP/2" + reason_phrase = None + print_response_headers(http_version, status, reason_phrase, headers) + + +def download_response(response: Response, download: typing.BinaryIO) -> None: + console = rich.console.Console() + console.print() + content_length = response.headers.get("Content-Length") + with rich.progress.Progress( + "[progress.description]{task.description}", + "[progress.percentage]{task.percentage:>3.0f}%", + rich.progress.BarColumn(bar_width=None), + rich.progress.DownloadColumn(), + rich.progress.TransferSpeedColumn(), + ) as progress: + description = f"Downloading [bold]{rich.markup.escape(download.name)}" + download_task = progress.add_task( + description, + total=int(content_length or 0), + start=content_length is not None, + ) + for chunk in response.iter_bytes(): + download.write(chunk) + progress.update(download_task, completed=response.num_bytes_downloaded) + + +def validate_json( + ctx: click.Context, + param: click.Option | click.Parameter, + value: typing.Any, +) -> typing.Any: + if value is None: + return None + + try: + return json.loads(value) + except json.JSONDecodeError: # pragma: no cover + raise click.BadParameter("Not valid JSON") + + +def validate_auth( + ctx: click.Context, + param: click.Option | click.Parameter, + value: typing.Any, +) -> typing.Any: + if value == (None, None): + return None + + username, password = value + if password == "-": # pragma: no cover + password = click.prompt("Password", hide_input=True) + return (username, password) + + +def handle_help( + ctx: click.Context, + param: click.Option | click.Parameter, + value: typing.Any, +) -> None: + if not value or ctx.resilient_parsing: + return + + print_help() + ctx.exit() + + +@click.command(add_help_option=False) +@click.argument("url", type=str) +@click.option( + "--method", + "-m", + "method", + type=str, + help=( + "Request method, such as GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD. " + "[Default: GET, or POST if a request body is included]" + ), +) +@click.option( + "--params", + "-p", + "params", + type=(str, str), + multiple=True, + help="Query parameters to include in the request URL.", +) +@click.option( + "--content", + "-c", + "content", + type=str, + help="Byte content to include in the request body.", +) +@click.option( + "--data", + "-d", + "data", + type=(str, str), + multiple=True, + help="Form data to include in the request body.", +) +@click.option( + "--files", + "-f", + "files", + type=(str, click.File(mode="rb")), + multiple=True, + help="Form files to include in the request body.", +) +@click.option( + "--json", + "-j", + "json", + type=str, + callback=validate_json, + help="JSON data to include in the request body.", +) +@click.option( + "--headers", + "-h", + "headers", + type=(str, str), + multiple=True, + help="Include additional HTTP headers in the request.", +) +@click.option( + "--cookies", + "cookies", + type=(str, str), + multiple=True, + help="Cookies to include in the request.", +) +@click.option( + "--auth", + "auth", + type=(str, str), + default=(None, None), + callback=validate_auth, + help=( + "Username and password to include in the request. " + "Specify '-' for the password to use a password prompt. " + "Note that using --verbose/-v will expose the Authorization header, " + "including the password encoding in a trivially reversible format." + ), +) +@click.option( + "--proxy", + "proxy", + type=str, + default=None, + help="Send the request via a proxy. Should be the URL giving the proxy address.", +) +@click.option( + "--timeout", + "timeout", + type=float, + default=5.0, + help=( + "Timeout value to use for network operations, such as establishing the " + "connection, reading some data, etc... [Default: 5.0]" + ), +) +@click.option( + "--follow-redirects", + "follow_redirects", + is_flag=True, + default=False, + help="Automatically follow redirects.", +) +@click.option( + "--no-verify", + "verify", + is_flag=True, + default=True, + help="Disable SSL verification.", +) +@click.option( + "--http2", + "http2", + type=bool, + is_flag=True, + default=False, + help="Send the request using HTTP/2, if the remote server supports it.", +) +@click.option( + "--download", + type=click.File("wb"), + help="Save the response content as a file, rather than displaying it.", +) +@click.option( + "--verbose", + "-v", + type=bool, + is_flag=True, + default=False, + help="Verbose. Show request as well as response.", +) +@click.option( + "--help", + is_flag=True, + is_eager=True, + expose_value=False, + callback=handle_help, + help="Show this message and exit.", +) +def main( + url: str, + method: str, + params: list[tuple[str, str]], + content: str, + data: list[tuple[str, str]], + files: list[tuple[str, click.File]], + json: str, + headers: list[tuple[str, str]], + cookies: list[tuple[str, str]], + auth: tuple[str, str] | None, + proxy: str, + timeout: float, + follow_redirects: bool, + verify: bool, + http2: bool, + download: typing.BinaryIO | None, + verbose: bool, +) -> None: + """ + An HTTP command line client. + Sends a request and displays the response. + """ + if not method: + method = "POST" if content or data or files or json else "GET" + + try: + with Client(proxy=proxy, timeout=timeout, http2=http2, verify=verify) as client: + with client.stream( + method, + url, + params=list(params), + content=content, + data=dict(data), + files=files, # type: ignore + json=json, + headers=headers, + cookies=dict(cookies), + auth=auth, + follow_redirects=follow_redirects, + extensions={"trace": functools.partial(trace, verbose=verbose)}, + ) as response: + if download is not None: + download_response(response, download) + else: + response.read() + if response.content: + print_response(response) + + except RequestError as exc: + console = rich.console.Console() + console.print(f"[red]{type(exc).__name__}[/red]: {exc}") + sys.exit(1) + + sys.exit(0 if response.is_success else 1) diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/_models.py b/data/miniconda3/lib/python3.13/site-packages/httpx/_models.py new file mode 100644 index 0000000000000000000000000000000000000000..67d74bf86bfc80e22d9a4a3153572845accd9039 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/httpx/_models.py @@ -0,0 +1,1277 @@ +from __future__ import annotations + +import codecs +import datetime +import email.message +import json as jsonlib +import re +import typing +import urllib.request +from collections.abc import Mapping +from http.cookiejar import Cookie, CookieJar + +from ._content import ByteStream, UnattachedStream, encode_request, encode_response +from ._decoders import ( + SUPPORTED_DECODERS, + ByteChunker, + ContentDecoder, + IdentityDecoder, + LineDecoder, + MultiDecoder, + TextChunker, + TextDecoder, +) +from ._exceptions import ( + CookieConflict, + HTTPStatusError, + RequestNotRead, + ResponseNotRead, + StreamClosed, + StreamConsumed, + request_context, +) +from ._multipart import get_multipart_boundary_from_content_type +from ._status_codes import codes +from ._types import ( + AsyncByteStream, + CookieTypes, + HeaderTypes, + QueryParamTypes, + RequestContent, + RequestData, + RequestExtensions, + RequestFiles, + ResponseContent, + ResponseExtensions, + SyncByteStream, +) +from ._urls import URL +from ._utils import to_bytes_or_str, to_str + +__all__ = ["Cookies", "Headers", "Request", "Response"] + +SENSITIVE_HEADERS = {"authorization", "proxy-authorization"} + + +def _is_known_encoding(encoding: str) -> bool: + """ + Return `True` if `encoding` is a known codec. + """ + try: + codecs.lookup(encoding) + except LookupError: + return False + return True + + +def _normalize_header_key(key: str | bytes, encoding: str | None = None) -> bytes: + """ + Coerce str/bytes into a strictly byte-wise HTTP header key. + """ + return key if isinstance(key, bytes) else key.encode(encoding or "ascii") + + +def _normalize_header_value(value: str | bytes, encoding: str | None = None) -> bytes: + """ + Coerce str/bytes into a strictly byte-wise HTTP header value. + """ + if isinstance(value, bytes): + return value + if not isinstance(value, str): + raise TypeError(f"Header value must be str or bytes, not {type(value)}") + return value.encode(encoding or "ascii") + + +def _parse_content_type_charset(content_type: str) -> str | None: + # We used to use `cgi.parse_header()` here, but `cgi` became a dead battery. + # See: https://peps.python.org/pep-0594/#cgi + msg = email.message.Message() + msg["content-type"] = content_type + return msg.get_content_charset(failobj=None) + + +def _parse_header_links(value: str) -> list[dict[str, str]]: + """ + Returns a list of parsed link headers, for more info see: + https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link + The generic syntax of those is: + Link: < uri-reference >; param1=value1; param2="value2" + So for instance: + Link; '; type="image/jpeg",;' + would return + [ + {"url": "http:/.../front.jpeg", "type": "image/jpeg"}, + {"url": "http://.../back.jpeg"}, + ] + :param value: HTTP Link entity-header field + :return: list of parsed link headers + """ + links: list[dict[str, str]] = [] + replace_chars = " '\"" + value = value.strip(replace_chars) + if not value: + return links + for val in re.split(", *<", value): + try: + url, params = val.split(";", 1) + except ValueError: + url, params = val, "" + link = {"url": url.strip("<> '\"")} + for param in params.split(";"): + try: + key, value = param.split("=") + except ValueError: + break + link[key.strip(replace_chars)] = value.strip(replace_chars) + links.append(link) + return links + + +def _obfuscate_sensitive_headers( + items: typing.Iterable[tuple[typing.AnyStr, typing.AnyStr]], +) -> typing.Iterator[tuple[typing.AnyStr, typing.AnyStr]]: + for k, v in items: + if to_str(k.lower()) in SENSITIVE_HEADERS: + v = to_bytes_or_str("[secure]", match_type_of=v) + yield k, v + + +class Headers(typing.MutableMapping[str, str]): + """ + HTTP headers, as a case-insensitive multi-dict. + """ + + def __init__( + self, + headers: HeaderTypes | None = None, + encoding: str | None = None, + ) -> None: + self._list = [] # type: typing.List[typing.Tuple[bytes, bytes, bytes]] + + if isinstance(headers, Headers): + self._list = list(headers._list) + elif isinstance(headers, Mapping): + for k, v in headers.items(): + bytes_key = _normalize_header_key(k, encoding) + bytes_value = _normalize_header_value(v, encoding) + self._list.append((bytes_key, bytes_key.lower(), bytes_value)) + elif headers is not None: + for k, v in headers: + bytes_key = _normalize_header_key(k, encoding) + bytes_value = _normalize_header_value(v, encoding) + self._list.append((bytes_key, bytes_key.lower(), bytes_value)) + + self._encoding = encoding + + @property + def encoding(self) -> str: + """ + Header encoding is mandated as ascii, but we allow fallbacks to utf-8 + or iso-8859-1. + """ + if self._encoding is None: + for encoding in ["ascii", "utf-8"]: + for key, value in self.raw: + try: + key.decode(encoding) + value.decode(encoding) + except UnicodeDecodeError: + break + else: + # The else block runs if 'break' did not occur, meaning + # all values fitted the encoding. + self._encoding = encoding + break + else: + # The ISO-8859-1 encoding covers all 256 code points in a byte, + # so will never raise decode errors. + self._encoding = "iso-8859-1" + return self._encoding + + @encoding.setter + def encoding(self, value: str) -> None: + self._encoding = value + + @property + def raw(self) -> list[tuple[bytes, bytes]]: + """ + Returns a list of the raw header items, as byte pairs. + """ + return [(raw_key, value) for raw_key, _, value in self._list] + + def keys(self) -> typing.KeysView[str]: + return {key.decode(self.encoding): None for _, key, value in self._list}.keys() + + def values(self) -> typing.ValuesView[str]: + values_dict: dict[str, str] = {} + for _, key, value in self._list: + str_key = key.decode(self.encoding) + str_value = value.decode(self.encoding) + if str_key in values_dict: + values_dict[str_key] += f", {str_value}" + else: + values_dict[str_key] = str_value + return values_dict.values() + + def items(self) -> typing.ItemsView[str, str]: + """ + Return `(key, value)` items of headers. Concatenate headers + into a single comma separated value when a key occurs multiple times. + """ + values_dict: dict[str, str] = {} + for _, key, value in self._list: + str_key = key.decode(self.encoding) + str_value = value.decode(self.encoding) + if str_key in values_dict: + values_dict[str_key] += f", {str_value}" + else: + values_dict[str_key] = str_value + return values_dict.items() + + def multi_items(self) -> list[tuple[str, str]]: + """ + Return a list of `(key, value)` pairs of headers. Allow multiple + occurrences of the same key without concatenating into a single + comma separated value. + """ + return [ + (key.decode(self.encoding), value.decode(self.encoding)) + for _, key, value in self._list + ] + + def get(self, key: str, default: typing.Any = None) -> typing.Any: + """ + Return a header value. If multiple occurrences of the header occur + then concatenate them together with commas. + """ + try: + return self[key] + except KeyError: + return default + + def get_list(self, key: str, split_commas: bool = False) -> list[str]: + """ + Return a list of all header values for a given key. + If `split_commas=True` is passed, then any comma separated header + values are split into multiple return strings. + """ + get_header_key = key.lower().encode(self.encoding) + + values = [ + item_value.decode(self.encoding) + for _, item_key, item_value in self._list + if item_key.lower() == get_header_key + ] + + if not split_commas: + return values + + split_values = [] + for value in values: + split_values.extend([item.strip() for item in value.split(",")]) + return split_values + + def update(self, headers: HeaderTypes | None = None) -> None: # type: ignore + headers = Headers(headers) + for key in headers.keys(): + if key in self: + self.pop(key) + self._list.extend(headers._list) + + def copy(self) -> Headers: + return Headers(self, encoding=self.encoding) + + def __getitem__(self, key: str) -> str: + """ + Return a single header value. + + If there are multiple headers with the same key, then we concatenate + them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2 + """ + normalized_key = key.lower().encode(self.encoding) + + items = [ + header_value.decode(self.encoding) + for _, header_key, header_value in self._list + if header_key == normalized_key + ] + + if items: + return ", ".join(items) + + raise KeyError(key) + + def __setitem__(self, key: str, value: str) -> None: + """ + Set the header `key` to `value`, removing any duplicate entries. + Retains insertion order. + """ + set_key = key.encode(self._encoding or "utf-8") + set_value = value.encode(self._encoding or "utf-8") + lookup_key = set_key.lower() + + found_indexes = [ + idx + for idx, (_, item_key, _) in enumerate(self._list) + if item_key == lookup_key + ] + + for idx in reversed(found_indexes[1:]): + del self._list[idx] + + if found_indexes: + idx = found_indexes[0] + self._list[idx] = (set_key, lookup_key, set_value) + else: + self._list.append((set_key, lookup_key, set_value)) + + def __delitem__(self, key: str) -> None: + """ + Remove the header `key`. + """ + del_key = key.lower().encode(self.encoding) + + pop_indexes = [ + idx + for idx, (_, item_key, _) in enumerate(self._list) + if item_key.lower() == del_key + ] + + if not pop_indexes: + raise KeyError(key) + + for idx in reversed(pop_indexes): + del self._list[idx] + + def __contains__(self, key: typing.Any) -> bool: + header_key = key.lower().encode(self.encoding) + return header_key in [key for _, key, _ in self._list] + + def __iter__(self) -> typing.Iterator[typing.Any]: + return iter(self.keys()) + + def __len__(self) -> int: + return len(self._list) + + def __eq__(self, other: typing.Any) -> bool: + try: + other_headers = Headers(other) + except ValueError: + return False + + self_list = [(key, value) for _, key, value in self._list] + other_list = [(key, value) for _, key, value in other_headers._list] + return sorted(self_list) == sorted(other_list) + + def __repr__(self) -> str: + class_name = self.__class__.__name__ + + encoding_str = "" + if self.encoding != "ascii": + encoding_str = f", encoding={self.encoding!r}" + + as_list = list(_obfuscate_sensitive_headers(self.multi_items())) + as_dict = dict(as_list) + + no_duplicate_keys = len(as_dict) == len(as_list) + if no_duplicate_keys: + return f"{class_name}({as_dict!r}{encoding_str})" + return f"{class_name}({as_list!r}{encoding_str})" + + +class Request: + def __init__( + self, + method: str, + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + stream: SyncByteStream | AsyncByteStream | None = None, + extensions: RequestExtensions | None = None, + ) -> None: + self.method = method.upper() + self.url = URL(url) if params is None else URL(url, params=params) + self.headers = Headers(headers) + self.extensions = {} if extensions is None else dict(extensions) + + if cookies: + Cookies(cookies).set_cookie_header(self) + + if stream is None: + content_type: str | None = self.headers.get("content-type") + headers, stream = encode_request( + content=content, + data=data, + files=files, + json=json, + boundary=get_multipart_boundary_from_content_type( + content_type=content_type.encode(self.headers.encoding) + if content_type + else None + ), + ) + self._prepare(headers) + self.stream = stream + # Load the request body, except for streaming content. + if isinstance(stream, ByteStream): + self.read() + else: + # There's an important distinction between `Request(content=...)`, + # and `Request(stream=...)`. + # + # Using `content=...` implies automatically populated `Host` and content + # headers, of either `Content-Length: ...` or `Transfer-Encoding: chunked`. + # + # Using `stream=...` will not automatically include *any* + # auto-populated headers. + # + # As an end-user you don't really need `stream=...`. It's only + # useful when: + # + # * Preserving the request stream when copying requests, eg for redirects. + # * Creating request instances on the *server-side* of the transport API. + self.stream = stream + + def _prepare(self, default_headers: dict[str, str]) -> None: + for key, value in default_headers.items(): + # Ignore Transfer-Encoding if the Content-Length has been set explicitly. + if key.lower() == "transfer-encoding" and "Content-Length" in self.headers: + continue + self.headers.setdefault(key, value) + + auto_headers: list[tuple[bytes, bytes]] = [] + + has_host = "Host" in self.headers + has_content_length = ( + "Content-Length" in self.headers or "Transfer-Encoding" in self.headers + ) + + if not has_host and self.url.host: + auto_headers.append((b"Host", self.url.netloc)) + if not has_content_length and self.method in ("POST", "PUT", "PATCH"): + auto_headers.append((b"Content-Length", b"0")) + + self.headers = Headers(auto_headers + self.headers.raw) + + @property + def content(self) -> bytes: + if not hasattr(self, "_content"): + raise RequestNotRead() + return self._content + + def read(self) -> bytes: + """ + Read and return the request content. + """ + if not hasattr(self, "_content"): + assert isinstance(self.stream, typing.Iterable) + self._content = b"".join(self.stream) + if not isinstance(self.stream, ByteStream): + # If a streaming request has been read entirely into memory, then + # we can replace the stream with a raw bytes implementation, + # to ensure that any non-replayable streams can still be used. + self.stream = ByteStream(self._content) + return self._content + + async def aread(self) -> bytes: + """ + Read and return the request content. + """ + if not hasattr(self, "_content"): + assert isinstance(self.stream, typing.AsyncIterable) + self._content = b"".join([part async for part in self.stream]) + if not isinstance(self.stream, ByteStream): + # If a streaming request has been read entirely into memory, then + # we can replace the stream with a raw bytes implementation, + # to ensure that any non-replayable streams can still be used. + self.stream = ByteStream(self._content) + return self._content + + def __repr__(self) -> str: + class_name = self.__class__.__name__ + url = str(self.url) + return f"<{class_name}({self.method!r}, {url!r})>" + + def __getstate__(self) -> dict[str, typing.Any]: + return { + name: value + for name, value in self.__dict__.items() + if name not in ["extensions", "stream"] + } + + def __setstate__(self, state: dict[str, typing.Any]) -> None: + for name, value in state.items(): + setattr(self, name, value) + self.extensions = {} + self.stream = UnattachedStream() + + +class Response: + def __init__( + self, + status_code: int, + *, + headers: HeaderTypes | None = None, + content: ResponseContent | None = None, + text: str | None = None, + html: str | None = None, + json: typing.Any = None, + stream: SyncByteStream | AsyncByteStream | None = None, + request: Request | None = None, + extensions: ResponseExtensions | None = None, + history: list[Response] | None = None, + default_encoding: str | typing.Callable[[bytes], str] = "utf-8", + ) -> None: + self.status_code = status_code + self.headers = Headers(headers) + + self._request: Request | None = request + + # When follow_redirects=False and a redirect is received, + # the client will set `response.next_request`. + self.next_request: Request | None = None + + self.extensions = {} if extensions is None else dict(extensions) + self.history = [] if history is None else list(history) + + self.is_closed = False + self.is_stream_consumed = False + + self.default_encoding = default_encoding + + if stream is None: + headers, stream = encode_response(content, text, html, json) + self._prepare(headers) + self.stream = stream + if isinstance(stream, ByteStream): + # Load the response body, except for streaming content. + self.read() + else: + # There's an important distinction between `Response(content=...)`, + # and `Response(stream=...)`. + # + # Using `content=...` implies automatically populated content headers, + # of either `Content-Length: ...` or `Transfer-Encoding: chunked`. + # + # Using `stream=...` will not automatically include any content headers. + # + # As an end-user you don't really need `stream=...`. It's only + # useful when creating response instances having received a stream + # from the transport API. + self.stream = stream + + self._num_bytes_downloaded = 0 + + def _prepare(self, default_headers: dict[str, str]) -> None: + for key, value in default_headers.items(): + # Ignore Transfer-Encoding if the Content-Length has been set explicitly. + if key.lower() == "transfer-encoding" and "content-length" in self.headers: + continue + self.headers.setdefault(key, value) + + @property + def elapsed(self) -> datetime.timedelta: + """ + Returns the time taken for the complete request/response + cycle to complete. + """ + if not hasattr(self, "_elapsed"): + raise RuntimeError( + "'.elapsed' may only be accessed after the response " + "has been read or closed." + ) + return self._elapsed + + @elapsed.setter + def elapsed(self, elapsed: datetime.timedelta) -> None: + self._elapsed = elapsed + + @property + def request(self) -> Request: + """ + Returns the request instance associated to the current response. + """ + if self._request is None: + raise RuntimeError( + "The request instance has not been set on this response." + ) + return self._request + + @request.setter + def request(self, value: Request) -> None: + self._request = value + + @property + def http_version(self) -> str: + try: + http_version: bytes = self.extensions["http_version"] + except KeyError: + return "HTTP/1.1" + else: + return http_version.decode("ascii", errors="ignore") + + @property + def reason_phrase(self) -> str: + try: + reason_phrase: bytes = self.extensions["reason_phrase"] + except KeyError: + return codes.get_reason_phrase(self.status_code) + else: + return reason_phrase.decode("ascii", errors="ignore") + + @property + def url(self) -> URL: + """ + Returns the URL for which the request was made. + """ + return self.request.url + + @property + def content(self) -> bytes: + if not hasattr(self, "_content"): + raise ResponseNotRead() + return self._content + + @property + def text(self) -> str: + if not hasattr(self, "_text"): + content = self.content + if not content: + self._text = "" + else: + decoder = TextDecoder(encoding=self.encoding or "utf-8") + self._text = "".join([decoder.decode(self.content), decoder.flush()]) + return self._text + + @property + def encoding(self) -> str | None: + """ + Return an encoding to use for decoding the byte content into text. + The priority for determining this is given by... + + * `.encoding = <>` has been set explicitly. + * The encoding as specified by the charset parameter in the Content-Type header. + * The encoding as determined by `default_encoding`, which may either be + a string like "utf-8" indicating the encoding to use, or may be a callable + which enables charset autodetection. + """ + if not hasattr(self, "_encoding"): + encoding = self.charset_encoding + if encoding is None or not _is_known_encoding(encoding): + if isinstance(self.default_encoding, str): + encoding = self.default_encoding + elif hasattr(self, "_content"): + encoding = self.default_encoding(self._content) + self._encoding = encoding or "utf-8" + return self._encoding + + @encoding.setter + def encoding(self, value: str) -> None: + """ + Set the encoding to use for decoding the byte content into text. + + If the `text` attribute has been accessed, attempting to set the + encoding will throw a ValueError. + """ + if hasattr(self, "_text"): + raise ValueError( + "Setting encoding after `text` has been accessed is not allowed." + ) + self._encoding = value + + @property + def charset_encoding(self) -> str | None: + """ + Return the encoding, as specified by the Content-Type header. + """ + content_type = self.headers.get("Content-Type") + if content_type is None: + return None + + return _parse_content_type_charset(content_type) + + def _get_content_decoder(self) -> ContentDecoder: + """ + Returns a decoder instance which can be used to decode the raw byte + content, depending on the Content-Encoding used in the response. + """ + if not hasattr(self, "_decoder"): + decoders: list[ContentDecoder] = [] + values = self.headers.get_list("content-encoding", split_commas=True) + for value in values: + value = value.strip().lower() + try: + decoder_cls = SUPPORTED_DECODERS[value] + decoders.append(decoder_cls()) + except KeyError: + continue + + if len(decoders) == 1: + self._decoder = decoders[0] + elif len(decoders) > 1: + self._decoder = MultiDecoder(children=decoders) + else: + self._decoder = IdentityDecoder() + + return self._decoder + + @property + def is_informational(self) -> bool: + """ + A property which is `True` for 1xx status codes, `False` otherwise. + """ + return codes.is_informational(self.status_code) + + @property + def is_success(self) -> bool: + """ + A property which is `True` for 2xx status codes, `False` otherwise. + """ + return codes.is_success(self.status_code) + + @property + def is_redirect(self) -> bool: + """ + A property which is `True` for 3xx status codes, `False` otherwise. + + Note that not all responses with a 3xx status code indicate a URL redirect. + + Use `response.has_redirect_location` to determine responses with a properly + formed URL redirection. + """ + return codes.is_redirect(self.status_code) + + @property + def is_client_error(self) -> bool: + """ + A property which is `True` for 4xx status codes, `False` otherwise. + """ + return codes.is_client_error(self.status_code) + + @property + def is_server_error(self) -> bool: + """ + A property which is `True` for 5xx status codes, `False` otherwise. + """ + return codes.is_server_error(self.status_code) + + @property + def is_error(self) -> bool: + """ + A property which is `True` for 4xx and 5xx status codes, `False` otherwise. + """ + return codes.is_error(self.status_code) + + @property + def has_redirect_location(self) -> bool: + """ + Returns True for 3xx responses with a properly formed URL redirection, + `False` otherwise. + """ + return ( + self.status_code + in ( + # 301 (Cacheable redirect. Method may change to GET.) + codes.MOVED_PERMANENTLY, + # 302 (Uncacheable redirect. Method may change to GET.) + codes.FOUND, + # 303 (Client should make a GET or HEAD request.) + codes.SEE_OTHER, + # 307 (Equiv. 302, but retain method) + codes.TEMPORARY_REDIRECT, + # 308 (Equiv. 301, but retain method) + codes.PERMANENT_REDIRECT, + ) + and "Location" in self.headers + ) + + def raise_for_status(self) -> Response: + """ + Raise the `HTTPStatusError` if one occurred. + """ + request = self._request + if request is None: + raise RuntimeError( + "Cannot call `raise_for_status` as the request " + "instance has not been set on this response." + ) + + if self.is_success: + return self + + if self.has_redirect_location: + message = ( + "{error_type} '{0.status_code} {0.reason_phrase}' for url '{0.url}'\n" + "Redirect location: '{0.headers[location]}'\n" + "For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/{0.status_code}" + ) + else: + message = ( + "{error_type} '{0.status_code} {0.reason_phrase}' for url '{0.url}'\n" + "For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/{0.status_code}" + ) + + status_class = self.status_code // 100 + error_types = { + 1: "Informational response", + 3: "Redirect response", + 4: "Client error", + 5: "Server error", + } + error_type = error_types.get(status_class, "Invalid status code") + message = message.format(self, error_type=error_type) + raise HTTPStatusError(message, request=request, response=self) + + def json(self, **kwargs: typing.Any) -> typing.Any: + return jsonlib.loads(self.content, **kwargs) + + @property + def cookies(self) -> Cookies: + if not hasattr(self, "_cookies"): + self._cookies = Cookies() + self._cookies.extract_cookies(self) + return self._cookies + + @property + def links(self) -> dict[str | None, dict[str, str]]: + """ + Returns the parsed header links of the response, if any + """ + header = self.headers.get("link") + if header is None: + return {} + + return { + (link.get("rel") or link.get("url")): link + for link in _parse_header_links(header) + } + + @property + def num_bytes_downloaded(self) -> int: + return self._num_bytes_downloaded + + def __repr__(self) -> str: + return f"" + + def __getstate__(self) -> dict[str, typing.Any]: + return { + name: value + for name, value in self.__dict__.items() + if name not in ["extensions", "stream", "is_closed", "_decoder"] + } + + def __setstate__(self, state: dict[str, typing.Any]) -> None: + for name, value in state.items(): + setattr(self, name, value) + self.is_closed = True + self.extensions = {} + self.stream = UnattachedStream() + + def read(self) -> bytes: + """ + Read and return the response content. + """ + if not hasattr(self, "_content"): + self._content = b"".join(self.iter_bytes()) + return self._content + + def iter_bytes(self, chunk_size: int | None = None) -> typing.Iterator[bytes]: + """ + A byte-iterator over the decoded response content. + This allows us to handle gzip, deflate, brotli, and zstd encoded responses. + """ + if hasattr(self, "_content"): + chunk_size = len(self._content) if chunk_size is None else chunk_size + for i in range(0, len(self._content), max(chunk_size, 1)): + yield self._content[i : i + chunk_size] + else: + decoder = self._get_content_decoder() + chunker = ByteChunker(chunk_size=chunk_size) + with request_context(request=self._request): + for raw_bytes in self.iter_raw(): + decoded = decoder.decode(raw_bytes) + for chunk in chunker.decode(decoded): + yield chunk + decoded = decoder.flush() + for chunk in chunker.decode(decoded): + yield chunk # pragma: no cover + for chunk in chunker.flush(): + yield chunk + + def iter_text(self, chunk_size: int | None = None) -> typing.Iterator[str]: + """ + A str-iterator over the decoded response content + that handles both gzip, deflate, etc but also detects the content's + string encoding. + """ + decoder = TextDecoder(encoding=self.encoding or "utf-8") + chunker = TextChunker(chunk_size=chunk_size) + with request_context(request=self._request): + for byte_content in self.iter_bytes(): + text_content = decoder.decode(byte_content) + for chunk in chunker.decode(text_content): + yield chunk + text_content = decoder.flush() + for chunk in chunker.decode(text_content): + yield chunk # pragma: no cover + for chunk in chunker.flush(): + yield chunk + + def iter_lines(self) -> typing.Iterator[str]: + decoder = LineDecoder() + with request_context(request=self._request): + for text in self.iter_text(): + for line in decoder.decode(text): + yield line + for line in decoder.flush(): + yield line + + def iter_raw(self, chunk_size: int | None = None) -> typing.Iterator[bytes]: + """ + A byte-iterator over the raw response content. + """ + if self.is_stream_consumed: + raise StreamConsumed() + if self.is_closed: + raise StreamClosed() + if not isinstance(self.stream, SyncByteStream): + raise RuntimeError("Attempted to call a sync iterator on an async stream.") + + self.is_stream_consumed = True + self._num_bytes_downloaded = 0 + chunker = ByteChunker(chunk_size=chunk_size) + + with request_context(request=self._request): + for raw_stream_bytes in self.stream: + self._num_bytes_downloaded += len(raw_stream_bytes) + for chunk in chunker.decode(raw_stream_bytes): + yield chunk + + for chunk in chunker.flush(): + yield chunk + + self.close() + + def close(self) -> None: + """ + Close the response and release the connection. + Automatically called if the response body is read to completion. + """ + if not isinstance(self.stream, SyncByteStream): + raise RuntimeError("Attempted to call an sync close on an async stream.") + + if not self.is_closed: + self.is_closed = True + with request_context(request=self._request): + self.stream.close() + + async def aread(self) -> bytes: + """ + Read and return the response content. + """ + if not hasattr(self, "_content"): + self._content = b"".join([part async for part in self.aiter_bytes()]) + return self._content + + async def aiter_bytes( + self, chunk_size: int | None = None + ) -> typing.AsyncIterator[bytes]: + """ + A byte-iterator over the decoded response content. + This allows us to handle gzip, deflate, brotli, and zstd encoded responses. + """ + if hasattr(self, "_content"): + chunk_size = len(self._content) if chunk_size is None else chunk_size + for i in range(0, len(self._content), max(chunk_size, 1)): + yield self._content[i : i + chunk_size] + else: + decoder = self._get_content_decoder() + chunker = ByteChunker(chunk_size=chunk_size) + with request_context(request=self._request): + async for raw_bytes in self.aiter_raw(): + decoded = decoder.decode(raw_bytes) + for chunk in chunker.decode(decoded): + yield chunk + decoded = decoder.flush() + for chunk in chunker.decode(decoded): + yield chunk # pragma: no cover + for chunk in chunker.flush(): + yield chunk + + async def aiter_text( + self, chunk_size: int | None = None + ) -> typing.AsyncIterator[str]: + """ + A str-iterator over the decoded response content + that handles both gzip, deflate, etc but also detects the content's + string encoding. + """ + decoder = TextDecoder(encoding=self.encoding or "utf-8") + chunker = TextChunker(chunk_size=chunk_size) + with request_context(request=self._request): + async for byte_content in self.aiter_bytes(): + text_content = decoder.decode(byte_content) + for chunk in chunker.decode(text_content): + yield chunk + text_content = decoder.flush() + for chunk in chunker.decode(text_content): + yield chunk # pragma: no cover + for chunk in chunker.flush(): + yield chunk + + async def aiter_lines(self) -> typing.AsyncIterator[str]: + decoder = LineDecoder() + with request_context(request=self._request): + async for text in self.aiter_text(): + for line in decoder.decode(text): + yield line + for line in decoder.flush(): + yield line + + async def aiter_raw( + self, chunk_size: int | None = None + ) -> typing.AsyncIterator[bytes]: + """ + A byte-iterator over the raw response content. + """ + if self.is_stream_consumed: + raise StreamConsumed() + if self.is_closed: + raise StreamClosed() + if not isinstance(self.stream, AsyncByteStream): + raise RuntimeError("Attempted to call an async iterator on an sync stream.") + + self.is_stream_consumed = True + self._num_bytes_downloaded = 0 + chunker = ByteChunker(chunk_size=chunk_size) + + with request_context(request=self._request): + async for raw_stream_bytes in self.stream: + self._num_bytes_downloaded += len(raw_stream_bytes) + for chunk in chunker.decode(raw_stream_bytes): + yield chunk + + for chunk in chunker.flush(): + yield chunk + + await self.aclose() + + async def aclose(self) -> None: + """ + Close the response and release the connection. + Automatically called if the response body is read to completion. + """ + if not isinstance(self.stream, AsyncByteStream): + raise RuntimeError("Attempted to call an async close on an sync stream.") + + if not self.is_closed: + self.is_closed = True + with request_context(request=self._request): + await self.stream.aclose() + + +class Cookies(typing.MutableMapping[str, str]): + """ + HTTP Cookies, as a mutable mapping. + """ + + def __init__(self, cookies: CookieTypes | None = None) -> None: + if cookies is None or isinstance(cookies, dict): + self.jar = CookieJar() + if isinstance(cookies, dict): + for key, value in cookies.items(): + self.set(key, value) + elif isinstance(cookies, list): + self.jar = CookieJar() + for key, value in cookies: + self.set(key, value) + elif isinstance(cookies, Cookies): + self.jar = CookieJar() + for cookie in cookies.jar: + self.jar.set_cookie(cookie) + else: + self.jar = cookies + + def extract_cookies(self, response: Response) -> None: + """ + Loads any cookies based on the response `Set-Cookie` headers. + """ + urllib_response = self._CookieCompatResponse(response) + urllib_request = self._CookieCompatRequest(response.request) + + self.jar.extract_cookies(urllib_response, urllib_request) # type: ignore + + def set_cookie_header(self, request: Request) -> None: + """ + Sets an appropriate 'Cookie:' HTTP header on the `Request`. + """ + urllib_request = self._CookieCompatRequest(request) + self.jar.add_cookie_header(urllib_request) + + def set(self, name: str, value: str, domain: str = "", path: str = "/") -> None: + """ + Set a cookie value by name. May optionally include domain and path. + """ + kwargs = { + "version": 0, + "name": name, + "value": value, + "port": None, + "port_specified": False, + "domain": domain, + "domain_specified": bool(domain), + "domain_initial_dot": domain.startswith("."), + "path": path, + "path_specified": bool(path), + "secure": False, + "expires": None, + "discard": True, + "comment": None, + "comment_url": None, + "rest": {"HttpOnly": None}, + "rfc2109": False, + } + cookie = Cookie(**kwargs) # type: ignore + self.jar.set_cookie(cookie) + + def get( # type: ignore + self, + name: str, + default: str | None = None, + domain: str | None = None, + path: str | None = None, + ) -> str | None: + """ + Get a cookie by name. May optionally include domain and path + in order to specify exactly which cookie to retrieve. + """ + value = None + for cookie in self.jar: + if cookie.name == name: + if domain is None or cookie.domain == domain: + if path is None or cookie.path == path: + if value is not None: + message = f"Multiple cookies exist with name={name}" + raise CookieConflict(message) + value = cookie.value + + if value is None: + return default + return value + + def delete( + self, + name: str, + domain: str | None = None, + path: str | None = None, + ) -> None: + """ + Delete a cookie by name. May optionally include domain and path + in order to specify exactly which cookie to delete. + """ + if domain is not None and path is not None: + return self.jar.clear(domain, path, name) + + remove = [ + cookie + for cookie in self.jar + if cookie.name == name + and (domain is None or cookie.domain == domain) + and (path is None or cookie.path == path) + ] + + for cookie in remove: + self.jar.clear(cookie.domain, cookie.path, cookie.name) + + def clear(self, domain: str | None = None, path: str | None = None) -> None: + """ + Delete all cookies. Optionally include a domain and path in + order to only delete a subset of all the cookies. + """ + args = [] + if domain is not None: + args.append(domain) + if path is not None: + assert domain is not None + args.append(path) + self.jar.clear(*args) + + def update(self, cookies: CookieTypes | None = None) -> None: # type: ignore + cookies = Cookies(cookies) + for cookie in cookies.jar: + self.jar.set_cookie(cookie) + + def __setitem__(self, name: str, value: str) -> None: + return self.set(name, value) + + def __getitem__(self, name: str) -> str: + value = self.get(name) + if value is None: + raise KeyError(name) + return value + + def __delitem__(self, name: str) -> None: + return self.delete(name) + + def __len__(self) -> int: + return len(self.jar) + + def __iter__(self) -> typing.Iterator[str]: + return (cookie.name for cookie in self.jar) + + def __bool__(self) -> bool: + for _ in self.jar: + return True + return False + + def __repr__(self) -> str: + cookies_repr = ", ".join( + [ + f"" + for cookie in self.jar + ] + ) + + return f"" + + class _CookieCompatRequest(urllib.request.Request): + """ + Wraps a `Request` instance up in a compatibility interface suitable + for use with `CookieJar` operations. + """ + + def __init__(self, request: Request) -> None: + super().__init__( + url=str(request.url), + headers=dict(request.headers), + method=request.method, + ) + self.request = request + + def add_unredirected_header(self, key: str, value: str) -> None: + super().add_unredirected_header(key, value) + self.request.headers[key] = value + + class _CookieCompatResponse: + """ + Wraps a `Request` instance up in a compatibility interface suitable + for use with `CookieJar` operations. + """ + + def __init__(self, response: Response) -> None: + self.response = response + + def info(self) -> email.message.Message: + info = email.message.Message() + for key, value in self.response.headers.multi_items(): + # Note that setting `info[key]` here is an "append" operation, + # not a "replace" operation. + # https://docs.python.org/3/library/email.compat32-message.html#email.message.Message.__setitem__ + info[key] = value + return info diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/_multipart.py b/data/miniconda3/lib/python3.13/site-packages/httpx/_multipart.py new file mode 100644 index 0000000000000000000000000000000000000000..b4761af9b2cf384de5189269927d781a700dbe46 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/httpx/_multipart.py @@ -0,0 +1,300 @@ +from __future__ import annotations + +import io +import mimetypes +import os +import re +import typing +from pathlib import Path + +from ._types import ( + AsyncByteStream, + FileContent, + FileTypes, + RequestData, + RequestFiles, + SyncByteStream, +) +from ._utils import ( + peek_filelike_length, + primitive_value_to_str, + to_bytes, +) + +_HTML5_FORM_ENCODING_REPLACEMENTS = {'"': "%22", "\\": "\\\\"} +_HTML5_FORM_ENCODING_REPLACEMENTS.update( + {chr(c): "%{:02X}".format(c) for c in range(0x1F + 1) if c != 0x1B} +) +_HTML5_FORM_ENCODING_RE = re.compile( + r"|".join([re.escape(c) for c in _HTML5_FORM_ENCODING_REPLACEMENTS.keys()]) +) + + +def _format_form_param(name: str, value: str) -> bytes: + """ + Encode a name/value pair within a multipart form. + """ + + def replacer(match: typing.Match[str]) -> str: + return _HTML5_FORM_ENCODING_REPLACEMENTS[match.group(0)] + + value = _HTML5_FORM_ENCODING_RE.sub(replacer, value) + return f'{name}="{value}"'.encode() + + +def _guess_content_type(filename: str | None) -> str | None: + """ + Guesses the mimetype based on a filename. Defaults to `application/octet-stream`. + + Returns `None` if `filename` is `None` or empty. + """ + if filename: + return mimetypes.guess_type(filename)[0] or "application/octet-stream" + return None + + +def get_multipart_boundary_from_content_type( + content_type: bytes | None, +) -> bytes | None: + if not content_type or not content_type.startswith(b"multipart/form-data"): + return None + # parse boundary according to + # https://www.rfc-editor.org/rfc/rfc2046#section-5.1.1 + if b";" in content_type: + for section in content_type.split(b";"): + if section.strip().lower().startswith(b"boundary="): + return section.strip()[len(b"boundary=") :].strip(b'"') + return None + + +class DataField: + """ + A single form field item, within a multipart form field. + """ + + def __init__(self, name: str, value: str | bytes | int | float | None) -> None: + if not isinstance(name, str): + raise TypeError( + f"Invalid type for name. Expected str, got {type(name)}: {name!r}" + ) + if value is not None and not isinstance(value, (str, bytes, int, float)): + raise TypeError( + "Invalid type for value. Expected primitive type," + f" got {type(value)}: {value!r}" + ) + self.name = name + self.value: str | bytes = ( + value if isinstance(value, bytes) else primitive_value_to_str(value) + ) + + def render_headers(self) -> bytes: + if not hasattr(self, "_headers"): + name = _format_form_param("name", self.name) + self._headers = b"".join( + [b"Content-Disposition: form-data; ", name, b"\r\n\r\n"] + ) + + return self._headers + + def render_data(self) -> bytes: + if not hasattr(self, "_data"): + self._data = to_bytes(self.value) + + return self._data + + def get_length(self) -> int: + headers = self.render_headers() + data = self.render_data() + return len(headers) + len(data) + + def render(self) -> typing.Iterator[bytes]: + yield self.render_headers() + yield self.render_data() + + +class FileField: + """ + A single file field item, within a multipart form field. + """ + + CHUNK_SIZE = 64 * 1024 + + def __init__(self, name: str, value: FileTypes) -> None: + self.name = name + + fileobj: FileContent + + headers: dict[str, str] = {} + content_type: str | None = None + + # This large tuple based API largely mirror's requests' API + # It would be good to think of better APIs for this that we could + # include in httpx 2.0 since variable length tuples(especially of 4 elements) + # are quite unwieldly + if isinstance(value, tuple): + if len(value) == 2: + # neither the 3rd parameter (content_type) nor the 4th (headers) + # was included + filename, fileobj = value + elif len(value) == 3: + filename, fileobj, content_type = value + else: + # all 4 parameters included + filename, fileobj, content_type, headers = value # type: ignore + else: + filename = Path(str(getattr(value, "name", "upload"))).name + fileobj = value + + if content_type is None: + content_type = _guess_content_type(filename) + + has_content_type_header = any("content-type" in key.lower() for key in headers) + if content_type is not None and not has_content_type_header: + # note that unlike requests, we ignore the content_type provided in the 3rd + # tuple element if it is also included in the headers requests does + # the opposite (it overwrites the headerwith the 3rd tuple element) + headers["Content-Type"] = content_type + + if isinstance(fileobj, io.StringIO): + raise TypeError( + "Multipart file uploads require 'io.BytesIO', not 'io.StringIO'." + ) + if isinstance(fileobj, io.TextIOBase): + raise TypeError( + "Multipart file uploads must be opened in binary mode, not text mode." + ) + + self.filename = filename + self.file = fileobj + self.headers = headers + + def get_length(self) -> int | None: + headers = self.render_headers() + + if isinstance(self.file, (str, bytes)): + return len(headers) + len(to_bytes(self.file)) + + file_length = peek_filelike_length(self.file) + + # If we can't determine the filesize without reading it into memory, + # then return `None` here, to indicate an unknown file length. + if file_length is None: + return None + + return len(headers) + file_length + + def render_headers(self) -> bytes: + if not hasattr(self, "_headers"): + parts = [ + b"Content-Disposition: form-data; ", + _format_form_param("name", self.name), + ] + if self.filename: + filename = _format_form_param("filename", self.filename) + parts.extend([b"; ", filename]) + for header_name, header_value in self.headers.items(): + key, val = f"\r\n{header_name}: ".encode(), header_value.encode() + parts.extend([key, val]) + parts.append(b"\r\n\r\n") + self._headers = b"".join(parts) + + return self._headers + + def render_data(self) -> typing.Iterator[bytes]: + if isinstance(self.file, (str, bytes)): + yield to_bytes(self.file) + return + + if hasattr(self.file, "seek"): + try: + self.file.seek(0) + except io.UnsupportedOperation: + pass + + chunk = self.file.read(self.CHUNK_SIZE) + while chunk: + yield to_bytes(chunk) + chunk = self.file.read(self.CHUNK_SIZE) + + def render(self) -> typing.Iterator[bytes]: + yield self.render_headers() + yield from self.render_data() + + +class MultipartStream(SyncByteStream, AsyncByteStream): + """ + Request content as streaming multipart encoded form data. + """ + + def __init__( + self, + data: RequestData, + files: RequestFiles, + boundary: bytes | None = None, + ) -> None: + if boundary is None: + boundary = os.urandom(16).hex().encode("ascii") + + self.boundary = boundary + self.content_type = "multipart/form-data; boundary=%s" % boundary.decode( + "ascii" + ) + self.fields = list(self._iter_fields(data, files)) + + def _iter_fields( + self, data: RequestData, files: RequestFiles + ) -> typing.Iterator[FileField | DataField]: + for name, value in data.items(): + if isinstance(value, (tuple, list)): + for item in value: + yield DataField(name=name, value=item) + else: + yield DataField(name=name, value=value) + + file_items = files.items() if isinstance(files, typing.Mapping) else files + for name, value in file_items: + yield FileField(name=name, value=value) + + def iter_chunks(self) -> typing.Iterator[bytes]: + for field in self.fields: + yield b"--%s\r\n" % self.boundary + yield from field.render() + yield b"\r\n" + yield b"--%s--\r\n" % self.boundary + + def get_content_length(self) -> int | None: + """ + Return the length of the multipart encoded content, or `None` if + any of the files have a length that cannot be determined upfront. + """ + boundary_length = len(self.boundary) + length = 0 + + for field in self.fields: + field_length = field.get_length() + if field_length is None: + return None + + length += 2 + boundary_length + 2 # b"--{boundary}\r\n" + length += field_length + length += 2 # b"\r\n" + + length += 2 + boundary_length + 4 # b"--{boundary}--\r\n" + return length + + # Content stream interface. + + def get_headers(self) -> dict[str, str]: + content_length = self.get_content_length() + content_type = self.content_type + if content_length is None: + return {"Transfer-Encoding": "chunked", "Content-Type": content_type} + return {"Content-Length": str(content_length), "Content-Type": content_type} + + def __iter__(self) -> typing.Iterator[bytes]: + for chunk in self.iter_chunks(): + yield chunk + + async def __aiter__(self) -> typing.AsyncIterator[bytes]: + for chunk in self.iter_chunks(): + yield chunk diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/_status_codes.py b/data/miniconda3/lib/python3.13/site-packages/httpx/_status_codes.py new file mode 100644 index 0000000000000000000000000000000000000000..133a6231a5b53fd2f073799ca1bd07c50abe40ae --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/httpx/_status_codes.py @@ -0,0 +1,162 @@ +from __future__ import annotations + +from enum import IntEnum + +__all__ = ["codes"] + + +class codes(IntEnum): + """HTTP status codes and reason phrases + + Status codes from the following RFCs are all observed: + + * RFC 7231: Hypertext Transfer Protocol (HTTP/1.1), obsoletes 2616 + * RFC 6585: Additional HTTP Status Codes + * RFC 3229: Delta encoding in HTTP + * RFC 4918: HTTP Extensions for WebDAV, obsoletes 2518 + * RFC 5842: Binding Extensions to WebDAV + * RFC 7238: Permanent Redirect + * RFC 2295: Transparent Content Negotiation in HTTP + * RFC 2774: An HTTP Extension Framework + * RFC 7540: Hypertext Transfer Protocol Version 2 (HTTP/2) + * RFC 2324: Hyper Text Coffee Pot Control Protocol (HTCPCP/1.0) + * RFC 7725: An HTTP Status Code to Report Legal Obstacles + * RFC 8297: An HTTP Status Code for Indicating Hints + * RFC 8470: Using Early Data in HTTP + """ + + def __new__(cls, value: int, phrase: str = "") -> codes: + obj = int.__new__(cls, value) + obj._value_ = value + + obj.phrase = phrase # type: ignore[attr-defined] + return obj + + def __str__(self) -> str: + return str(self.value) + + @classmethod + def get_reason_phrase(cls, value: int) -> str: + try: + return codes(value).phrase # type: ignore + except ValueError: + return "" + + @classmethod + def is_informational(cls, value: int) -> bool: + """ + Returns `True` for 1xx status codes, `False` otherwise. + """ + return 100 <= value <= 199 + + @classmethod + def is_success(cls, value: int) -> bool: + """ + Returns `True` for 2xx status codes, `False` otherwise. + """ + return 200 <= value <= 299 + + @classmethod + def is_redirect(cls, value: int) -> bool: + """ + Returns `True` for 3xx status codes, `False` otherwise. + """ + return 300 <= value <= 399 + + @classmethod + def is_client_error(cls, value: int) -> bool: + """ + Returns `True` for 4xx status codes, `False` otherwise. + """ + return 400 <= value <= 499 + + @classmethod + def is_server_error(cls, value: int) -> bool: + """ + Returns `True` for 5xx status codes, `False` otherwise. + """ + return 500 <= value <= 599 + + @classmethod + def is_error(cls, value: int) -> bool: + """ + Returns `True` for 4xx or 5xx status codes, `False` otherwise. + """ + return 400 <= value <= 599 + + # informational + CONTINUE = 100, "Continue" + SWITCHING_PROTOCOLS = 101, "Switching Protocols" + PROCESSING = 102, "Processing" + EARLY_HINTS = 103, "Early Hints" + + # success + OK = 200, "OK" + CREATED = 201, "Created" + ACCEPTED = 202, "Accepted" + NON_AUTHORITATIVE_INFORMATION = 203, "Non-Authoritative Information" + NO_CONTENT = 204, "No Content" + RESET_CONTENT = 205, "Reset Content" + PARTIAL_CONTENT = 206, "Partial Content" + MULTI_STATUS = 207, "Multi-Status" + ALREADY_REPORTED = 208, "Already Reported" + IM_USED = 226, "IM Used" + + # redirection + MULTIPLE_CHOICES = 300, "Multiple Choices" + MOVED_PERMANENTLY = 301, "Moved Permanently" + FOUND = 302, "Found" + SEE_OTHER = 303, "See Other" + NOT_MODIFIED = 304, "Not Modified" + USE_PROXY = 305, "Use Proxy" + TEMPORARY_REDIRECT = 307, "Temporary Redirect" + PERMANENT_REDIRECT = 308, "Permanent Redirect" + + # client error + BAD_REQUEST = 400, "Bad Request" + UNAUTHORIZED = 401, "Unauthorized" + PAYMENT_REQUIRED = 402, "Payment Required" + FORBIDDEN = 403, "Forbidden" + NOT_FOUND = 404, "Not Found" + METHOD_NOT_ALLOWED = 405, "Method Not Allowed" + NOT_ACCEPTABLE = 406, "Not Acceptable" + PROXY_AUTHENTICATION_REQUIRED = 407, "Proxy Authentication Required" + REQUEST_TIMEOUT = 408, "Request Timeout" + CONFLICT = 409, "Conflict" + GONE = 410, "Gone" + LENGTH_REQUIRED = 411, "Length Required" + PRECONDITION_FAILED = 412, "Precondition Failed" + REQUEST_ENTITY_TOO_LARGE = 413, "Request Entity Too Large" + REQUEST_URI_TOO_LONG = 414, "Request-URI Too Long" + UNSUPPORTED_MEDIA_TYPE = 415, "Unsupported Media Type" + REQUESTED_RANGE_NOT_SATISFIABLE = 416, "Requested Range Not Satisfiable" + EXPECTATION_FAILED = 417, "Expectation Failed" + IM_A_TEAPOT = 418, "I'm a teapot" + MISDIRECTED_REQUEST = 421, "Misdirected Request" + UNPROCESSABLE_ENTITY = 422, "Unprocessable Entity" + LOCKED = 423, "Locked" + FAILED_DEPENDENCY = 424, "Failed Dependency" + TOO_EARLY = 425, "Too Early" + UPGRADE_REQUIRED = 426, "Upgrade Required" + PRECONDITION_REQUIRED = 428, "Precondition Required" + TOO_MANY_REQUESTS = 429, "Too Many Requests" + REQUEST_HEADER_FIELDS_TOO_LARGE = 431, "Request Header Fields Too Large" + UNAVAILABLE_FOR_LEGAL_REASONS = 451, "Unavailable For Legal Reasons" + + # server errors + INTERNAL_SERVER_ERROR = 500, "Internal Server Error" + NOT_IMPLEMENTED = 501, "Not Implemented" + BAD_GATEWAY = 502, "Bad Gateway" + SERVICE_UNAVAILABLE = 503, "Service Unavailable" + GATEWAY_TIMEOUT = 504, "Gateway Timeout" + HTTP_VERSION_NOT_SUPPORTED = 505, "HTTP Version Not Supported" + VARIANT_ALSO_NEGOTIATES = 506, "Variant Also Negotiates" + INSUFFICIENT_STORAGE = 507, "Insufficient Storage" + LOOP_DETECTED = 508, "Loop Detected" + NOT_EXTENDED = 510, "Not Extended" + NETWORK_AUTHENTICATION_REQUIRED = 511, "Network Authentication Required" + + +# Include lower-case styles for `requests` compatibility. +for code in codes: + setattr(codes, code._name_.lower(), int(code)) diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/_types.py b/data/miniconda3/lib/python3.13/site-packages/httpx/_types.py new file mode 100644 index 0000000000000000000000000000000000000000..704dfdffc8ba61eb913fa918072381e410b23c00 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/httpx/_types.py @@ -0,0 +1,114 @@ +""" +Type definitions for type checking purposes. +""" + +from http.cookiejar import CookieJar +from typing import ( + IO, + TYPE_CHECKING, + Any, + AsyncIterable, + AsyncIterator, + Callable, + Dict, + Iterable, + Iterator, + List, + Mapping, + Optional, + Sequence, + Tuple, + Union, +) + +if TYPE_CHECKING: # pragma: no cover + from ._auth import Auth # noqa: F401 + from ._config import Proxy, Timeout # noqa: F401 + from ._models import Cookies, Headers, Request # noqa: F401 + from ._urls import URL, QueryParams # noqa: F401 + + +PrimitiveData = Optional[Union[str, int, float, bool]] + +URLTypes = Union["URL", str] + +QueryParamTypes = Union[ + "QueryParams", + Mapping[str, Union[PrimitiveData, Sequence[PrimitiveData]]], + List[Tuple[str, PrimitiveData]], + Tuple[Tuple[str, PrimitiveData], ...], + str, + bytes, +] + +HeaderTypes = Union[ + "Headers", + Mapping[str, str], + Mapping[bytes, bytes], + Sequence[Tuple[str, str]], + Sequence[Tuple[bytes, bytes]], +] + +CookieTypes = Union["Cookies", CookieJar, Dict[str, str], List[Tuple[str, str]]] + +TimeoutTypes = Union[ + Optional[float], + Tuple[Optional[float], Optional[float], Optional[float], Optional[float]], + "Timeout", +] +ProxyTypes = Union["URL", str, "Proxy"] +CertTypes = Union[str, Tuple[str, str], Tuple[str, str, str]] + +AuthTypes = Union[ + Tuple[Union[str, bytes], Union[str, bytes]], + Callable[["Request"], "Request"], + "Auth", +] + +RequestContent = Union[str, bytes, Iterable[bytes], AsyncIterable[bytes]] +ResponseContent = Union[str, bytes, Iterable[bytes], AsyncIterable[bytes]] +ResponseExtensions = Mapping[str, Any] + +RequestData = Mapping[str, Any] + +FileContent = Union[IO[bytes], bytes, str] +FileTypes = Union[ + # file (or bytes) + FileContent, + # (filename, file (or bytes)) + Tuple[Optional[str], FileContent], + # (filename, file (or bytes), content_type) + Tuple[Optional[str], FileContent, Optional[str]], + # (filename, file (or bytes), content_type, headers) + Tuple[Optional[str], FileContent, Optional[str], Mapping[str, str]], +] +RequestFiles = Union[Mapping[str, FileTypes], Sequence[Tuple[str, FileTypes]]] + +RequestExtensions = Mapping[str, Any] + +__all__ = ["AsyncByteStream", "SyncByteStream"] + + +class SyncByteStream: + def __iter__(self) -> Iterator[bytes]: + raise NotImplementedError( + "The '__iter__' method must be implemented." + ) # pragma: no cover + yield b"" # pragma: no cover + + def close(self) -> None: + """ + Subclasses can override this method to release any network resources + after a request/response cycle is complete. + """ + + +class AsyncByteStream: + async def __aiter__(self) -> AsyncIterator[bytes]: + raise NotImplementedError( + "The '__aiter__' method must be implemented." + ) # pragma: no cover + yield b"" # pragma: no cover + + async def aclose(self) -> None: + pass diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/_urlparse.py b/data/miniconda3/lib/python3.13/site-packages/httpx/_urlparse.py new file mode 100644 index 0000000000000000000000000000000000000000..bf190fd560ee4fc8a11af371a15fc5f1dc284d34 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/httpx/_urlparse.py @@ -0,0 +1,527 @@ +""" +An implementation of `urlparse` that provides URL validation and normalization +as described by RFC3986. + +We rely on this implementation rather than the one in Python's stdlib, because: + +* It provides more complete URL validation. +* It properly differentiates between an empty querystring and an absent querystring, + to distinguish URLs with a trailing '?'. +* It handles scheme, hostname, port, and path normalization. +* It supports IDNA hostnames, normalizing them to their encoded form. +* The API supports passing individual components, as well as the complete URL string. + +Previously we relied on the excellent `rfc3986` package to handle URL parsing and +validation, but this module provides a simpler alternative, with less indirection +required. +""" + +from __future__ import annotations + +import ipaddress +import re +import typing + +import idna + +from ._exceptions import InvalidURL + +MAX_URL_LENGTH = 65536 + +# https://datatracker.ietf.org/doc/html/rfc3986.html#section-2.3 +UNRESERVED_CHARACTERS = ( + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~" +) +SUB_DELIMS = "!$&'()*+,;=" + +PERCENT_ENCODED_REGEX = re.compile("%[A-Fa-f0-9]{2}") + +# https://url.spec.whatwg.org/#percent-encoded-bytes + +# The fragment percent-encode set is the C0 control percent-encode set +# and U+0020 SPACE, U+0022 ("), U+003C (<), U+003E (>), and U+0060 (`). +FRAG_SAFE = "".join( + [chr(i) for i in range(0x20, 0x7F) if i not in (0x20, 0x22, 0x3C, 0x3E, 0x60)] +) + +# The query percent-encode set is the C0 control percent-encode set +# and U+0020 SPACE, U+0022 ("), U+0023 (#), U+003C (<), and U+003E (>). +QUERY_SAFE = "".join( + [chr(i) for i in range(0x20, 0x7F) if i not in (0x20, 0x22, 0x23, 0x3C, 0x3E)] +) + +# The path percent-encode set is the query percent-encode set +# and U+003F (?), U+0060 (`), U+007B ({), and U+007D (}). +PATH_SAFE = "".join( + [ + chr(i) + for i in range(0x20, 0x7F) + if i not in (0x20, 0x22, 0x23, 0x3C, 0x3E) + (0x3F, 0x60, 0x7B, 0x7D) + ] +) + +# The userinfo percent-encode set is the path percent-encode set +# and U+002F (/), U+003A (:), U+003B (;), U+003D (=), U+0040 (@), +# U+005B ([) to U+005E (^), inclusive, and U+007C (|). +USERNAME_SAFE = "".join( + [ + chr(i) + for i in range(0x20, 0x7F) + if i + not in (0x20, 0x22, 0x23, 0x3C, 0x3E) + + (0x3F, 0x60, 0x7B, 0x7D) + + (0x2F, 0x3A, 0x3B, 0x3D, 0x40, 0x5B, 0x5C, 0x5D, 0x5E, 0x7C) + ] +) +PASSWORD_SAFE = "".join( + [ + chr(i) + for i in range(0x20, 0x7F) + if i + not in (0x20, 0x22, 0x23, 0x3C, 0x3E) + + (0x3F, 0x60, 0x7B, 0x7D) + + (0x2F, 0x3A, 0x3B, 0x3D, 0x40, 0x5B, 0x5C, 0x5D, 0x5E, 0x7C) + ] +) +# Note... The terminology 'userinfo' percent-encode set in the WHATWG document +# is used for the username and password quoting. For the joint userinfo component +# we remove U+003A (:) from the safe set. +USERINFO_SAFE = "".join( + [ + chr(i) + for i in range(0x20, 0x7F) + if i + not in (0x20, 0x22, 0x23, 0x3C, 0x3E) + + (0x3F, 0x60, 0x7B, 0x7D) + + (0x2F, 0x3B, 0x3D, 0x40, 0x5B, 0x5C, 0x5D, 0x5E, 0x7C) + ] +) + + +# {scheme}: (optional) +# //{authority} (optional) +# {path} +# ?{query} (optional) +# #{fragment} (optional) +URL_REGEX = re.compile( + ( + r"(?:(?P{scheme}):)?" + r"(?://(?P{authority}))?" + r"(?P{path})" + r"(?:\?(?P{query}))?" + r"(?:#(?P{fragment}))?" + ).format( + scheme="([a-zA-Z][a-zA-Z0-9+.-]*)?", + authority="[^/?#]*", + path="[^?#]*", + query="[^#]*", + fragment=".*", + ) +) + +# {userinfo}@ (optional) +# {host} +# :{port} (optional) +AUTHORITY_REGEX = re.compile( + ( + r"(?:(?P{userinfo})@)?" r"(?P{host})" r":?(?P{port})?" + ).format( + userinfo=".*", # Any character sequence. + host="(\\[.*\\]|[^:@]*)", # Either any character sequence excluding ':' or '@', + # or an IPv6 address enclosed within square brackets. + port=".*", # Any character sequence. + ) +) + + +# If we call urlparse with an individual component, then we need to regex +# validate that component individually. +# Note that we're duplicating the same strings as above. Shock! Horror!! +COMPONENT_REGEX = { + "scheme": re.compile("([a-zA-Z][a-zA-Z0-9+.-]*)?"), + "authority": re.compile("[^/?#]*"), + "path": re.compile("[^?#]*"), + "query": re.compile("[^#]*"), + "fragment": re.compile(".*"), + "userinfo": re.compile("[^@]*"), + "host": re.compile("(\\[.*\\]|[^:]*)"), + "port": re.compile(".*"), +} + + +# We use these simple regexs as a first pass before handing off to +# the stdlib 'ipaddress' module for IP address validation. +IPv4_STYLE_HOSTNAME = re.compile(r"^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$") +IPv6_STYLE_HOSTNAME = re.compile(r"^\[.*\]$") + + +class ParseResult(typing.NamedTuple): + scheme: str + userinfo: str + host: str + port: int | None + path: str + query: str | None + fragment: str | None + + @property + def authority(self) -> str: + return "".join( + [ + f"{self.userinfo}@" if self.userinfo else "", + f"[{self.host}]" if ":" in self.host else self.host, + f":{self.port}" if self.port is not None else "", + ] + ) + + @property + def netloc(self) -> str: + return "".join( + [ + f"[{self.host}]" if ":" in self.host else self.host, + f":{self.port}" if self.port is not None else "", + ] + ) + + def copy_with(self, **kwargs: str | None) -> ParseResult: + if not kwargs: + return self + + defaults = { + "scheme": self.scheme, + "authority": self.authority, + "path": self.path, + "query": self.query, + "fragment": self.fragment, + } + defaults.update(kwargs) + return urlparse("", **defaults) + + def __str__(self) -> str: + authority = self.authority + return "".join( + [ + f"{self.scheme}:" if self.scheme else "", + f"//{authority}" if authority else "", + self.path, + f"?{self.query}" if self.query is not None else "", + f"#{self.fragment}" if self.fragment is not None else "", + ] + ) + + +def urlparse(url: str = "", **kwargs: str | None) -> ParseResult: + # Initial basic checks on allowable URLs. + # --------------------------------------- + + # Hard limit the maximum allowable URL length. + if len(url) > MAX_URL_LENGTH: + raise InvalidURL("URL too long") + + # If a URL includes any ASCII control characters including \t, \r, \n, + # then treat it as invalid. + if any(char.isascii() and not char.isprintable() for char in url): + char = next(char for char in url if char.isascii() and not char.isprintable()) + idx = url.find(char) + error = ( + f"Invalid non-printable ASCII character in URL, {char!r} at position {idx}." + ) + raise InvalidURL(error) + + # Some keyword arguments require special handling. + # ------------------------------------------------ + + # Coerce "port" to a string, if it is provided as an integer. + if "port" in kwargs: + port = kwargs["port"] + kwargs["port"] = str(port) if isinstance(port, int) else port + + # Replace "netloc" with "host and "port". + if "netloc" in kwargs: + netloc = kwargs.pop("netloc") or "" + kwargs["host"], _, kwargs["port"] = netloc.partition(":") + + # Replace "username" and/or "password" with "userinfo". + if "username" in kwargs or "password" in kwargs: + username = quote(kwargs.pop("username", "") or "", safe=USERNAME_SAFE) + password = quote(kwargs.pop("password", "") or "", safe=PASSWORD_SAFE) + kwargs["userinfo"] = f"{username}:{password}" if password else username + + # Replace "raw_path" with "path" and "query". + if "raw_path" in kwargs: + raw_path = kwargs.pop("raw_path") or "" + kwargs["path"], seperator, kwargs["query"] = raw_path.partition("?") + if not seperator: + kwargs["query"] = None + + # Ensure that IPv6 "host" addresses are always escaped with "[...]". + if "host" in kwargs: + host = kwargs.get("host") or "" + if ":" in host and not (host.startswith("[") and host.endswith("]")): + kwargs["host"] = f"[{host}]" + + # If any keyword arguments are provided, ensure they are valid. + # ------------------------------------------------------------- + + for key, value in kwargs.items(): + if value is not None: + if len(value) > MAX_URL_LENGTH: + raise InvalidURL(f"URL component '{key}' too long") + + # If a component includes any ASCII control characters including \t, \r, \n, + # then treat it as invalid. + if any(char.isascii() and not char.isprintable() for char in value): + char = next( + char for char in value if char.isascii() and not char.isprintable() + ) + idx = value.find(char) + error = ( + f"Invalid non-printable ASCII character in URL {key} component, " + f"{char!r} at position {idx}." + ) + raise InvalidURL(error) + + # Ensure that keyword arguments match as a valid regex. + if not COMPONENT_REGEX[key].fullmatch(value): + raise InvalidURL(f"Invalid URL component '{key}'") + + # The URL_REGEX will always match, but may have empty components. + url_match = URL_REGEX.match(url) + assert url_match is not None + url_dict = url_match.groupdict() + + # * 'scheme', 'authority', and 'path' may be empty strings. + # * 'query' may be 'None', indicating no trailing "?" portion. + # Any string including the empty string, indicates a trailing "?". + # * 'fragment' may be 'None', indicating no trailing "#" portion. + # Any string including the empty string, indicates a trailing "#". + scheme = kwargs.get("scheme", url_dict["scheme"]) or "" + authority = kwargs.get("authority", url_dict["authority"]) or "" + path = kwargs.get("path", url_dict["path"]) or "" + query = kwargs.get("query", url_dict["query"]) + frag = kwargs.get("fragment", url_dict["fragment"]) + + # The AUTHORITY_REGEX will always match, but may have empty components. + authority_match = AUTHORITY_REGEX.match(authority) + assert authority_match is not None + authority_dict = authority_match.groupdict() + + # * 'userinfo' and 'host' may be empty strings. + # * 'port' may be 'None'. + userinfo = kwargs.get("userinfo", authority_dict["userinfo"]) or "" + host = kwargs.get("host", authority_dict["host"]) or "" + port = kwargs.get("port", authority_dict["port"]) + + # Normalize and validate each component. + # We end up with a parsed representation of the URL, + # with components that are plain ASCII bytestrings. + parsed_scheme: str = scheme.lower() + parsed_userinfo: str = quote(userinfo, safe=USERINFO_SAFE) + parsed_host: str = encode_host(host) + parsed_port: int | None = normalize_port(port, scheme) + + has_scheme = parsed_scheme != "" + has_authority = ( + parsed_userinfo != "" or parsed_host != "" or parsed_port is not None + ) + validate_path(path, has_scheme=has_scheme, has_authority=has_authority) + if has_scheme or has_authority: + path = normalize_path(path) + + parsed_path: str = quote(path, safe=PATH_SAFE) + parsed_query: str | None = None if query is None else quote(query, safe=QUERY_SAFE) + parsed_frag: str | None = None if frag is None else quote(frag, safe=FRAG_SAFE) + + # The parsed ASCII bytestrings are our canonical form. + # All properties of the URL are derived from these. + return ParseResult( + parsed_scheme, + parsed_userinfo, + parsed_host, + parsed_port, + parsed_path, + parsed_query, + parsed_frag, + ) + + +def encode_host(host: str) -> str: + if not host: + return "" + + elif IPv4_STYLE_HOSTNAME.match(host): + # Validate IPv4 hostnames like #.#.#.# + # + # From https://datatracker.ietf.org/doc/html/rfc3986/#section-3.2.2 + # + # IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet + try: + ipaddress.IPv4Address(host) + except ipaddress.AddressValueError: + raise InvalidURL(f"Invalid IPv4 address: {host!r}") + return host + + elif IPv6_STYLE_HOSTNAME.match(host): + # Validate IPv6 hostnames like [...] + # + # From https://datatracker.ietf.org/doc/html/rfc3986/#section-3.2.2 + # + # "A host identified by an Internet Protocol literal address, version 6 + # [RFC3513] or later, is distinguished by enclosing the IP literal + # within square brackets ("[" and "]"). This is the only place where + # square bracket characters are allowed in the URI syntax." + try: + ipaddress.IPv6Address(host[1:-1]) + except ipaddress.AddressValueError: + raise InvalidURL(f"Invalid IPv6 address: {host!r}") + return host[1:-1] + + elif host.isascii(): + # Regular ASCII hostnames + # + # From https://datatracker.ietf.org/doc/html/rfc3986/#section-3.2.2 + # + # reg-name = *( unreserved / pct-encoded / sub-delims ) + WHATWG_SAFE = '"`{}%|\\' + return quote(host.lower(), safe=SUB_DELIMS + WHATWG_SAFE) + + # IDNA hostnames + try: + return idna.encode(host.lower()).decode("ascii") + except idna.IDNAError: + raise InvalidURL(f"Invalid IDNA hostname: {host!r}") + + +def normalize_port(port: str | int | None, scheme: str) -> int | None: + # From https://tools.ietf.org/html/rfc3986#section-3.2.3 + # + # "A scheme may define a default port. For example, the "http" scheme + # defines a default port of "80", corresponding to its reserved TCP + # port number. The type of port designated by the port number (e.g., + # TCP, UDP, SCTP) is defined by the URI scheme. URI producers and + # normalizers should omit the port component and its ":" delimiter if + # port is empty or if its value would be the same as that of the + # scheme's default." + if port is None or port == "": + return None + + try: + port_as_int = int(port) + except ValueError: + raise InvalidURL(f"Invalid port: {port!r}") + + # See https://url.spec.whatwg.org/#url-miscellaneous + default_port = {"ftp": 21, "http": 80, "https": 443, "ws": 80, "wss": 443}.get( + scheme + ) + if port_as_int == default_port: + return None + return port_as_int + + +def validate_path(path: str, has_scheme: bool, has_authority: bool) -> None: + """ + Path validation rules that depend on if the URL contains + a scheme or authority component. + + See https://datatracker.ietf.org/doc/html/rfc3986.html#section-3.3 + """ + if has_authority: + # If a URI contains an authority component, then the path component + # must either be empty or begin with a slash ("/") character." + if path and not path.startswith("/"): + raise InvalidURL("For absolute URLs, path must be empty or begin with '/'") + + if not has_scheme and not has_authority: + # If a URI does not contain an authority component, then the path cannot begin + # with two slash characters ("//"). + if path.startswith("//"): + raise InvalidURL("Relative URLs cannot have a path starting with '//'") + + # In addition, a URI reference (Section 4.1) may be a relative-path reference, + # in which case the first path segment cannot contain a colon (":") character. + if path.startswith(":"): + raise InvalidURL("Relative URLs cannot have a path starting with ':'") + + +def normalize_path(path: str) -> str: + """ + Drop "." and ".." segments from a URL path. + + For example: + + normalize_path("/path/./to/somewhere/..") == "/path/to" + """ + # Fast return when no '.' characters in the path. + if "." not in path: + return path + + components = path.split("/") + + # Fast return when no '.' or '..' components in the path. + if "." not in components and ".." not in components: + return path + + # https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4 + output: list[str] = [] + for component in components: + if component == ".": + pass + elif component == "..": + if output and output != [""]: + output.pop() + else: + output.append(component) + return "/".join(output) + + +def PERCENT(string: str) -> str: + return "".join([f"%{byte:02X}" for byte in string.encode("utf-8")]) + + +def percent_encoded(string: str, safe: str) -> str: + """ + Use percent-encoding to quote a string. + """ + NON_ESCAPED_CHARS = UNRESERVED_CHARACTERS + safe + + # Fast path for strings that don't need escaping. + if not string.rstrip(NON_ESCAPED_CHARS): + return string + + return "".join( + [char if char in NON_ESCAPED_CHARS else PERCENT(char) for char in string] + ) + + +def quote(string: str, safe: str) -> str: + """ + Use percent-encoding to quote a string, omitting existing '%xx' escape sequences. + + See: https://www.rfc-editor.org/rfc/rfc3986#section-2.1 + + * `string`: The string to be percent-escaped. + * `safe`: A string containing characters that may be treated as safe, and do not + need to be escaped. Unreserved characters are always treated as safe. + See: https://www.rfc-editor.org/rfc/rfc3986#section-2.3 + """ + parts = [] + current_position = 0 + for match in re.finditer(PERCENT_ENCODED_REGEX, string): + start_position, end_position = match.start(), match.end() + matched_text = match.group(0) + # Add any text up to the '%xx' escape sequence. + if start_position != current_position: + leading_text = string[current_position:start_position] + parts.append(percent_encoded(leading_text, safe=safe)) + + # Add the '%xx' escape sequence. + parts.append(matched_text) + current_position = end_position + + # Add any text after the final '%xx' escape sequence. + if current_position != len(string): + trailing_text = string[current_position:] + parts.append(percent_encoded(trailing_text, safe=safe)) + + return "".join(parts) diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/_urls.py b/data/miniconda3/lib/python3.13/site-packages/httpx/_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..147a8fa333acaf31618d37ba2896e3a5bf5e4d02 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/httpx/_urls.py @@ -0,0 +1,641 @@ +from __future__ import annotations + +import typing +from urllib.parse import parse_qs, unquote, urlencode + +import idna + +from ._types import QueryParamTypes +from ._urlparse import urlparse +from ._utils import primitive_value_to_str + +__all__ = ["URL", "QueryParams"] + + +class URL: + """ + url = httpx.URL("HTTPS://jo%40email.com:a%20secret@müller.de:1234/pa%20th?search=ab#anchorlink") + + assert url.scheme == "https" + assert url.username == "jo@email.com" + assert url.password == "a secret" + assert url.userinfo == b"jo%40email.com:a%20secret" + assert url.host == "müller.de" + assert url.raw_host == b"xn--mller-kva.de" + assert url.port == 1234 + assert url.netloc == b"xn--mller-kva.de:1234" + assert url.path == "/pa th" + assert url.query == b"?search=ab" + assert url.raw_path == b"/pa%20th?search=ab" + assert url.fragment == "anchorlink" + + The components of a URL are broken down like this: + + https://jo%40email.com:a%20secret@müller.de:1234/pa%20th?search=ab#anchorlink + [scheme] [ username ] [password] [ host ][port][ path ] [ query ] [fragment] + [ userinfo ] [ netloc ][ raw_path ] + + Note that: + + * `url.scheme` is normalized to always be lowercased. + + * `url.host` is normalized to always be lowercased. Internationalized domain + names are represented in unicode, without IDNA encoding applied. For instance: + + url = httpx.URL("http://中国.icom.museum") + assert url.host == "中国.icom.museum" + url = httpx.URL("http://xn--fiqs8s.icom.museum") + assert url.host == "中国.icom.museum" + + * `url.raw_host` is normalized to always be lowercased, and is IDNA encoded. + + url = httpx.URL("http://中国.icom.museum") + assert url.raw_host == b"xn--fiqs8s.icom.museum" + url = httpx.URL("http://xn--fiqs8s.icom.museum") + assert url.raw_host == b"xn--fiqs8s.icom.museum" + + * `url.port` is either None or an integer. URLs that include the default port for + "http", "https", "ws", "wss", and "ftp" schemes have their port + normalized to `None`. + + assert httpx.URL("http://example.com") == httpx.URL("http://example.com:80") + assert httpx.URL("http://example.com").port is None + assert httpx.URL("http://example.com:80").port is None + + * `url.userinfo` is raw bytes, without URL escaping. Usually you'll want to work + with `url.username` and `url.password` instead, which handle the URL escaping. + + * `url.raw_path` is raw bytes of both the path and query, without URL escaping. + This portion is used as the target when constructing HTTP requests. Usually you'll + want to work with `url.path` instead. + + * `url.query` is raw bytes, without URL escaping. A URL query string portion can + only be properly URL escaped when decoding the parameter names and values + themselves. + """ + + def __init__(self, url: URL | str = "", **kwargs: typing.Any) -> None: + if kwargs: + allowed = { + "scheme": str, + "username": str, + "password": str, + "userinfo": bytes, + "host": str, + "port": int, + "netloc": bytes, + "path": str, + "query": bytes, + "raw_path": bytes, + "fragment": str, + "params": object, + } + + # Perform type checking for all supported keyword arguments. + for key, value in kwargs.items(): + if key not in allowed: + message = f"{key!r} is an invalid keyword argument for URL()" + raise TypeError(message) + if value is not None and not isinstance(value, allowed[key]): + expected = allowed[key].__name__ + seen = type(value).__name__ + message = f"Argument {key!r} must be {expected} but got {seen}" + raise TypeError(message) + if isinstance(value, bytes): + kwargs[key] = value.decode("ascii") + + if "params" in kwargs: + # Replace any "params" keyword with the raw "query" instead. + # + # Ensure that empty params use `kwargs["query"] = None` rather + # than `kwargs["query"] = ""`, so that generated URLs do not + # include an empty trailing "?". + params = kwargs.pop("params") + kwargs["query"] = None if not params else str(QueryParams(params)) + + if isinstance(url, str): + self._uri_reference = urlparse(url, **kwargs) + elif isinstance(url, URL): + self._uri_reference = url._uri_reference.copy_with(**kwargs) + else: + raise TypeError( + "Invalid type for url. Expected str or httpx.URL," + f" got {type(url)}: {url!r}" + ) + + @property + def scheme(self) -> str: + """ + The URL scheme, such as "http", "https". + Always normalised to lowercase. + """ + return self._uri_reference.scheme + + @property + def raw_scheme(self) -> bytes: + """ + The raw bytes representation of the URL scheme, such as b"http", b"https". + Always normalised to lowercase. + """ + return self._uri_reference.scheme.encode("ascii") + + @property + def userinfo(self) -> bytes: + """ + The URL userinfo as a raw bytestring. + For example: b"jo%40email.com:a%20secret". + """ + return self._uri_reference.userinfo.encode("ascii") + + @property + def username(self) -> str: + """ + The URL username as a string, with URL decoding applied. + For example: "jo@email.com" + """ + userinfo = self._uri_reference.userinfo + return unquote(userinfo.partition(":")[0]) + + @property + def password(self) -> str: + """ + The URL password as a string, with URL decoding applied. + For example: "a secret" + """ + userinfo = self._uri_reference.userinfo + return unquote(userinfo.partition(":")[2]) + + @property + def host(self) -> str: + """ + The URL host as a string. + Always normalized to lowercase, with IDNA hosts decoded into unicode. + + Examples: + + url = httpx.URL("http://www.EXAMPLE.org") + assert url.host == "www.example.org" + + url = httpx.URL("http://中国.icom.museum") + assert url.host == "中国.icom.museum" + + url = httpx.URL("http://xn--fiqs8s.icom.museum") + assert url.host == "中国.icom.museum" + + url = httpx.URL("https://[::ffff:192.168.0.1]") + assert url.host == "::ffff:192.168.0.1" + """ + host: str = self._uri_reference.host + + if host.startswith("xn--"): + host = idna.decode(host) + + return host + + @property + def raw_host(self) -> bytes: + """ + The raw bytes representation of the URL host. + Always normalized to lowercase, and IDNA encoded. + + Examples: + + url = httpx.URL("http://www.EXAMPLE.org") + assert url.raw_host == b"www.example.org" + + url = httpx.URL("http://中国.icom.museum") + assert url.raw_host == b"xn--fiqs8s.icom.museum" + + url = httpx.URL("http://xn--fiqs8s.icom.museum") + assert url.raw_host == b"xn--fiqs8s.icom.museum" + + url = httpx.URL("https://[::ffff:192.168.0.1]") + assert url.raw_host == b"::ffff:192.168.0.1" + """ + return self._uri_reference.host.encode("ascii") + + @property + def port(self) -> int | None: + """ + The URL port as an integer. + + Note that the URL class performs port normalization as per the WHATWG spec. + Default ports for "http", "https", "ws", "wss", and "ftp" schemes are always + treated as `None`. + + For example: + + assert httpx.URL("http://www.example.com") == httpx.URL("http://www.example.com:80") + assert httpx.URL("http://www.example.com:80").port is None + """ + return self._uri_reference.port + + @property + def netloc(self) -> bytes: + """ + Either `` or `:` as bytes. + Always normalized to lowercase, and IDNA encoded. + + This property may be used for generating the value of a request + "Host" header. + """ + return self._uri_reference.netloc.encode("ascii") + + @property + def path(self) -> str: + """ + The URL path as a string. Excluding the query string, and URL decoded. + + For example: + + url = httpx.URL("https://example.com/pa%20th") + assert url.path == "/pa th" + """ + path = self._uri_reference.path or "/" + return unquote(path) + + @property + def query(self) -> bytes: + """ + The URL query string, as raw bytes, excluding the leading b"?". + + This is necessarily a bytewise interface, because we cannot + perform URL decoding of this representation until we've parsed + the keys and values into a QueryParams instance. + + For example: + + url = httpx.URL("https://example.com/?filter=some%20search%20terms") + assert url.query == b"filter=some%20search%20terms" + """ + query = self._uri_reference.query or "" + return query.encode("ascii") + + @property + def params(self) -> QueryParams: + """ + The URL query parameters, neatly parsed and packaged into an immutable + multidict representation. + """ + return QueryParams(self._uri_reference.query) + + @property + def raw_path(self) -> bytes: + """ + The complete URL path and query string as raw bytes. + Used as the target when constructing HTTP requests. + + For example: + + GET /users?search=some%20text HTTP/1.1 + Host: www.example.org + Connection: close + """ + path = self._uri_reference.path or "/" + if self._uri_reference.query is not None: + path += "?" + self._uri_reference.query + return path.encode("ascii") + + @property + def fragment(self) -> str: + """ + The URL fragments, as used in HTML anchors. + As a string, without the leading '#'. + """ + return unquote(self._uri_reference.fragment or "") + + @property + def is_absolute_url(self) -> bool: + """ + Return `True` for absolute URLs such as 'http://example.com/path', + and `False` for relative URLs such as '/path'. + """ + # We don't use `.is_absolute` from `rfc3986` because it treats + # URLs with a fragment portion as not absolute. + # What we actually care about is if the URL provides + # a scheme and hostname to which connections should be made. + return bool(self._uri_reference.scheme and self._uri_reference.host) + + @property + def is_relative_url(self) -> bool: + """ + Return `False` for absolute URLs such as 'http://example.com/path', + and `True` for relative URLs such as '/path'. + """ + return not self.is_absolute_url + + def copy_with(self, **kwargs: typing.Any) -> URL: + """ + Copy this URL, returning a new URL with some components altered. + Accepts the same set of parameters as the components that are made + available via properties on the `URL` class. + + For example: + + url = httpx.URL("https://www.example.com").copy_with( + username="jo@gmail.com", password="a secret" + ) + assert url == "https://jo%40email.com:a%20secret@www.example.com" + """ + return URL(self, **kwargs) + + def copy_set_param(self, key: str, value: typing.Any = None) -> URL: + return self.copy_with(params=self.params.set(key, value)) + + def copy_add_param(self, key: str, value: typing.Any = None) -> URL: + return self.copy_with(params=self.params.add(key, value)) + + def copy_remove_param(self, key: str) -> URL: + return self.copy_with(params=self.params.remove(key)) + + def copy_merge_params(self, params: QueryParamTypes) -> URL: + return self.copy_with(params=self.params.merge(params)) + + def join(self, url: URL | str) -> URL: + """ + Return an absolute URL, using this URL as the base. + + Eg. + + url = httpx.URL("https://www.example.com/test") + url = url.join("/new/path") + assert url == "https://www.example.com/new/path" + """ + from urllib.parse import urljoin + + return URL(urljoin(str(self), str(URL(url)))) + + def __hash__(self) -> int: + return hash(str(self)) + + def __eq__(self, other: typing.Any) -> bool: + return isinstance(other, (URL, str)) and str(self) == str(URL(other)) + + def __str__(self) -> str: + return str(self._uri_reference) + + def __repr__(self) -> str: + scheme, userinfo, host, port, path, query, fragment = self._uri_reference + + if ":" in userinfo: + # Mask any password component. + userinfo = f'{userinfo.split(":")[0]}:[secure]' + + authority = "".join( + [ + f"{userinfo}@" if userinfo else "", + f"[{host}]" if ":" in host else host, + f":{port}" if port is not None else "", + ] + ) + url = "".join( + [ + f"{self.scheme}:" if scheme else "", + f"//{authority}" if authority else "", + path, + f"?{query}" if query is not None else "", + f"#{fragment}" if fragment is not None else "", + ] + ) + + return f"{self.__class__.__name__}({url!r})" + + @property + def raw(self) -> tuple[bytes, bytes, int, bytes]: # pragma: nocover + import collections + import warnings + + warnings.warn("URL.raw is deprecated.") + RawURL = collections.namedtuple( + "RawURL", ["raw_scheme", "raw_host", "port", "raw_path"] + ) + return RawURL( + raw_scheme=self.raw_scheme, + raw_host=self.raw_host, + port=self.port, + raw_path=self.raw_path, + ) + + +class QueryParams(typing.Mapping[str, str]): + """ + URL query parameters, as a multi-dict. + """ + + def __init__(self, *args: QueryParamTypes | None, **kwargs: typing.Any) -> None: + assert len(args) < 2, "Too many arguments." + assert not (args and kwargs), "Cannot mix named and unnamed arguments." + + value = args[0] if args else kwargs + + if value is None or isinstance(value, (str, bytes)): + value = value.decode("ascii") if isinstance(value, bytes) else value + self._dict = parse_qs(value, keep_blank_values=True) + elif isinstance(value, QueryParams): + self._dict = {k: list(v) for k, v in value._dict.items()} + else: + dict_value: dict[typing.Any, list[typing.Any]] = {} + if isinstance(value, (list, tuple)): + # Convert list inputs like: + # [("a", "123"), ("a", "456"), ("b", "789")] + # To a dict representation, like: + # {"a": ["123", "456"], "b": ["789"]} + for item in value: + dict_value.setdefault(item[0], []).append(item[1]) + else: + # Convert dict inputs like: + # {"a": "123", "b": ["456", "789"]} + # To dict inputs where values are always lists, like: + # {"a": ["123"], "b": ["456", "789"]} + dict_value = { + k: list(v) if isinstance(v, (list, tuple)) else [v] + for k, v in value.items() + } + + # Ensure that keys and values are neatly coerced to strings. + # We coerce values `True` and `False` to JSON-like "true" and "false" + # representations, and coerce `None` values to the empty string. + self._dict = { + str(k): [primitive_value_to_str(item) for item in v] + for k, v in dict_value.items() + } + + def keys(self) -> typing.KeysView[str]: + """ + Return all the keys in the query params. + + Usage: + + q = httpx.QueryParams("a=123&a=456&b=789") + assert list(q.keys()) == ["a", "b"] + """ + return self._dict.keys() + + def values(self) -> typing.ValuesView[str]: + """ + Return all the values in the query params. If a key occurs more than once + only the first item for that key is returned. + + Usage: + + q = httpx.QueryParams("a=123&a=456&b=789") + assert list(q.values()) == ["123", "789"] + """ + return {k: v[0] for k, v in self._dict.items()}.values() + + def items(self) -> typing.ItemsView[str, str]: + """ + Return all items in the query params. If a key occurs more than once + only the first item for that key is returned. + + Usage: + + q = httpx.QueryParams("a=123&a=456&b=789") + assert list(q.items()) == [("a", "123"), ("b", "789")] + """ + return {k: v[0] for k, v in self._dict.items()}.items() + + def multi_items(self) -> list[tuple[str, str]]: + """ + Return all items in the query params. Allow duplicate keys to occur. + + Usage: + + q = httpx.QueryParams("a=123&a=456&b=789") + assert list(q.multi_items()) == [("a", "123"), ("a", "456"), ("b", "789")] + """ + multi_items: list[tuple[str, str]] = [] + for k, v in self._dict.items(): + multi_items.extend([(k, i) for i in v]) + return multi_items + + def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any: + """ + Get a value from the query param for a given key. If the key occurs + more than once, then only the first value is returned. + + Usage: + + q = httpx.QueryParams("a=123&a=456&b=789") + assert q.get("a") == "123" + """ + if key in self._dict: + return self._dict[str(key)][0] + return default + + def get_list(self, key: str) -> list[str]: + """ + Get all values from the query param for a given key. + + Usage: + + q = httpx.QueryParams("a=123&a=456&b=789") + assert q.get_list("a") == ["123", "456"] + """ + return list(self._dict.get(str(key), [])) + + def set(self, key: str, value: typing.Any = None) -> QueryParams: + """ + Return a new QueryParams instance, setting the value of a key. + + Usage: + + q = httpx.QueryParams("a=123") + q = q.set("a", "456") + assert q == httpx.QueryParams("a=456") + """ + q = QueryParams() + q._dict = dict(self._dict) + q._dict[str(key)] = [primitive_value_to_str(value)] + return q + + def add(self, key: str, value: typing.Any = None) -> QueryParams: + """ + Return a new QueryParams instance, setting or appending the value of a key. + + Usage: + + q = httpx.QueryParams("a=123") + q = q.add("a", "456") + assert q == httpx.QueryParams("a=123&a=456") + """ + q = QueryParams() + q._dict = dict(self._dict) + q._dict[str(key)] = q.get_list(key) + [primitive_value_to_str(value)] + return q + + def remove(self, key: str) -> QueryParams: + """ + Return a new QueryParams instance, removing the value of a key. + + Usage: + + q = httpx.QueryParams("a=123") + q = q.remove("a") + assert q == httpx.QueryParams("") + """ + q = QueryParams() + q._dict = dict(self._dict) + q._dict.pop(str(key), None) + return q + + def merge(self, params: QueryParamTypes | None = None) -> QueryParams: + """ + Return a new QueryParams instance, updated with. + + Usage: + + q = httpx.QueryParams("a=123") + q = q.merge({"b": "456"}) + assert q == httpx.QueryParams("a=123&b=456") + + q = httpx.QueryParams("a=123") + q = q.merge({"a": "456", "b": "789"}) + assert q == httpx.QueryParams("a=456&b=789") + """ + q = QueryParams(params) + q._dict = {**self._dict, **q._dict} + return q + + def __getitem__(self, key: typing.Any) -> str: + return self._dict[key][0] + + def __contains__(self, key: typing.Any) -> bool: + return key in self._dict + + def __iter__(self) -> typing.Iterator[typing.Any]: + return iter(self.keys()) + + def __len__(self) -> int: + return len(self._dict) + + def __bool__(self) -> bool: + return bool(self._dict) + + def __hash__(self) -> int: + return hash(str(self)) + + def __eq__(self, other: typing.Any) -> bool: + if not isinstance(other, self.__class__): + return False + return sorted(self.multi_items()) == sorted(other.multi_items()) + + def __str__(self) -> str: + return urlencode(self.multi_items()) + + def __repr__(self) -> str: + class_name = self.__class__.__name__ + query_string = str(self) + return f"{class_name}({query_string!r})" + + def update(self, params: QueryParamTypes | None = None) -> None: + raise RuntimeError( + "QueryParams are immutable since 0.18.0. " + "Use `q = q.merge(...)` to create an updated copy." + ) + + def __setitem__(self, key: str, value: str) -> None: + raise RuntimeError( + "QueryParams are immutable since 0.18.0. " + "Use `q = q.set(key, value)` to create an updated copy." + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/_utils.py b/data/miniconda3/lib/python3.13/site-packages/httpx/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7fe827da4d071b32ea6da44328629699d6fc88ce --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/httpx/_utils.py @@ -0,0 +1,242 @@ +from __future__ import annotations + +import ipaddress +import os +import re +import typing +from urllib.request import getproxies + +from ._types import PrimitiveData + +if typing.TYPE_CHECKING: # pragma: no cover + from ._urls import URL + + +def primitive_value_to_str(value: PrimitiveData) -> str: + """ + Coerce a primitive data type into a string value. + + Note that we prefer JSON-style 'true'/'false' for boolean values here. + """ + if value is True: + return "true" + elif value is False: + return "false" + elif value is None: + return "" + return str(value) + + +def get_environment_proxies() -> dict[str, str | None]: + """Gets proxy information from the environment""" + + # urllib.request.getproxies() falls back on System + # Registry and Config for proxies on Windows and macOS. + # We don't want to propagate non-HTTP proxies into + # our configuration such as 'TRAVIS_APT_PROXY'. + proxy_info = getproxies() + mounts: dict[str, str | None] = {} + + for scheme in ("http", "https", "all"): + if proxy_info.get(scheme): + hostname = proxy_info[scheme] + mounts[f"{scheme}://"] = ( + hostname if "://" in hostname else f"http://{hostname}" + ) + + no_proxy_hosts = [host.strip() for host in proxy_info.get("no", "").split(",")] + for hostname in no_proxy_hosts: + # See https://curl.haxx.se/libcurl/c/CURLOPT_NOPROXY.html for details + # on how names in `NO_PROXY` are handled. + if hostname == "*": + # If NO_PROXY=* is used or if "*" occurs as any one of the comma + # separated hostnames, then we should just bypass any information + # from HTTP_PROXY, HTTPS_PROXY, ALL_PROXY, and always ignore + # proxies. + return {} + elif hostname: + # NO_PROXY=.google.com is marked as "all://*.google.com, + # which disables "www.google.com" but not "google.com" + # NO_PROXY=google.com is marked as "all://*google.com, + # which disables "www.google.com" and "google.com". + # (But not "wwwgoogle.com") + # NO_PROXY can include domains, IPv6, IPv4 addresses and "localhost" + # NO_PROXY=example.com,::1,localhost,192.168.0.0/16 + if "://" in hostname: + mounts[hostname] = None + elif is_ipv4_hostname(hostname): + mounts[f"all://{hostname}"] = None + elif is_ipv6_hostname(hostname): + mounts[f"all://[{hostname}]"] = None + elif hostname.lower() == "localhost": + mounts[f"all://{hostname}"] = None + else: + mounts[f"all://*{hostname}"] = None + + return mounts + + +def to_bytes(value: str | bytes, encoding: str = "utf-8") -> bytes: + return value.encode(encoding) if isinstance(value, str) else value + + +def to_str(value: str | bytes, encoding: str = "utf-8") -> str: + return value if isinstance(value, str) else value.decode(encoding) + + +def to_bytes_or_str(value: str, match_type_of: typing.AnyStr) -> typing.AnyStr: + return value if isinstance(match_type_of, str) else value.encode() + + +def unquote(value: str) -> str: + return value[1:-1] if value[0] == value[-1] == '"' else value + + +def peek_filelike_length(stream: typing.Any) -> int | None: + """ + Given a file-like stream object, return its length in number of bytes + without reading it into memory. + """ + try: + # Is it an actual file? + fd = stream.fileno() + # Yup, seems to be an actual file. + length = os.fstat(fd).st_size + except (AttributeError, OSError): + # No... Maybe it's something that supports random access, like `io.BytesIO`? + try: + # Assuming so, go to end of stream to figure out its length, + # then put it back in place. + offset = stream.tell() + length = stream.seek(0, os.SEEK_END) + stream.seek(offset) + except (AttributeError, OSError): + # Not even that? Sorry, we're doomed... + return None + + return length + + +class URLPattern: + """ + A utility class currently used for making lookups against proxy keys... + + # Wildcard matching... + >>> pattern = URLPattern("all://") + >>> pattern.matches(httpx.URL("http://example.com")) + True + + # Witch scheme matching... + >>> pattern = URLPattern("https://") + >>> pattern.matches(httpx.URL("https://example.com")) + True + >>> pattern.matches(httpx.URL("http://example.com")) + False + + # With domain matching... + >>> pattern = URLPattern("https://example.com") + >>> pattern.matches(httpx.URL("https://example.com")) + True + >>> pattern.matches(httpx.URL("http://example.com")) + False + >>> pattern.matches(httpx.URL("https://other.com")) + False + + # Wildcard scheme, with domain matching... + >>> pattern = URLPattern("all://example.com") + >>> pattern.matches(httpx.URL("https://example.com")) + True + >>> pattern.matches(httpx.URL("http://example.com")) + True + >>> pattern.matches(httpx.URL("https://other.com")) + False + + # With port matching... + >>> pattern = URLPattern("https://example.com:1234") + >>> pattern.matches(httpx.URL("https://example.com:1234")) + True + >>> pattern.matches(httpx.URL("https://example.com")) + False + """ + + def __init__(self, pattern: str) -> None: + from ._urls import URL + + if pattern and ":" not in pattern: + raise ValueError( + f"Proxy keys should use proper URL forms rather " + f"than plain scheme strings. " + f'Instead of "{pattern}", use "{pattern}://"' + ) + + url = URL(pattern) + self.pattern = pattern + self.scheme = "" if url.scheme == "all" else url.scheme + self.host = "" if url.host == "*" else url.host + self.port = url.port + if not url.host or url.host == "*": + self.host_regex: typing.Pattern[str] | None = None + elif url.host.startswith("*."): + # *.example.com should match "www.example.com", but not "example.com" + domain = re.escape(url.host[2:]) + self.host_regex = re.compile(f"^.+\\.{domain}$") + elif url.host.startswith("*"): + # *example.com should match "www.example.com" and "example.com" + domain = re.escape(url.host[1:]) + self.host_regex = re.compile(f"^(.+\\.)?{domain}$") + else: + # example.com should match "example.com" but not "www.example.com" + domain = re.escape(url.host) + self.host_regex = re.compile(f"^{domain}$") + + def matches(self, other: URL) -> bool: + if self.scheme and self.scheme != other.scheme: + return False + if ( + self.host + and self.host_regex is not None + and not self.host_regex.match(other.host) + ): + return False + if self.port is not None and self.port != other.port: + return False + return True + + @property + def priority(self) -> tuple[int, int, int]: + """ + The priority allows URLPattern instances to be sortable, so that + we can match from most specific to least specific. + """ + # URLs with a port should take priority over URLs without a port. + port_priority = 0 if self.port is not None else 1 + # Longer hostnames should match first. + host_priority = -len(self.host) + # Longer schemes should match first. + scheme_priority = -len(self.scheme) + return (port_priority, host_priority, scheme_priority) + + def __hash__(self) -> int: + return hash(self.pattern) + + def __lt__(self, other: URLPattern) -> bool: + return self.priority < other.priority + + def __eq__(self, other: typing.Any) -> bool: + return isinstance(other, URLPattern) and self.pattern == other.pattern + + +def is_ipv4_hostname(hostname: str) -> bool: + try: + ipaddress.IPv4Address(hostname.split("/")[0]) + except Exception: + return False + return True + + +def is_ipv6_hostname(hostname: str) -> bool: + try: + ipaddress.IPv6Address(hostname.split("/")[0]) + except Exception: + return False + return True diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/py.typed b/data/miniconda3/lib/python3.13/site-packages/httpx/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/__init__.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..feaf0d94b7657f2dbf1c7e7daf006c83d1137f68 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/__init__.py @@ -0,0 +1,383 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Thomas Krijnen +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# IfcOpenShell is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with IfcOpenShell. If not, see . + +"""Welcome to IfcOpenShell! IfcOpenShell provides a way to read and write IFCs. + +IfcOpenShell can open IFC files, read entities (such as walls, buildings, +properties, systems, etc), edit attributes, write out ``.ifc`` files and more. + +This module provides primitive functions to interact with IFC, including: + +- For most users, you can open and read IFC models, see docs for :func:`open`. + This returns an :class:`file` object representing the IFC model. You can then + query the model to filter elements. +- For developers, you can query the schema itself, see docs for + :func:`schema_by_name`. This returns a schema object which you can use to + analyse the definitions of IFC classes and data types. + +You may also be interested in: + +- For model authoring and editing operations, see :mod:`ifcopenshell.api`. +- For extracting information from models, see :mod:`ifcopenshell.util`. +- For processing geometry, see :mod:`ifcopenshell.geom`. + + +For more details, consult https://docs.ifcopenshell.org/ + +Example: + +.. code:: python + + import ifcopenshell + + print(ifcopenshell.version) + + model = ifcopenshell.open("/path/to/model.ifc") + walls = model.by_type("IfcWall") + + for wall in walls: + print(wall.Name) +""" +from __future__ import annotations +import os +import sys +import zipfile +import tempfile +from pathlib import Path +from typing import Optional, Union, TYPE_CHECKING, Any, overload, Literal +from collections.abc import Generator, Sequence + +if TYPE_CHECKING: + import ifcopenshell.express.schema_class + + +if sys.platform != "win32": + platform_system = os.uname()[0].lower() +else: + platform_system = "windows" + +if sys.maxsize == (1 << 31) - 1: + platform_architecture = "32bit" +else: + platform_architecture = "64bit" + +python_version_tuple = tuple(sys.version.split(" ")[0].split(".")) + +python_distribution = os.path.join(platform_system, platform_architecture, "python%s.%s" % python_version_tuple[:2]) +sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "lib", python_distribution))) + +try: + from . import ifcopenshell_wrapper +except Exception: + raise ImportError("IfcOpenShell not built for '%s'" % python_distribution) + +# `_file`, `_stream` is used only for annotations inside this file, +# see https://github.com/microsoft/pyright/discussions/9065. +from .file import file as _file +from .file import file + +from .file import rocksdb_lazy_instance +from . import guid +from .entity_instance import entity_instance, register_schema_attributes +from .sql import sqlite, sqlite_entity + +# explicitly specify available imported symbols +# (it's a requirement for a typed library) +__all__ = [ + "entity_instance", + "file", + "guid", + "ifcopenshell_wrapper", + "sqlite", + "sqlite_entity", + "stream", + "stream_entity", +] + +try: + from .stream import stream as _stream, stream_entity + from .stream import stream +except: + pass + + +class Error(Exception): + """Error used when a generic problem occurs""" + + pass + + +class SchemaError(Error): + """Error used when an IFC schema related problem occurs""" + + pass + + +@overload +def open( + path: Union[os.PathLike, str], format: Optional[str] = None, *, should_stream: Literal[False] = False +) -> Union[_file, sqlite]: ... +@overload +def open(path: Union[os.PathLike, str], format: Optional[str] = None, *, should_stream: Literal[True]) -> _stream: ... +@overload +def open( + path: Union[os.PathLike, str], format: Optional[str] = None, *, should_stream: bool = False, readonly: bool = False +) -> Union[_file, sqlite, _stream]: ... +def open( + path: Union[os.PathLike, str], + format: Optional[str] = None, + should_stream: bool = False, + readonly: bool = False, + mmap: bool = False, + bypass_types: Optional[Sequence[str]] = None, +) -> Union[_file, sqlite, _stream]: + """Loads an IFC dataset from a filepath + + :param should_stream: Whether to open the file in streaming mode. Could be useful + for reading large files. + + You can specify a file format. If no format is given, it is guessed from + its extension. Currently supported specified format: .ifc | .ifcZIP | + .ifcXML. + + You can then filter by element ID, class, etc, and subscript by id or guid. + + Example: + + .. code:: python + + model = ifcopenshell.open("/path/to/model.ifc") + model = ifcopenshell.open("/path/to/model.ifcXML") + model = ifcopenshell.open("/path/to/model.any_extension", ".ifc") + + products = model.by_type("IfcProduct") + print(products[0].id(), products[0].GlobalId) # 122 2XQ$n5SLP5MBLyL442paFx + print(products[0] == model[122] == model["2XQ$n5SLP5MBLyL442paFx"]) # True + """ + path = Path(path) + if not path.exists(): + raise FileNotFoundError(f"Path does not exist: '{path}'.") + if format is None: + format = guess_format(path) + if format == ".ifcXML": + f = ifcopenshell_wrapper.parse_ifcxml(str(path.absolute())) + if f: + return file(f) + raise OSError(f"Failed to parse .ifcXML file from {path}") + if format == ".ifcZIP": + with tempfile.TemporaryDirectory() as unzipped_path: + with zipfile.ZipFile(path) as zf: + for name in zf.namelist(): + if Path(name).suffix.lower() in (".ifc", ".ifcxml"): + return open(zf.extract(name, unzipped_path)) + else: + raise LookupError(f"No .ifc or .ifcXML file found in {path}") + if format == ".ifcSQLite": + return sqlite(path) + if should_stream: + return stream(path) + if readonly: # Temporary conditional see #7131. Remove once newer builds don't segfault on Linux. + f = ifcopenshell_wrapper.open(str(path.absolute()), readonly=readonly) + elif bypass_types: + f = ifcopenshell_wrapper.file(ifcopenshell_wrapper.uninitialized_tag()) + for ty in bypass_types: + f.bypass_type(ty) + if mmap: + f.initialize(str(path.absolute()), mmap=mmap) + else: + f.initialize(str(path.absolute())) + elif mmap: + f = ifcopenshell_wrapper.open(str(path.absolute()), mmap=mmap) + else: + f = ifcopenshell_wrapper.open(str(path.absolute())) + return file(f) + + +def create_entity(type: str, schema: str = "IFC4", *args: Any, **kwargs: Any) -> entity_instance: + """Creates a new IFC entity that does not belong to an IFC file object + + Note that it is more common to create entities within a existing file + object. See :meth:`ifcopenshell.file.create_entity`. + + :param type: Case insensitive name of the IFC class + :param schema: The IFC schema identifier + :param args: The positional arguments of the IFC class + :param kwargs: The keyword arguments of the IFC class + :returns: An entity instance + + Example: + + .. code:: python + + person = ifcopenshell.create_entity("IfcPerson") # #0=IfcPerson($,$,$,$,$,$,$,$) + model = ifcopenshell.file() + model.add(person) # #1=IfcPerson($,$,$,$,$,$,$,$) + """ + e = entity_instance((schema, type)) + attrs = list(enumerate(args)) + [(e.wrapped_data.get_argument_index(name), arg) for name, arg in kwargs.items()] + for idx, arg in attrs: + e[idx] = arg + return e + + +def register_schema(schema: ifcopenshell.express.schema_class.SchemaClass) -> None: + """Registers a custom IFC schema + + :param schema: A schema object + + Example: + + .. code:: python + + schema = ifcopenshell.express.parse("/path/to/ifc-custom.exp") + ifcopenshell.register_schema(schema) + ifcopenshell.file(schema="IFC_CUSTOM") + """ + schema.schema.this.disown() + schema.disown() + ifcopenshell_wrapper.register_schema(schema.schema) + register_schema_attributes(schema.schema) + + +def schema_by_name( + schema: Optional[str] = None, + schema_version: Optional[tuple[int, ...]] = None, +) -> ifcopenshell_wrapper.schema_definition: + """Returns an object allowing you to query the IFC schema itself + + :param schema: Which IFC schema to use, chosen from "IFC2X3", "IFC4", + or "IFC4X3". These refer to the ISO approved versions of IFC. + E.g. from ``ifcopenshell.file.schema_identifier``. + Passing ``ifcopenshell.file.schema`` also will work but may result + in not precisely matching schema but it's only conern if you're + using not one of the main schemas. + :param schema_version: If you want to specify an exact version of IFC + that may not be an ISO approved version, use this argument instead + of ``schema``. IFC versions on technical.buildingsmart.org are + described using 4 integers representing the major, minor, addendum, + and corrigendum number. For example, (4, 0, 2, 1) refers to IFC4 + ADD2 TC1, which is the official version approved by ISO when people + refer to "IFC4". Generally you should not use this argument unless + you are testing non-ISO IFC releases. + :return: Schema definition object. + """ + assert schema_version or schema, "Either schema or schema_version must be specified." + if schema_version: + prefixes = ("IFC", "X", "_ADD", "_TC") + schema = "".join("".join(map(str, t)) if t[1] else "" for t in zip(prefixes, schema_version)) + else: + schema = {"IFC4X3": "IFC4X3_ADD2"}.get(schema, schema) + return ifcopenshell_wrapper.schema_by_name(schema) + + +def guess_format(path: Path) -> Literal[".ifc", ".ifcZIP", ".ifcXML", ".ifcJSON", ".ifcSQLite", None]: + """Guesses the IFC format using file extension + + IFCs may be serialised as different formats. The most common is a ``.ifc`` + file, which is plaintext and stores data using the STEP Physical File + format. IFC can also be stored as a Zipfile, XML, JSON, or SQL. + + This will return the canonical form of the format. For example, if a path + has the extension of .xml or .ifcxml (case insensitive), it will return + .ifcXML. + + Users generally won't call this function. The :func:`open` function uses + this internally to guess the file format. + """ + suffix = path.suffix.lower() + if path.is_dir(): + return "rocksdb" + elif suffix == ".ifc": + return ".ifc" + elif suffix in (".ifczip", ".zip"): + return ".ifcZIP" + elif suffix in (".ifcxml", ".xml"): + return ".ifcXML" + elif suffix in (".ifcjson", ".json"): + return ".ifcJSON" + elif suffix in (".ifcsqlite", ".sqlite", ".db"): + return ".ifcSQLite" + return None + + +def stream2(path: Union[Path, str], mmap: bool = False, page_size: int = 0): + """Streams the content of a file path from disk, yielding each instance + as a dictionary. + + :param path: Input file path + :param mmap: Open the file contents using memory mapping + :param page_size: Open file in python and feed chunks to the parser. + + :yield: Entity instance dictionaries + """ + if page_size: + import builtins + + f = builtins.open(path, encoding="ascii") + strm = ifcopenshell_wrapper.InstanceStreamer() + strm.pushPage(f.read(page_size)) + finished = False + while True: + while strm.hasSemicolon(): + if inst := strm.readInstancePy(): + yield inst + else: + finished = True + break + if finished: + break + else: + if data := f.read(page_size): + strm.pushPage(data) + else: + break + else: + streamer = ifcopenshell_wrapper.InstanceStreamer(str(path), mmap) + while streamer: + if inst := streamer.readInstancePy(): + yield inst + + +def stream2_from_string(data: str) -> Generator[dict]: + """Streams the content of a file path from string, yielding each instance + as a dictionary. + + :param data: Input data string + :yield: entity instance dictionaries + """ + streamer = ifcopenshell_wrapper.stream_from_string(data) + while streamer: + if inst := streamer.read_instance_py(): + yield inst + + +def convert_path_to_rocksdb(ifcspf_path: Union[Path, str], rocksdb_path: Union[Path, str]) -> None: + """Converts an IFC-SPF file on disk to the IfcOpenShell-specific + RocksDB encoding. RocksDB is an embedded key-value store that allows + partial reads and is therefore more memory efficient with larger files. + + :param ifcspf_path: Input file path - needs to exist + :param rocksdb_path: RocksDB file path (directory) - may exist, but result may then be invalid + """ + ser = ifcopenshell_wrapper.RocksDbSerializer(str(ifcspf_path), str(rocksdb_path), True) + ser.finalize() + + +version_core = ifcopenshell_wrapper.version() +__version__ = version = "0.8.4" +get_log = ifcopenshell_wrapper.get_log diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/draw.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/draw.py new file mode 100644 index 0000000000000000000000000000000000000000..e2e38d700b8080d133446b56d2813f2752cfe969 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/draw.py @@ -0,0 +1,735 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Thomas Krijnen +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# IfcOpenShell is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with IfcOpenShell. If not, see . + +"""2D drawing generation and serialisation""" + +from functools import reduce +import itertools +import math +import json +import operator +import warnings +import shapely + +import ifcopenshell +import ifcopenshell.geom +import ifcopenshell.util.element +import ifcopenshell.util.selector + +from xml.dom.minidom import parseString +from dataclasses import dataclass, fields, field +from collections.abc import Callable, Sequence + +import numpy + +W = ifcopenshell.ifcopenshell_wrapper + +WHITE = numpy.array((1.0, 1.0, 1.0)) + +DO_NOTHING = lambda *args: None + + +@dataclass +class draw_settings: + width: float = 297.0 + height: float = 420.0 + scale: float = 1.0 / 100.0 + auto_elevation: bool = False + auto_section: bool = False + auto_floorplan: bool = True + space_names: bool = False + space_areas: bool = False + door_arcs: bool = False + subtract_before_hlr: bool = False + cache: bool = False + css: str = "" + storey_heights: str = "none" + storey_filter: str = "" + include_entities: str = "" + exclude_entities: str = "IfcOpeningElement" + drawing_guid: str = field( + default="", + metadata={ + "doc": "Use a drawing with the provided GlobalId. Setting takes priority over 'drawing_object_type'." + }, + ) + drawing_object_type: str = field( + default="", metadata={"doc": 'Use IfcAnnotations with provided ObjectType for drawings (e.g. "DRAWING").'} + ) + profile_threshold: int = -1 + cells: bool = True + merge_cells: bool = False + include_projection: bool = True + hlr_poly: bool = False + prefilter: bool = True + include_curves: bool = False + unify_inputs: bool = True + arrange_spaces: bool = False + arrange_zones: bool = False + zone_filter: str = "" + zone_label: str = "" + mirror_y: bool = False + + +class type_unsafe_value: + def __init__(self, value): + self.value = value + + def __eq__(self, other): + try: + v = type(other)(self.value) + except: + return False + return v == other + + +def main( + settings: draw_settings, + files: list[ifcopenshell.file], + iterators: Sequence[ifcopenshell.geom.iterator] = (), + merge_projection: bool = True, + progress_function: Callable = DO_NOTHING, +): + + def by_guid(g): + for f in files: + try: + return f.by_guid(g) + except: + pass + + geom_settings = ifcopenshell.geom.settings( + # when not doing booleans, proper solids from shells isn't a requirement + REORIENT_SHELLS=settings.subtract_before_hlr, + # SVG serialiazation depends on element hierarchy now to look up the parent + ELEMENT_HIERARCHY=True, + ) + + # this is required for serialization + dimensionality = W.CURVES_SURFACES_AND_SOLIDS if settings.include_curves else W.SURFACES_AND_SOLIDS + geom_settings.set("dimensionality", dimensionality) + geom_settings.set("iterator-output", ifcopenshell.ifcopenshell_wrapper.NATIVE) + geom_settings.set("apply-default-materials", True) + + if not iterators: + iterator_kwargs = {} + if settings.include_entities: + iterator_kwargs["include"] = settings.include_entities.split(",") + elif settings.exclude_entities: + iterator_kwargs["exclude"] = settings.exclude_entities.split(",") + + def yield_parents(el): + yield el + if par := ifcopenshell.util.element.get_parent(el): + yield from yield_parents(par) + + def has_selected_parent(el): + return any(settings.storey_filter in (x.Name or x.GlobalId) for x in yield_parents(el)) + + def create_iter(f): + if settings.storey_filter and iterator_kwargs.get("include"): + iterator_kwargs["include"] = list( + filter(has_selected_parent, sum((f.by_type(x) for x in iterator_kwargs["include"]), [])) + ) + return ifcopenshell.geom.iterator(geom_settings, f, **iterator_kwargs) + + # We have to keep the iterator in memory because otherwise + # the styles are cleared up. + iterators = list( + map( + create_iter, + files, + ) + ) + + if settings.cache: + serializer_settings = ifcopenshell.geom.serializer_settings() + cache = ifcopenshell.geom.serializers.hdf5("cache.h5", geom_settings, serializer_settings) + for it in iterators: + it.set_cache(cache) + + # Initialize serializer + buffer = ifcopenshell.geom.serializers.buffer() + serialiser_settings = ifcopenshell.geom.serializer_settings() + sr = ifcopenshell.geom.serializers.svg(buffer, geom_settings, serialiser_settings) + + sr.setFile(files[0]) + if settings.auto_floorplan: + sr.setSectionHeightsFromStoreys() + + # setElevationRefGuid and setElevationRef are also mutually exclusive in C-code. + # Note that guid or object type are not checked anywhere to be valid, + # it's up to user to keep them valid for the provided projects. + if settings.drawing_guid or settings.drawing_object_type: + if settings.drawing_guid: + if not by_guid(settings.drawing_guid): + raise ValueError(f"Unable to find guid {settings.drawing_guid!r}") + sr.setElevationRefGuid(settings.drawing_guid) + elif settings.drawing_object_type: + sr.setElevationRef(settings.drawing_object_type) + sr.setWithoutStoreys(True) + + # required for svgfill + sr.setPolygonal(True) + sr.setUseNamespace(True) + + sr.setAlwaysProject(settings.include_projection) + + sr.setProfileThreshold(settings.profile_threshold) + sr.setBoundingRectangle(settings.width, settings.height) + sr.setScale(settings.scale) + sr.setAutoElevation(settings.auto_elevation) + sr.setAutoSection(settings.auto_section) + sr.setPrintSpaceNames(settings.space_names) + sr.setPrintSpaceAreas(settings.space_areas) + sr.setDrawDoorArcs(settings.door_arcs) + sr.setNoCSS(not not settings.css) + if settings.subtract_before_hlr: + sr.setSubtractionSettings(W.ALWAYS) + + sr.setUseHlrPoly(settings.hlr_poly) + sr.setUsePrefiltering(settings.prefilter) + sr.setUnifyInputs(settings.unify_inputs) + sr.setMirrorY(settings.mirror_y) + + try: + sh = ["none", "full", "left"].index(settings.storey_heights) + sr.setDrawStoreyHeights(sh) + except: + raise ValueError("storey_heights should be one of {'none', 'full', 'left'}") + + """ + # It is also possible to add drawing planes manually + import bpy + obj = bpy.context.active_object + sr.addDrawing( + obj.matrix_world.transposed()[3][0:3], # location + obj.matrix_world.transposed()[2][0:3], # z axis (view direction) + obj.matrix_world.transposed()[0][0:3], # x axis + "Test", # drawing name + True # include projection + ) + """ + + # Initialize tree + tree = ifcopenshell.geom.tree() + # This instructs the tree to explode BReps into faces and return + # the style of the face when running tree.select_ray() + tree.enable_face_styles(True) + + # Loop over iterators for geometric content + for i, it in enumerate(iterators): + for elem in it: + sr.write(elem) + if elem.type != "IfcSpace": + tree.add_element(elem) + progress_function("file", i, "progress", it.progress()) + + progress_function("hidden line rendering") + sr.finalize() + + # Obtain SVG output from serializer buffer + svg_data_1 = buffer.get_value() + + if not merge_projection: + return svg_data_1 + + if not settings.cells: + return svg_data_1.encode("ascii", "xmlcharrefreplace") + + def yield_groups(n, tag="g"): + if n.nodeType == n.ELEMENT_NODE and n.tagName == tag: + yield n + for c in n.childNodes: + yield from yield_groups(c, tag=tag) + + dom1 = parseString(svg_data_1) + svg1 = dom1.childNodes[0] + # From file 1 we take the groups to be substituted + groups1 = [g for g in yield_groups(svg1) if g.getAttribute("class") == "projection"] + + # Parse SVG into vector of line segments + # + # The second argument 'projection' tells the parser to only include groups + # that have the classname 'projection'. The IfcOpenShell SVG serializer puts + # the hidden line rendering output into this group. So the sections are not + # included here as they already form closed loops. + + ls_groups = W.svg_to_line_segments(svg_data_1, "projection") + for i, (ls, g1) in enumerate(zip(ls_groups, groups1)): + progress_function("creating cells", i) + + projection, g1 = g1, g1.parentNode + + svgfill_context = W.context(W.FILTERED_CARTESIAN_QUOTIENT, 1.0e-3) + + # remove duplicates (without tolerance) + ls = list(map(tuple, set(map(frozenset, ls)))) + + svgfill_context.add(ls) + + if settings.merge_cells: + # To be refined: + # - Find cells on original line segments + # - Associate cells with IFC entities for merging + # - Merge cells by discarding edges + # - Associate cells with IFC entities for styling + num_passes = 1 + else: + num_passes = 0 + + for iteration in range(num_passes + 1): + + # initialize empty group, note that in the current approach only one + # group is stored + ps = W.svg_groups_of_polygons() + + if iteration != 0 or svgfill_context.build(): + svgfill_context.write(ps) + + """ + # Debugging tool to plot line segments and cells + from matplotlib import pyplot as plt + + arr = numpy.array(ls).reshape((-1, 2, 2)) + for x in arr: + plt.plot(x.T[0], x.T[1]) + for x in ps[0]: + plt.fill(numpy.array(x.boundary).T[0], numpy.array(x.boundary).T[1]) + """ + + if iteration != num_passes: + pairs = svgfill_context.get_face_pairs() + semantics = [None] * (max(pairs) + 1) + # For every edge print the two neighbouring faces + # for x in range(0, len(pairs), 2): + # print(x // 2, *pairs[x:x+2]) + + # Reserialize cells into an SVG string + svg_data_2 = W.polygons_to_svg(ps, True) + + # We parse both SVG files to create on document with the combination of sections from + # the output directly from the serializer and the cells found from the hidden line + # rendering + dom2 = parseString(svg_data_2) + svg2 = dom2.childNodes[0] + # file 2 only has the groups we are interested in. + # in fact in the approach, it's only a single group + + g2 = next(yield_groups(svg2)) + + # These are attributes on the original group that we can use to reconstruct + # a 4x4 matrix of the projection used in the SVG generation process + nm = g1.getAttribute("ifc:name") + m4 = numpy.array(json.loads(g1.getAttribute("ifc:plane"))) + m3 = numpy.array(json.loads(g1.getAttribute("ifc:matrix3"))) + m44 = numpy.eye(4) + m44[0][0:2] = m3[0][0:2] + m44[1][0:2] = m3[1][0:2] + m44[0][3] = m3[0][2] + m44[1][3] = m3[1][2] + m44 = numpy.linalg.inv(m44) + + def project(xy, z=0.0): + xyzw = m44 @ numpy.array(xy + [z, 1.0]) + xyzw[1] *= -1.0 + return (m4 @ xyzw)[0:3] + + def pythonize(arr): + return tuple(map(float, arr)) + + # Loop over the cell paths + for pi, p in enumerate(g2.getElementsByTagName("path")): + + progress_function("group", i, "pass", iteration, "path", pi) + + d = p.getAttribute("d") + # point inside is an attribute that comes from line_segments_to_polygons() + # it is an arbitrary point guaranteed to be inside the polygon and outside + # of any potential inner bounds. We can use this to construct a ray to find + # the face of the IFC element that the cell belongs to. + assert p.hasAttribute("ifc:pointInside") + + xy = list(map(float, p.getAttribute("ifc:pointInside").split(","))) + + a, b = project(xy, 0.0), project(xy, -100.0) + + inside_elements = tree.select(pythonize(a)) + + if inside_elements: + elements = None + if iteration != num_passes: + semantics[pi] = (inside_elements[0], -1) + else: + elements = tree.select_ray(pythonize(a), pythonize(b - a)) + + if elements: + # Put the IFC element entity type on the path for CSS-based styling + p.setAttribute("class", elements[0].instance.is_a()) + + # Obtain style (IfcOpenShell IfcGeom::Material) + style = tree.styles()[elements[0].style_index] + + # This is just a demonstration. We compose a factor of using: + # - ray intersection distance + # - dot product ray . face normal + # - style transparency + # the factor determines how much white will be interpolated + # into the style diffuse color. + def clr(c): + if isinstance(c, ifcopenshell.ifcopenshell_wrapper.colour): + return c.r(), c.g(), c.b() + else: + return c + + clr = numpy.array(clr(style.diffuse) if style else (0.6, 0.6, 0.6)) + factor = (math.log(elements[0].distance + 2.0) / 7.0) * (1.0 - 0.5 * abs(elements[0].dot_product)) + if style and style.has_transparency: + factor *= 1.0 - style.transparency + clr = WHITE * (1.0 - factor) + clr * factor + + svg_fill = "rgb(%s)" % ", ".join(str(f * 255.0) for f in clr[0:3]) + + if iteration != num_passes: + semantics[pi] = elements[0] + else: + svg_fill = "none" + + p.setAttribute("style", "fill: " + svg_fill) + + if iteration != num_passes: + to_remove = [] + + for he_idx in range(0, len(pairs), 2): + # @todo instead of ray_distance, better do (x.point - y.point).dot(x.normal) + # to see if they're coplanar, because ray-distance will be different in case + # of element surfaces non-orthogonal to the view direction + + def format(x): + if x is None: + return None + elif isinstance(x, tuple): + # found to be inside element using tree.select() no face or style info + return x + else: + return (x.instance.is_a(), x.ray_distance, tuple(x.position)) + + pp = pairs[he_idx : he_idx + 2] + if pp == (-1, -1): + continue + data = list(map(format, map(semantics.__getitem__, pp))) + if None not in data and data[0][0] == data[1][0] and abs(data[0][1] - data[1][1]) < 1.0e-5: + to_remove.append(he_idx // 2) + # Print edge index and semantic data + # print(he_idx // 2, *data) + + svgfill_context.merge(to_remove) + + # Swap the XML nodes from the files + # Remove the original hidden line node we still have in the serializer output + g1.removeChild(projection) + g2.setAttribute("class", "projection") + # Find the children of the projection node parent + children = [x for x in g1.childNodes if x.nodeType == x.ELEMENT_NODE] + if children: + # Insert the new semantically enriched cell-based projection node + # *before* the node with sections from the serializer. SVG derives + # draw order from node order in the DOM so sections are draw over + # the projections. + g1.insertBefore(g2, children[0]) + else: + # This generally shouldn't happen + g1.appendChild(g2) + + if settings.arrange_spaces or settings.arrange_zones: + + if settings.storey_filter: + # delete storey groups not selected by filter + # sometimes happens in case of elements protruding multiple stories + # are assigned wrongly in the decomposition tree + for rg in (g for g in yield_groups(svg1) if g.parentNode.tagName == "svg"): + storey_guid = ifcopenshell.guid.compress(rg.attributes["id"].value.split("-", 1)[1].replace("-", "")) + storey = by_guid(storey_guid) + if settings.storey_filter not in (storey.Name or storey.GlobalId): + rg.parentNode.removeChild(rg) + + root_groups = [g for g in yield_groups(svg1) if g.parentNode.tagName == "svg"] + zone_groups = [] + + for grp in root_groups: + path_objects = [p for p in yield_groups(grp, "path") if "IfcSpace" in p.parentNode.getAttribute("class")] + + polies = [p.getAttribute("d") for p in path_objects] + + def break_at_second(char, s, offset=1): + i = s.find(char, offset) + if i == -1: + return s + else: + warnings.warn("Polygons with holes are not supported") + return s[0:i] + + def svg_to_coordlist(str): + return [[*map(float, s[1:].split(","))] for s in break_at_second("M", str).split(" ")[:-1]] + + polies = [svg_to_coordlist(d) for d in polies] + + def create_poly(b): + p = ifcopenshell.ifcopenshell_wrapper.polygon_2() + p.boundary = b + return p + + def min_bound_extent_p2(p): + arr = numpy.array(p.boundary) + return (arr.max(axis=0) - arr.min(axis=0)).min() > 0.5 + + def min_bound_extent_li(p): + arr = numpy.array(p) + return (arr.max(axis=0) - arr.min(axis=0)).min() > 0.5 + + def polygon_to_svg_path(doc, polygon: shapely.Polygon) -> str: + def ring_to_path(coords): + coords = list(coords)[:-1] + return "M " + " L ".join(f"{x},{y}" for x, y in coords) + " Z" + + rings = [polygon.exterior, *polygon.interiors] + d = " ".join(ring_to_path(r.coords) for r in rings) + + path = doc.createElement("path") + path.setAttribute("d", d) + path.setAttribute("fill-rule", "evenodd") + return path + + included = list(map(min_bound_extent_li, polies)) + polies = [p for p, incl in zip(polies, included) if incl] + + path_objects = [p for p, incl in zip(path_objects, included) if incl] + section_polies = list(map(shapely.Polygon, polies)) + polies = [create_poly(p) for p in polies] + + def has_relevant_zone(i): + inst = by_guid(path_objects[i].parentNode.attributes["ifc:guid"].value) + groups = [rel.RelatingGroup for rel in inst.HasAssignments if rel.is_a("IfcRelAssignsToGroup")] + if settings.zone_filter: + query, val = settings.zone_filter.rsplit("=", 1) + # cast to type encountered in pset prop + val = type_unsafe_value(val) + groups = [g for g in groups if ifcopenshell.util.selector.get_element_value(g, query) == val] + return len(groups) > 0 + + if settings.arrange_zones: + path_objects, section_polies, polies = zip( + *(tup for i, tup in enumerate(zip(path_objects, section_polies, polies)) if has_relevant_zone(i)) + ) + + arranged = W.arrange_polygons(polies) + svg_data_3 = W.polygons_to_svg(arranged, False) + dom3 = parseString(svg_data_3) + svg3 = dom3.childNodes[0] + g3 = next(yield_groups(svg3)) + arranged_polies = [] + for p in g3.getElementsByTagName("path"): + # arranged path + sp = shapely.Polygon(svg_to_coordlist(p.getAttribute("d"))) + arranged_polies.append(sp) + + # Mapping of arrange_poly_idx (stored as list) -> instance + # Obtained by point containment of sectionpoly in arranged + mapping = [None] * len(arranged_polies) + for i, p in enumerate(section_polies): + g = by_guid(path_objects[i].parentNode.attributes["ifc:guid"].value) + contains = [ap.contains(p.representative_point()) for ap in arranged_polies] + # arrangement, so this can generally be assumed + if sum(contains) == 1: + idx = contains.index(True) + # mapping[idx].append(g) + if mapping[idx] is None: + mapping[idx] = g + else: + warnings.warn(f"Not applying {g}; overlapping with {mapping[idx]}") + else: + warnings.warn(f"Point {p.representative_point()} not covered by arrangement") + + if settings.arrange_zones: + # @todo test whether output with only arrange_spaces is unaltered for bimlegal to function + + zone_assignment = [None] * len(arranged_polies) + + for i, m in enumerate(mapping): + if m is not None: + groups = [rel.RelatingGroup for rel in m.HasAssignments if rel.is_a("IfcRelAssignsToGroup")] + if settings.zone_filter: + query, val = settings.zone_filter.rsplit("=", 1) + # cast to type encountered in pset prop + val = type_unsafe_value(val) + groups = [ + g for g in groups if ifcopenshell.util.selector.get_element_value(g, query) == val + ] + zone_assignment[i] = frozenset(groups) + + all_zones = list(set(itertools.chain.from_iterable(a or () for a in zone_assignment))) + all_zone_memberships = [ + {i for i, zns in enumerate(zone_assignment) if zns is not None and zn in zns} for zn in all_zones + ] + + def union_find(sets): + merged = True + while merged: + merged = False + result = [] + while sets: + first, *rest = sets + first = set(first) + + # merge any overlapping sets into `first` + changed = True + while changed: + changed = False + new_rest = [] + for r in rest: + if first & r: # overlap? + first |= r + changed = True + merged = True + else: + new_rest.append(r) + rest = new_rest + result.append(first) + sets = rest + sets[:] = result + return sets + + to_merge = union_find(all_zone_memberships) + zone_groups.append(dom1.createElement("g")) + for idx_set in to_merge: + zone = next(iter(zone_assignment[max(idx_set)])) + + poly = shapely.unary_union([arranged_polies[i] for i in idx_set]) + poly = poly.geoms if poly.geom_type == "MultiPolygon" else [poly] + g = dom1.createElement("g") + + def classes(): + yield zone.is_a() + for propname, propval in reduce( + operator.or_, ifcopenshell.util.element.get_psets(zone).values() + ).items(): + if propval is True: + yield propname + + g.setAttribute("class", " ".join(classes())) + for p in poly: + g.appendChild(polygon_to_svg_path(dom1, p)) + + if (lbl := settings.zone_label) and ( + val := ifcopenshell.util.selector.get_element_value(zone, lbl) + ): + pt = p.representative_point() + text_el = dom1.createElement("text") + text_el.setAttribute("x", str(pt.x)) + text_el.setAttribute("y", str(pt.y)) + text_el.appendChild(dom1.createTextNode(str(val))) + g.appendChild(text_el) + zone_groups[-1].appendChild(g) + else: + zone_groups.append(g3) + + for rg, zg in zip(root_groups, zone_groups): + if not settings.arrange_zones: + for p in rg.getElementsByTagName("path"): + p.setAttribute("style", "fill: none; stroke: black; stroke-width: 0.05") + rg.appendChild(zg) + + if settings.css: + svg = dom1.documentElement + style = dom1.createElement("style") + style.setAttribute("type", "text/css") + style.appendChild( + dom1.createTextNode(open(settings.css[1:]).read() if settings.css.startswith("@") else settings.css) + ) + svg.insertBefore(style, svg.firstChild) + + data = dom1.toprettyxml() + data = data.encode("ascii", "xmlcharrefreplace") + + return data + + +if __name__ == "__main__": + import sys + import time + import argparse + + times = [] + + def measure(task, fn): + t0 = time.time() + r = fn() + dt = time.time() - t0 + times.append((task, dt)) + return r + + def print_progress(*args): + print("\r", *args, " " * 10, end="", flush=True) + + parser = argparse.ArgumentParser() + + parser.add_argument( + "files", + type=str, + nargs="+", + help=( + "List of files for script to use. " + "Last file is considered an output file (.svg), all other files are existing IFC files." + ), + ) + + for field in fields(draw_settings): + name = field.name.replace("_", "-") + description = field.metadata.get("doc") or "" + description += " " if description else "" + description += f"Default: {repr(field.default)}." + if field.type == bool: + parser.add_argument( + f"--{name}", + help=description, + dest=field.name, + action="store_true", + ) + parser.add_argument(f"--no-{name}", dest=field.name, action="store_false") + parser.set_defaults(**{field.name: field.default}) + else: + parser.add_argument(f"--{name}", help=description, dest=field.name, type=field.type, default=field.default) + + args = vars(parser.parse_args()) + + if len(args["files"]) < 2: + parser.error("At least 2 files are required: one or more input files and one output file.") + + files = args.pop("files") + output = files.pop() + + settings = draw_settings(**args) + + files = measure("open files", lambda: list(map(ifcopenshell.open, files))) + result = measure("processing", lambda: main(settings, files, progress_function=print_progress)) + open(output, "wb").write(result) + + print("\r Done!", " " * 20) + + for t, dt in times: + print(f"{t}: {dt}") diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/entity_instance.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/entity_instance.py new file mode 100644 index 0000000000000000000000000000000000000000..0cae2608f3ba172773c3e1de5c822a0462863083 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/entity_instance.py @@ -0,0 +1,654 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Thomas Krijnen +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# IfcOpenShell is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with IfcOpenShell. If not, see . + + +from __future__ import annotations +import functools +import importlib +import numbers +import itertools +import operator +import subprocess +import sys +import time +from typing import Union, Any, TypeVar, overload, TYPE_CHECKING, cast, NoReturn +from collections.abc import Callable, Sequence + +from . import ifcopenshell_wrapper +from . import settings + +if TYPE_CHECKING: + import ifcopenshell + +try: + import logging +except ImportError: + logging = type("logger", (object,), {"exception": staticmethod(lambda s: print(s))}) + +T = TypeVar("T") + + +def set_derived_attribute(*args): + raise TypeError("Unable to set derived attribute") + + +def set_unsupported_attribute(*args): + raise TypeError("This is an unsupported attribute type") + + +# For every schema and its entities populate a list +# of functions for every entity attribute (including +# inherited attributes) to set that particular +# attribute by index. +# For example. IFC2X3.IfcWall with have a list of +# 9 methods. The first will point at +# ifcopenshell.ifcopenshell_wrapper.entity_instance.setArgumentAsString +# because the first attribute GlobalId ultimately +# is of type string. +# Previously, resolving the appropriate function was +# done for each invocation of __setitem__. Now this +# mapping is built once during initialization of the +# module. +MethodList = list[Callable[[ifcopenshell_wrapper.entity_instance, int, Any], Union[None, NoReturn]]] +"""List of setter methods for class attributes.""" +_method_dict: dict[str, MethodList] = {} +"""Mapping of entity classes (e.g. 'IFC4.IfcWall') to MethodLists.""" + + +def register_schema_attributes(schema: ifcopenshell_wrapper.schema_definition) -> None: + for decl in schema.declarations(): + if hasattr(decl, "argument_types"): + fq_name = ".".join((schema.name(), decl.name())) + + # get type strings as reported by IfcOpenShell C++ + type_strs = decl.argument_types() + type_strs = cast(Sequence[str], type_strs) + + # convert case for setter function + type_strs = [x.title().replace(" ", "") for x in type_strs] + + # binary and enumeration are passed from python as string as well + type_strs = [x.replace("Binary", "String") for x in type_strs] + type_strs = [x.replace("Enumeration", "String") for x in type_strs] + + # prefix to get method names + fn_names = ["setArgumentAs" + x for x in type_strs] + + # resolve to actual functions in wrapper + functions = [ + ( + set_derived_attribute + if mname == "setArgumentAsDerived" + else ( + set_unsupported_attribute + if mname == "setArgumentAsUnknown" + else getattr(ifcopenshell_wrapper.entity_instance, mname) + ) + ) + for mname in fn_names + ] + + _method_dict[fq_name] = functions + + +for nm in ifcopenshell_wrapper.schema_names(): + schema = ifcopenshell_wrapper.schema_by_name(nm) + register_schema_attributes(schema) + + +class entity_instance: + """Represents an entity (wall, slab, property, etc) of an IFC model + + An IFC model consists of entities. Examples of entities include walls, + slabs, doors and so on. Entities can also be non-physical things, like + properties, systems, construction tasks, colours, geometry, and more. + + Entities are defined through an **IFC Class**. There are hundreds of **IFC + Classes** defined as part of the ISO standard by the buildingSMART + International organisation. The **IFC Class** defines the attributes of an + entity, as well as the data types and whether or not an attribute is + mandatory or optional. + + IfcOpenShell's API dynamically implements the IFC schema. You will not find + documentation about available **IFC Classes**, or what attributes they + have. Please consult the buildingSMART official documentation or start + reading :doc:`/introduction/introduction_to_ifc`. + + In addition to the Python methods you see documented here, an instantiated + entity_instance will have attributes defined by its IFC class. For example, + an entity instance which is an IfcWall class will have a ``Name`` + attribute, and an IfcColourRgb will have a ``Red`` attribute. Please + consult the buildingSMART official documentation. + + Example: + + .. code:: python + + model = ifcopenshell.open(file_path) + walls = model.by_type("IfcWall") + wall = walls[0] + + print(wall) # #38=IFCWALL('2MEinnTPbCMwLOgceaQZFu',$,$,'My Wall',$,#52,#47,$,$); + print(wall.is_a()) # IfcWall + + # Note: the `Name` attribute is dynamic, based on the IFC class. + print(wall.Name) # My Wall + + # Attributes are ordered and may also be accessed via index. + print(wall[3]) # My Wall + + print(wall.__class__) # + """ + + wrapped_data: ifcopenshell_wrapper.entity_instance + method_list: Union[MethodList, None] = None + + def __init__( + self, + e: Union[ifcopenshell_wrapper.entity_instance, tuple[str, str]], + file: Union[ifcopenshell.file, None] = None, + ): + """ + :param e: Wrapper's ``entity_instance`` or a tuple ``(schema_identifier, ifc_class)``. + """ + # Instances of this class will be created and removed very often, + # so it's important to keep it very optimized. + + if isinstance(e, tuple): + e = ifcopenshell_wrapper.new_IfcBaseClass(*e) + object.__setattr__(self, "wrapped_data", e) + + # Make sure the file is not gc'ed while we have live instances + e.file = file + + def __del__(self): + """ + #2471 while the precise chain of action is unclear, creating + instance references prevents file gc, even with all instance + refs deleted. This is a work-around for that. + """ + # Avoid infinite recursion if entity is failed to initialize + # and wrapped_data is unset. Hacky since we override + # both __dict__ and __dir__. + try: + wrapped_data = object.__getattribute__(self, "wrapped_data") + wrapped_data.file = None + except AttributeError: + return + + @property + def file(self): + # ugh circular imports, name collisions + from . import file + + return file.from_pointer(self.wrapped_data.file_pointer()) + + def __getattr__(self, name: str) -> Any: + """ + Any aggregate attributes (e.g. `SET`) are returns as Python tuples. + + Inverse attributes are always returned as tuples, even it's not a set origially in IFC + (e.g. IfcFeatureElementSubtraction.VoidsElements) + """ + INVALID, FORWARD, INVERSE = range(3) + attr_cat = self.wrapped_data.get_attribute_category(name) + if attr_cat == FORWARD: + idx = self.wrapped_data.get_argument_index(name) + if _method_dict[self.is_a(True)][idx] != set_derived_attribute: + # A bit ugly, but we fall through to derived attribute handling below + return entity_instance.wrap_value(self.wrapped_data.get_argument(idx), self.wrapped_data.file) + elif attr_cat == INVERSE: + vs = entity_instance.wrap_value(self.wrapped_data.get_inverse(name), self.wrapped_data.file) + if settings.unpack_non_aggregate_inverses: + schema_name = self.wrapped_data.is_a(True).split(".")[0] + ent: ifcopenshell_wrapper.entity + ent = ifcopenshell_wrapper.schema_by_name(schema_name).declaration_by_name(self.is_a()) + inv = next(i for i in ent.all_inverse_attributes() if i.name() == name) + if (inv.bound1(), inv.bound2()) == (-1, -1): + if vs: + vs = vs[0] + else: + vs = None + return vs + + # derived attribute perhaps? + schema_name = self.wrapped_data.is_a(True).split(".")[0] + try: + rules = importlib.import_module(f"ifcopenshell.express.rules.{schema_name}") + except: + import os + + current_dir_files = {fn.lower(): fn for fn in os.listdir(".")} + exp_filename = schema_name.lower() + ".exp" + schema_path = current_dir_files.get(exp_filename) + if schema_path is None: + raise Exception( + f"Couldn't find express file '{schema_name.lower()}.exp' in the current folder: '{os.getcwd()}'." + ) + fn = schema_path[:-4] + ".py" + if not os.path.exists(fn): + subprocess.run( + [sys.executable, "-m", "ifcopenshell.express.rule_compiler", schema_path, fn], check=True + ) + time.sleep(1.0) + rules = importlib.import_module(schema_name) + + def yield_supertypes(): + decl = ifcopenshell_wrapper.schema_by_name(schema_name).declaration_by_name(self.is_a()) + while decl: + yield decl.name() + decl = decl.supertype() + + for sty in yield_supertypes(): + fn = getattr(rules, f"calc_{sty}_{name}", None) + if fn: + return fn(self) + + if attr_cat != FORWARD: + raise AttributeError( + "entity instance of type '%s' has no attribute '%s'" % (self.wrapped_data.is_a(True), name) + ) + + @staticmethod + def walk(f: Callable[[Any], bool], g: Callable[[Any], Any], value: Any) -> Any: + """Applies a transformation to `value` based on a given condition. + + If value is a nested structure (e.g., a list or a tuple) will apply + transformation to it's elements. + + :param f: A callable that takes a single argument and returns a boolean + value. It represents the condition. + :param g: A callable that takes a single argument and returns a + transformed value. It represents the transformation. + :param value: Any object, the input value to be processed + :return: Transformed value + + Example: + + .. code:: python + + # Define condition and transformation functions + condition = lambda v: v == old + transform = lambda v: new + + # Usage example + attribute_value = element.RelatedElements + print(old in attribute_value, new in attribute_value) # True, False + + result = element.walk(condition, transform, element.RelatedElements) + print(old in attribute_value, new in attribute_value) # False, True + """ + + if isinstance(value, (tuple, list)): + return tuple(map(functools.partial(entity_instance.walk, f, g), value)) + elif f(value): + return g(value) + else: + return value + + @staticmethod + def wrap_value(v, file: ifcopenshell.file): + def wrap(e: ifcopenshell_wrapper.entity_instance) -> entity_instance: + return entity_instance(e, file) + + def is_instance(e: Any) -> bool: + return isinstance(e, ifcopenshell_wrapper.entity_instance) + + return entity_instance.walk(is_instance, wrap, v) + + @staticmethod + def unwrap_value(v): + def unwrap(e): + return e.wrapped_data + + def is_instance(e): + return isinstance(e, entity_instance) + + return entity_instance.walk(is_instance, unwrap, v) + + def attribute_type(self, attr: Union[int, str]) -> str: + """Return the data type of a positional attribute of the element + + :param attr: The index or name of the attribute + """ + attr_idx = attr if isinstance(attr, numbers.Integral) else self.wrapped_data.get_argument_index(attr) + return self.wrapped_data.get_argument_type(attr_idx) + + def attribute_name(self, attr_idx: int) -> str: + """Return the name of a positional attribute of the element + + :param attr_idx: The index of the attribute + """ + return self.wrapped_data.get_argument_name(attr_idx) + + def __setattr__(self, key: str, value: Any) -> None: + index = self.wrapped_data.get_argument_index(key) + try: + self[index] = value + except IndexError as e: + # get_argument_index returns 0xFFFFFFFF if attribute is not found + if index == 0xFFFFFFFF: + raise AttributeError( + "entity instance of type '%s' has no attribute '%s'" % (self.wrapped_data.is_a(True), key) + ) + raise e + + def __getitem__(self, key: int) -> Any: + if key < 0 or key >= len(self): + raise IndexError("Attribute index {} out of range for instance of type {}".format(key, self.is_a())) + return entity_instance.wrap_value(self.wrapped_data.get_argument(key), self.wrapped_data.file) + + def __setitem__(self, idx: int, value: T) -> T: + if self.wrapped_data.file and self.wrapped_data.file.transaction: + self.wrapped_data.file.transaction.store_edit(self, idx, value) + + if self.method_list is None: + super().__setattr__("method_list", _method_dict[self.is_a(True)]) + + method = self.method_list[idx] + + if value is None: + if method is not set_derived_attribute: + try: + self.wrapped_data.setArgumentAsNull(idx) + except RuntimeError as e: + if e.args == ("Attribute not set",): + raise TypeError( + "attribute '%s' is not optional for entity instance of type '%s'" + % (self.wrapped_data.get_argument_name(idx), self.wrapped_data.is_a(True)) + ) + raise e + else: + try: + self.method_list[idx](self.wrapped_data, idx, entity_instance.unwrap_value(value)) + except TypeError: + raise TypeError( + "attribute '%s' for entity '%s' is expecting value of type '%s', got '%s'." + % ( + self.wrapped_data.get_argument_name(idx), + self.wrapped_data.is_a(True), + self.wrapped_data.get_argument_type(idx), + type(value).__name__, + ) + ) + + return value + + def __len__(self): + return len(self.wrapped_data) + + def __repr__(self): + return repr(self.wrapped_data) + + def to_string(self, valid_spf=True) -> str: + """Returns a string representation of the current entity instance. + Equal to str(self) when valid_spf=False. When valid_spf is True + returns a representation of the string that conforms to valid Step + Physical File notation. The difference being entity names in upper + case and string attribute values with unicode values encoded per + the specific control directives. + """ + + return self.wrapped_data.to_string(valid_spf) + + @overload + def is_a(self) -> str: ... + @overload + def is_a(self, ifc_class: str) -> bool: ... + @overload + def is_a(self, with_schema: bool) -> str: ... + def is_a(self, *args: Union[str, bool]) -> Union[str, bool]: + """Return the IFC class name of an instance, or checks if an instance belongs to a class. + + The check will also return true if a parent class name is provided. + + :param args: If specified, is a case insensitive IFC class name to check + or if specified as a boolean then will define whether + returned IFC class name should include schema name + (e.g. "IFC4.IfcWall" if `True` and "IfcWall" if `False`). + If omitted will act as `False`. + :returns: Either the name of the class, or a boolean if it passes the check + + Example: + + .. code:: python + + f = ifcopenshell.file() + f.create_entity('IfcPerson') + f.is_a() + >>> 'IfcPerson' + f.is_a('IfcPerson') + >>> True + """ + return self.wrapped_data.is_a(*args) + + def id(self) -> int: + """Return the STEP numerical identifier""" + return self.wrapped_data.id() + + def __eq__(self, other: entity_instance) -> bool: + if not isinstance(self, type(other)): + return False + elif None in (self.wrapped_data.file, other.wrapped_data.file): + # when not added to a file, we can only compare attribute values + # and we need this for where rule evaluation + return self.get_info_2(recursive=True, include_identifier=False) == other.get_info_2( + recursive=True, include_identifier=False + ) + else: + # Proper entity instances have a stable identity by means of the numeric + # step id. Selected type instances (such as IfcPropertySingleValue.NominalValue + # always have id=0, so we compare + if self.id(): + return self.wrapped_data == other.wrapped_data + else: + return (self.is_a(), self[0], self.wrapped_data.file_pointer()) == ( + other.is_a(), + other[0], + other.wrapped_data.file_pointer(), + ) + + def is_entity(self) -> bool: + """Tests whether the instance is an entity type as opposed to a simple data type. + + :return: True if the instance is an entity + """ + schema_name = self.wrapped_data.is_a(True).split(".")[0] + decl = ifcopenshell_wrapper.schema_by_name(schema_name).declaration_by_name(self.is_a()) + return isinstance(decl, ifcopenshell_wrapper.entity) + + def compare(self, other, op, reverse=False): + """Compares with another instance. + + For simple types the declaration name is not taken into account: + + >>> f = ifcopenshell.file() + >>> f.createIfcInteger(0) < f.createIfcPositiveInteger(1) + True + + For entity types the declaration name is taken into account: + + >>> f.createIfcWall('a') < f.createIfcWall('b') + True + + >>> f.createIfcWallStandardCase('a') < f.createIfcWall('b') + False + + Comparing simple types with different underlying types throws an exception: + + >>> f.createIfcInteger(0) < f.createIfcLabel('x') + Traceback (most recent call last): + File "", line 1, in + File "entity_instance.py", line 371, in compare + return op(a, b) + TypeError: '<' not supported between instances of 'int' and 'str' + + :param other: Right hand side (or lhs when reverse = True) + :param op: The comparison operator (likely from the operator module) + :param reverse: When true swaps lhs and rhs. Defaults to False. + + :return: bool: The comparison predicate applied to self and other + """ + + if isinstance(other, entity_instance): + a, b = map(tuple, (self, other)) + if any(map(entity_instance.is_entity, (self, other))): + a = (self.is_a(),) + a + b = (other.is_a(),) + b + elif self.is_entity(): + a = tuple(self) + b = other + if isinstance(b, list): + b = tuple(b) + if not isinstance(b, tuple): + b = (b,) + else: + a = self[0] + b = other + + if reverse: + a, b = b, a + + return op(a, b) + + __le__ = functools.partialmethod(compare, op=operator.le) + __lt__ = functools.partialmethod(compare, op=operator.lt) + __ge__ = functools.partialmethod(compare, op=operator.ge) + __gt__ = functools.partialmethod(compare, op=operator.gt) + __rle__ = functools.partialmethod(compare, op=operator.le, reverse=True) + __rlt__ = functools.partialmethod(compare, op=operator.lt, reverse=True) + __rge__ = functools.partialmethod(compare, op=operator.ge, reverse=True) + __rgt__ = functools.partialmethod(compare, op=operator.gt, reverse=True) + + def __hash__(self): + # Proper entity instances have a stable identity by means of the numeric + # step id. Selected type instances (such as IfcPropertySingleValue.NominalValue + # always have id=0, so we hash + if id_ := self.id(): + return hash((id_, self.wrapped_data.file_pointer())) + else: + return hash((self.is_a(), self[0], self.wrapped_data.file_pointer())) + + def __dir__(self): + return sorted( + set( + itertools.chain( + dir(type(self)), + map(str, self.wrapped_data.get_attribute_names()), + map(str, self.wrapped_data.get_inverse_attribute_names()), + ) + ) + ) + + def get_info( + self, + include_identifier: bool = True, + recursive: bool = False, + return_type: Union[type[dict], type] = dict, + ignore: Sequence[str] = (), + scalar_only: bool = False, + ) -> dict[str, Any]: + """Return a dictionary of the entity_instance's properties (Python and IFC) and their values. + + Resulting dictionary keys: 'id', 'type', all entity attribute names. + + :param include_identifier: Whether or not to include the STEP numerical identifier + :param recursive: Whether or not to convert referenced IFC elements into dictionaries too. All attributes also apply recursively + :param return_type: The return data type to be casted into + :param ignore: A list of attribute names to ignore + :param scalar_only: Filters out all values that are IFC instances + :returns: A dictionary of properties and their corresponding values + + Example: + + .. code:: python + + ifc_file = ifcopenshell.open(file_path) + products = ifc_file.by_type("IfcProduct") + obj_info = products[0].get_info() + print(obj_info.keys()) + >>> dict_keys(['Description', 'Name', 'BuildingAddress', 'LongName', 'GlobalId', 'ObjectPlacement', 'OwnerHistory', 'ObjectType', + >>> ...'ElevationOfTerrain', 'CompositionType', 'id', 'Representation', 'type', 'ElevationOfRefHeight']) + """ + + def _(): + try: + if include_identifier: + yield "id", self.id() + yield "type", self.is_a() + except BaseException: + logging.exception("unhandled exception while getting id / type info on {}".format(self)) + for i in range(len(self)): + try: + if self.wrapped_data.get_attribute_names()[i] in ignore: + continue + attr_value = self[i] + + to_include = {"v": True} + + if recursive or scalar_only: + + def is_instance(e): + return isinstance(e, entity_instance) + + def get_info_(inst): + return entity_instance.get_info( + inst, + include_identifier=include_identifier, + recursive=recursive, + return_type=return_type, + ignore=ignore, + ) + + def do_ignore(inst): + to_include["v"] = False + return None + + attr_value = entity_instance.walk( + is_instance, get_info_ if recursive else do_ignore, attr_value + ) + + if to_include["v"]: + yield self.attribute_name(i), attr_value + except BaseException: + logging.exception("unhandled exception occurred setting attribute name for {}".format(self)) + + return return_type(_()) + + __dict__ = property(get_info) + + def get_info_2( + self, + include_identifier: bool = True, + recursive: bool = False, + return_type: type[dict] = dict, + ignore: Sequence[str] = (), + ) -> dict[str, Any]: + """More perfomant version of `.get_info()` but with limited arguments values.\n + Method has exactly the same signature as `.get_info()` but it doesn't support getting information non-recursively. + + Currently supported arguments values: + * recursive: `True` (will fail with default `False` value from `.get_info()`) + * return_type: `dict` + * ignore: `()` (empty tuple) + """ + + assert recursive + assert return_type is dict + assert len(ignore) == 0 + return ifcopenshell_wrapper.get_info_cpp(self.wrapped_data, include_identifier) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/file.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/file.py new file mode 100644 index 0000000000000000000000000000000000000000..0aadacfbfc66c7b02071abaa2e5c77c3acbf27de --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/file.py @@ -0,0 +1,1070 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Thomas Krijnen +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# IfcOpenShell is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with IfcOpenShell. If not, see . + +from __future__ import annotations +import os +import re +import numbers +import time +import zipfile +import functools +import ifcopenshell +import weakref +import types +from pathlib import Path +from typing import Any, Optional, TYPE_CHECKING, Union, overload, Literal, TypedDict +from collections.abc import Callable, Generator +from typing_extensions import assert_never + +from . import ifcopenshell_wrapper +from .entity_instance import entity_instance + +from ifcopenshell.util.mvd_info import MvdInfo, LARK_AVAILABLE + +if TYPE_CHECKING: + import ifcopenshell.util.schema + + InverseReference = tuple[int, Any] + ElementInverses = dict[int, list[InverseReference]] + + class CreateOperation(TypedDict): + action: Literal["create"] + value: Any + + class EditOperation(TypedDict): + action: Literal["edit"] + id: int + index: int + old: Any + new: Any + + class DeleteOperation(TypedDict): + action: Literal["delete"] + inverses: ElementInverses + value: Any + + class BatchDeleteOperation(TypedDict): + action: Literal["batch_delete"] + inverses: ElementInverses + + TransactionOperation = Union[CreateOperation, EditOperation, DeleteOperation, BatchDeleteOperation] + +HEADER_FIELDS = { + "file_description": [ + "description", + "implementation_level", + ], + "file_name": [ + "name", + "time_stamp", + "author", + "organization", + "preprocessor_version", + "originating_system", + "authorization", + ], +} + + +class UndoSystemError(Exception): + def __init__(self, message: str, transaction: Transaction): + super().__init__(message) + self.transaction = transaction + + +class Transaction: + operations: list[TransactionOperation] + batch_inverses: list[ElementInverses] + batch_delete_ids: set[int] + + def __init__(self, ifc_file: file): + self.file: file = ifc_file + self.operations = [] + self.is_batched = False + self.batch_delete_index = 0 + self.batch_delete_ids = set() + self.batch_inverses = [] + + def serialise_entity_instance(self, element: ifcopenshell.entity_instance) -> dict[str, Any]: + info = element.get_info() + for key, value in info.items(): + info[key] = self.serialise_value(element, value) + return info + + def serialise_value(self, element, value) -> Any: + return element.walk( + lambda v: isinstance(v, entity_instance), + lambda v: {"id": v.id()} if v.id() else {"type": v.is_a(), "value": v.wrappedValue}, + value, + ) + + def unserialise_value(self, element, value) -> Any: + return element.walk( + lambda v: isinstance(v, dict), + lambda v: self.file.by_id(v["id"]) if v.get("id") else self.file.create_entity(v["type"], v["value"]), + value, + ) + + def batch(self) -> None: + self.is_batched = True + self.batch_delete_index = len(self.operations) + self.batch_delete_ids = set() + self.batch_inverses = [] + + def unbatch(self) -> None: + for inverses in self.batch_inverses: + if inverses: + self.operations.insert(self.batch_delete_index, {"action": "batch_delete", "inverses": inverses}) + self.is_batched = False + self.batch_delete_index = 0 + self.batch_delete_ids = set() + self.batch_inverses = [] + + def store_create(self, element: ifcopenshell.entity_instance) -> None: + if element.id(): + self.operations.append({"action": "create", "value": self.serialise_entity_instance(element)}) + + def store_edit(self, element: ifcopenshell.entity_instance, index: int, value: Any) -> None: + if element.id(): + self.operations.append( + { + "action": "edit", + "id": element.id(), + "index": index, + "old": self.serialise_value(element, element[index]), + "new": self.serialise_value(element, value), + } + ) + + def store_delete(self, element: ifcopenshell.entity_instance) -> None: + inverses = {} + if self.is_batched: + if element.id() not in self.batch_delete_ids: + self.batch_inverses.append(self.get_element_inverses(element)) + self.batch_delete_ids.add(element.id()) + else: + inverses = self.get_element_inverses(element) + self.operations.append( + {"action": "delete", "inverses": inverses, "value": self.serialise_entity_instance(element)} + ) + + def get_element_inverses(self, element: ifcopenshell.entity_instance) -> ElementInverses: + inverses: ElementInverses = {} + for inverse in self.file.get_inverse(element): + inverse_references: list[InverseReference] = [] + for i, attribute in enumerate(inverse): + if self.has_element_reference(attribute, element): + inverse_references.append((i, self.serialise_value(inverse, attribute))) + inverses[inverse.id()] = inverse_references + return inverses + + def has_element_reference(self, value: Any, element: ifcopenshell.entity_instance) -> bool: + if isinstance(value, (tuple, list)): + for v in value: + if self.has_element_reference(v, element): + return True + return False + return value == element + + def rollback(self) -> None: + for operation in self.operations[::-1]: + if operation["action"] == "create": + element = self.file.by_id(operation["value"]["id"]) + if hasattr(element, "GlobalId") and element.GlobalId is None: + # hack, otherwise ifcopenshell gets upset + element.GlobalId = "x" + self.file.remove(element) + elif operation["action"] == "edit": + element = self.file.by_id(operation["id"]) + try: + element[operation["index"]] = self.unserialise_value(element, operation["old"]) + except: + # Catch discrepancy where IfcOpenShell creates but doesn't allow editing of invalid values + pass + elif operation["action"] == "delete": + e = self.file.create_entity(operation["value"]["type"], id=operation["value"]["id"]) + for k, v in operation["value"].items(): + try: + setattr(e, k, self.unserialise_value(e, v)) + except: + # Catch discrepancy where IfcOpenShell creates but doesn't allow editing of invalid values + pass + for inverse_id, data in operation["inverses"].items(): + inverse = self.file.by_id(inverse_id) + for index, value in data: + inverse[index] = self.unserialise_value(inverse, value) + elif operation["action"] == "batch_delete": + for inverse_id, data in operation["inverses"].items(): + inverse = self.file.by_id(inverse_id) + for index, value in data: + inverse[index] = self.unserialise_value(inverse, value) + else: + assert_never(operation["action"]) + + def commit(self) -> None: + for operation in self.operations: + if operation["action"] == "create": + e = self.file.create_entity(operation["value"]["type"], id=operation["value"]["id"]) + for k, v in operation["value"].items(): + try: + setattr(e, k, self.unserialise_value(e, v)) + except: + # Catch discrepancy where IfcOpenShell creates but doesn't allow editing of invalid values + pass + elif operation["action"] == "edit": + element = self.file.by_id(operation["id"]) + element[operation["index"]] = self.unserialise_value(element, operation["new"]) + elif operation["action"] == "delete": + element = self.file.by_id(operation["value"]["id"]) + self.file.remove(element) + elif operation["action"] == "batch_delete": + pass + else: + assert_never(operation["action"]) + + +file_dict: dict[int, tuple[weakref.ReferenceType[file], int]] = {} +"""Mapping of internal IfcFile pointer address to existing ``ifcopenshell.file`` +and the timestamp when it was created. + +Needed only to quickly access related from ``entity_instance`` it's ``file``. +""" + +READ_ERROR = ifcopenshell_wrapper.file_open_status.READ_ERROR +NO_HEADER = ifcopenshell_wrapper.file_open_status.NO_HEADER +UNSUPPORTED_SCHEMA = ifcopenshell_wrapper.file_open_status.UNSUPPORTED_SCHEMA +INVALID_SYNTAX = ifcopenshell_wrapper.file_open_status.INVALID_SYNTAX + +# TODO: Workaround for old builds, remove after build stabilizes. +try: + UNKNOWN = ifcopenshell_wrapper.file_open_status.UNKNOWN +except: + UNKNOWN = 5 # Workaround + +import struct + + +def consume_buffer(val, inner): + while val: + s = struct.unpack("@q", val[:8])[0] + val = val[8:] + yield inner(val[0:s]) + val = val[s:] + + +binary_deserializers = ( + lambda __, _: None, + lambda __, _: None, + lambda __, val: struct.unpack("@i", val)[0], + lambda __, val: val[0] == 1, + # @todo 3 state + lambda __, val: val[0] == 1, + lambda __, val: struct.unpack("@d", val)[0], + lambda __, val: val.decode("utf-8"), + lambda __, val: val.decode("utf-8"), + lambda storage, val: ifcopenshell_wrapper.schema_by_name(storage.schema_identifier) + .declarations()[struct.unpack("@q", val[:8])[0]] + .enumeration_items()[struct.unpack("@q", val[8:])[0]], + lambda storage, val: storage.by_id((val[0] == 105, struct.unpack("@q", val[1:])[0])), + lambda __, _: (), + lambda __, val: struct.unpack("@" + "i" * (len(val) // 4), val), + lambda __, val: struct.unpack("@" + "d" * (len(val) // 8), val), + lambda __, val: tuple(consume_buffer(val, lambda inner: inner.decode("utf-8"))), + lambda __, val: tuple(consume_buffer(val, lambda inner: inner.decode("utf-8"))), + lambda storage, val: tuple( + storage.by_id((val[i * 9] == 105, struct.unpack("@q", val[i * 9 + 1 : i * 9 + 9])[0])) + for i in range(len(val) // 9) + ), + lambda __, _: ((),), + lambda __, val: tuple( + consume_buffer(val, lambda inner: struct.unpack("@" + 105 * (len(inner) // struct.calcsize("@i")), inner)) + ), + lambda __, val: tuple( + consume_buffer(val, lambda inner: struct.unpack("@" + "d" * (len(inner) // struct.calcsize("@d")), inner)) + ), + lambda storage, val: tuple( + consume_buffer( + val, + lambda inner: tuple( + storage.by_id((inner[i * 9] == 105, struct.unpack("@q", inner[i * 9 + 1 : i * 9 + 9])[0])) + for i in range(len(inner) // 9) + ), + ) + ), +) + + +@functools.cache +def attribute_lookup(schema_name, entity_name): + decl = ifcopenshell_wrapper.schema_by_name(schema_name).declaration_by_name(entity_name) + attributes = decl.as_entity().all_attributes() + di = {v: k for k, v in enumerate(a.name() for a in attributes)} + all_inverses = decl.as_entity().all_inverse_attributes() + for inv in all_inverses: + + def visit(decl): + yield decl.index_in_schema() + for ty in decl.subtypes(): + yield from visit(ty) + + attribute_index = inv.entity_reference().attribute_index(inv.attribute_reference()) + entity_indices = list(visit(inv.entity_reference())) + di[inv.name()] = (entity_indices, attribute_index) + return di + + +@functools.cache +def entity_name_lookup(schema_name, index): + return ifcopenshell_wrapper.schema_by_name(schema_name).declarations()[index].name() + + +class rocksdb_lazy_instance: + __slots__ = ("storage", "name") + + def _transform_value(self, val: bytes) -> Any: + if not val: + return None + # ord('A') is 65 + return binary_deserializers[val[0] - 65](self.storage, val[1:]) + + def __init__(self, storage, name): + self.storage = storage + self.name = name + + @functools.cache + def is_a(self): + if self.name.startswith("h|"): + return self.name[2:] + idx = struct.unpack("@q", self.storage.read(f"{self.name}|_"))[0] + return entity_name_lookup(self.storage.schema_identifier, idx) + + def __getattr__(self, name): + attr = attribute_lookup(self.storage.schema_identifier, self.is_a()).get(name) + if isinstance(attr, int): + return self[attr] + else: + entity_indices, attribute_index = attr + + def _(): + for index_in_schema in entity_indices: + buffer = self.storage.read(f"v|{self.name[2:]}|{index_in_schema}|{attribute_index}") or b"" + yield from map(self.storage.by_id, struct.unpack("<" + "I" * (len(buffer) // 4), buffer)) + + return list(_()) + + def __getitem__(self, index): + return self._transform_value(self.storage.read(f"{self.name}|{index}")) + + @functools.cache + def __len__(self): + return ( + max( + map( + int, + filter( + lambda s: s.isdigit(), + (k.split(b"|")[2] for k, v in self.storage.prefix(f"{self.name}|").items()), + ), + ), + default=-1, + ) + + 1 + ) + + def __iter__(self): + for i in range(len(self)): + yield self[i] + + def __repr__(self): + pre = f"#{self.name[2:]}=" if self.name.startswith("i|") else "" + + def val_repr(val): + if isinstance(val, rocksdb_lazy_instance): + if val.name[0] == "i": + return f"#{val.name[2:]}" + else: + return repr(val) + elif isinstance(val, (tuple, list)): + return f'({",".join(map(val_repr, val))})' + elif val is None: + return "$" + else: + return repr(val) + + return f'{pre}{self.is_a()}({",".join(map(val_repr, self))})' + + def id(self): + if self.name.startswith("i|"): + return int(self.name[2:]) + else: + # compatibility with C++ + return 0 + + def __bool__(self): + return len(self) > 0 + + @property + def _comparison_tuple(self): + return self.storage.file.file_pointer(), self.name + + def __eq__(self, other): + if not isinstance(other, rocksdb_lazy_instance): + return False + return self._comparison_tuple == other._comparison_tuple + + def __hash__(self): + return hash(self._comparison_tuple) + + +class rocksdb_file_storage: + def __init__(self, file, prefix=""): + self.file = file + self._prefix = prefix + + def items(self): + it = self.file.wrapped_data.key_value_store_iter(self._prefix) + while it and it.valid(): + yield it.key(), it.value() + it.next() + + def read(self, key): + return self.file.wrapped_data.key_value_store_query(key) + + def by_id(self, name): + if isinstance(name, tuple): + inst = rocksdb_lazy_instance(self, f'{"i" if name[0] else "t"}|{name[1]}') + else: + inst = rocksdb_lazy_instance(self, f"i|{name}") + if not inst: + raise KeyError(f"Instance with name {name} not found in file") + return inst + + def by_type(self, ty: str): + def visit(decl): + yield decl.index_in_schema() + for ty in decl.subtypes(): + yield from visit(ty) + + decl = ifcopenshell_wrapper.schema_by_name(self.schema_identifier).declaration_by_name(ty) + + def _(): + for index in visit(decl): + buff = self.read(f"t|{index}") or b"" + yield from map(self.by_id, struct.unpack("@" + "q" * (len(buff) // 8), buff)) + + return list(_()) + + __getitem__ = by_id + + def __iter__(self): + previous = None + for k, v in self.items(): + if k.startswith(b"i|"): + name = int(k[2:].split(b"|")[0]) + if name != previous: + previous = name + yield rocksdb_lazy_instance(self, f"i|{name}") + + def prefix(self, prefix): + return rocksdb_file_storage(self.file, self._prefix + prefix) + + @functools.cached_property + def schema_identifier(self): + """Full IFC schema version: IFC2X3_TC1, IFC4_ADD2, IFC4X3_ADD2, etc.""" + return rocksdb_lazy_instance(self, f"h|file_schema")[0][0] + + @functools.cached_property + def schema(self) -> ifcopenshell.util.schema.IFC_SCHEMA: + """General IFC schema version: IFC2X3, IFC4, IFC4X3.""" + prefixes = ("IFC", "X", "_ADD", "_TC") + reg = "".join(f"(?P<{s}>{s}\\d+)?" for s in prefixes) + match = re.match(reg, self.schema_identifier) + version_tuple = tuple( + map( + lambda pp: int(pp[1][len(pp[0]) :]) if pp[1] else None, + ((p, match.group(p)) for p in prefixes), + ) + ) + return "".join("".join(map(str, t)) if t[1] else "" for t in zip(prefixes, version_tuple[0:2])) + + +class file_header: + def __init__(self, file, header_data): + self.file = file + self.header_data = header_data + + @property + def file_description(self) -> entity_instance: + return entity_instance.wrap_value(self.header_data.file_description_py(), file=self.file) + + @property + def file_name(self) -> entity_instance: + return entity_instance.wrap_value(self.header_data.file_name_py(), file=self.file) + + @property + def file_schema(self) -> entity_instance: + return entity_instance.wrap_value(self.header_data.file_schema_py(), file=self.file) + + +class file: + """Base class for containing IFC files. + + Class has instance methods for filtering by element Id, Type, etc. + Instantiated objects can be subscripted by Id or Guid + + Example: + + .. code:: python + + model = ifcopenshell.open(file_path) + products = model.by_type("IfcProduct") + print(products[0].id(), products[0].GlobalId) # 122 2XQ$n5SLP5MBLyL442paFx + print(products[0] == model[122] == model["2XQ$n5SLP5MBLyL442paFx"]) # True + """ + + wrapped_data: ifcopenshell_wrapper.file + units: dict[str, entity_instance] = {} + history_size: int = 64 + history: list[Transaction] + """Chronological order - from oldest to newest.""" + future: list[Transaction] + """Reversed chronological order - from newest to oldest.""" + + to_delete: Union[set[ifcopenshell.entity_instance], None] = None + """Entities for batch removal.""" + + def __init__( + self, + f: Optional[ifcopenshell_wrapper.file] = None, + schema: Optional[ifcopenshell.util.schema.IFC_SCHEMA] = None, + schema_version: Optional[tuple[int, int, int, int]] = None, + ): + """Create a new blank IFC model + + This IFC model does not have any entities in it yet. See the + ``create_entity`` function for how to create new entities. All data is + stored in memory. If you wish to write the IFC model to disk, see the + ``write`` function. + + :param f: The underlying IfcOpenShell file object to be wrapped. This + is an internal implementation detail and should generally be left + as None by users. + :param schema: Which IFC schema to use, chosen from "IFC2X3", "IFC4", + or "IFC4X3". These refer to the ISO approved versions of IFC. + Defaults to "IFC4" if not specified, which is currently recommended + for all new projects. + :param schema_version: If you want to specify an exact version of IFC + that may not be an ISO approved version, use this argument instead + of ``schema``. IFC versions on technical.buildingsmart.org are + described using 4 integers representing the major, minor, addendum, + and corrigendum number. For example, (4, 0, 2, 1) refers to IFC4 + ADD2 TC1, which is the official version approved by ISO when people + refer to "IFC4". Generally you should not use this argument unless + you are testing non-ISO IFC releases. + + Example: + + .. code:: python + + # Create a new IFC4 model, create a wall, then save it to an IFC-SPF file. + model = ifcopenshell.file() + model.create_entity("IfcWall") + model.write("/path/to/model.ifc") + + # Create a new IFC4X3 model + model = ifcopenshell.file(schema="IFC4X3") + + # A poweruser testing out a particular version of IFC4X3 + model = ifcopenshell.file(schema_version=(4, 3, 0, 1)) + """ + if schema_version: + prefixes = ("IFC", "X", "_ADD", "_TC") + schema = "".join("".join(map(str, t)) if t[1] else "" for t in zip(prefixes, schema_version)) + else: + schema = {"IFC4X3": "IFC4X3_ADD2"}.get(schema, schema) + if f is not None: + self.wrapped_data = f + if not f.good(): + from . import Error, SchemaError + + exc, msg = { + READ_ERROR: lambda: (IOError, "Unable to open file for reading"), + NO_HEADER: lambda: (Error, "Unable to parse IFC SPF header"), + UNSUPPORTED_SCHEMA: lambda: ( + SchemaError, + "Unsupported schema: %s" % ",".join(self.header.file_schema.schema_identifiers), + ), + INVALID_SYNTAX: lambda: (Error, "Syntax error during parse, check logs"), + # This is the case when passing uninitialized_tag + UNKNOWN: lambda: (None, None), + }[f.good().value()]() + if exc is not None: + raise exc(msg) + else: + args = filter(None, [schema]) + args = map(ifcopenshell_wrapper.schema_by_name, args) + self.wrapped_data = ifcopenshell_wrapper.file(*args) + self.history = [] + self.future = [] + self.transaction: Optional[Transaction] = None + + # we store a tuple of C++ file pointer address and creation time stamp so that + # when memory addresses get recycled we do not run into collisions when the + # address is used as a cache key. + file_dict[self.wrapped_data.file_pointer()] = (weakref.ref(self), time.monotonic_ns()) + + @property + def identifier(self) -> tuple[int, int]: + """Pair of C++ file pointer address and creation time stamp to uniquely identify a file + over the life time of ifcopenshell module that should be mostly safe except in pathological + cases + + Returns: + tuple[int, int]: Pair of C++ file pointer address and creation time stamp + """ + return (self.wrapped_data.file_pointer(), file_dict[self.wrapped_data.file_pointer()][1]) + + def __del__(self) -> None: + # Avoid infinite recursion if file is failed to initialize + # and wrapped_data is unset. + if "wrapped_data" not in dir(self): + return + del file_dict[self.file_pointer()] + + def set_history_size(self, size: int) -> None: + self.history_size = size + while len(self.history) > self.history_size: + self.history.pop(0) + + def begin_transaction(self) -> None: + if self.history_size: + self.transaction = Transaction(self) + + def end_transaction(self) -> None: + if self.transaction: + self.history.append(self.transaction) + if len(self.history) > self.history_size: + self.history.pop(0) + self.future = [] + self.transaction = None + + def discard_transaction(self) -> None: + if self.transaction: + self.transaction.rollback() + self.transaction = None + + def undo(self) -> None: + if not self.history: + return + transaction = self.history.pop() + try: + transaction.rollback() + except Exception as e: + raise UndoSystemError("Error during transaction undo.", transaction) from e + self.future.append(transaction) + + def redo(self) -> None: + if not self.future: + return + transaction = self.future.pop() + try: + transaction.commit() + except Exception as e: + raise UndoSystemError("Error during transaction redo.", transaction) from e + self.history.append(transaction) + + def create_entity(self, type: str, *args: Any, **kwargs: Any) -> ifcopenshell.entity_instance: + """Create a new IFC entity in the file. + + You can also use dynamic methods similar to `ifc_file.createIfcWall(...)` + to create IFC entities. They work exactly the same as if you would do + `ifc_file.create_entity("IfcWall", ...)` but the resulting typing + is not as accurate as for `create_entity` due to a dynamic nature + of those methods. + + :param type: Case insensitive name of the IFC class + :param args: The positional arguments of the IFC class + :param kwargs: The keyword arguments of the IFC class + :returns: An entity instance + + Example: + + .. code:: python + + f = ifcopenshell.file() + f.create_entity("IfcPerson") + # >>> #1=IfcPerson($,$,$,$,$,$,$,$) + f.create_entity("IfcPerson", "Foobar") + # >>> #2=IfcPerson('Foobar',$,$,$,$,$,$,$) + f.create_entity("IfcPerson", Identification="Foobar") + # >>> #3=IfcPerson('Foobar',$,$,$,$,$,$,$) + """ + eid = kwargs.pop("id", -1) + + e = entity_instance((self.schema_identifier, type), self) + + # Create pairs of {attribute index, attribute value}. + # Keyword arguments are mapped to their corresponding + # numeric index with get_argument_index(). + + # @todo we should probably check that values for + # attributes are not passed as duplicates using + # both regular arguments and keyword arguments. + kwargs_attrs = [(e.wrapped_data.get_argument_index(name), arg) for name, arg in kwargs.items()] + attrs = list(enumerate(args)) + kwargs_attrs + + if len(attrs) > len(e): + raise ValueError( + "entity instance of type '%s' has only %s attributes but %s attributes were provided." + % (e.is_a(True), len(e), len(attrs)) + ) + + # Don't store these attributes as transactions + # as the creation it self is already stored with + # it's arguments + if attrs: + transaction = self.transaction + self.transaction = None + + try: + for idx, arg in attrs: + e[idx] = arg + except IndexError: + invalid_attrs = [] + for (attr_index, _), attr_name in zip(kwargs_attrs, kwargs): + if attr_index == 0xFFFFFFFF: + invalid_attrs.append(attr_name) + raise ValueError( + "entity instance of type '%s' doesn't have the following attributes: %s." + % (e.is_a(True), ", ".join(invalid_attrs)) + ) + + # Restore transaction status + if attrs: + self.transaction = transaction + + # Once the values are populated add the instance + # to the file. + self.wrapped_data.add(e.wrapped_data, eid) + + # The file container now handles the lifetime of + # this instance. Tell SWIG that it is no longer + # the owner. + e.wrapped_data.this.disown() + + if self.transaction: + self.transaction.store_create(e) + + return e + + @property + def schema(self) -> ifcopenshell.util.schema.IFC_SCHEMA: + """General IFC schema version: IFC2X3, IFC4, IFC4X3.""" + prefixes = ("IFC", "X", "_ADD", "_TC") + reg = "".join(f"(?P<{s}>{s}\\d+)?" for s in prefixes) + match = re.match(reg, self.wrapped_data.schema) + version_tuple = tuple( + map( + lambda pp: int(pp[1][len(pp[0]) :]) if pp[1] else None, + ((p, match.group(p)) for p in prefixes), + ) + ) + return "".join("".join(map(str, t)) if t[1] else "" for t in zip(prefixes, version_tuple[0:2])) + + @property + def schema_identifier(self) -> str: + """Full IFC schema version: IFC2X3_TC1, IFC4_ADD2, IFC4X3_ADD2, etc.""" + return self.wrapped_data.schema + + @property + def schema_version(self) -> tuple[int, int, int, int]: + """Numeric representation of the full IFC schema version. + + E.g. IFC4X3_ADD2 is represented as (4, 3, 2, 0). + """ + schema = self.wrapped_data.schema + version = [] + for prefix in ("IFC", "X", "_ADD", "_TC"): + number = re.search(prefix + r"(\d)", schema) + version.append(int(number.group(1)) if number else 0) + return tuple(version) + + @property + def mvd(self): + if not LARK_AVAILABLE: + return None + return MvdInfo(self.header) + + def __getattr__(self, attr) -> Union[Any, Callable[..., ifcopenshell.entity_instance]]: + if attr[0:6] == "create": + return functools.partial(self.create_entity, attr[6:]) + else: + return getattr(self.wrapped_data, attr) + + def __getitem__(self, key: Union[numbers.Integral, str, bytes]) -> entity_instance: + if isinstance(key, numbers.Integral): + return entity_instance(self.wrapped_data.by_id(key), self) + elif isinstance(key, (str, bytes)): + return entity_instance(self.wrapped_data.by_guid(str(key)), self) + + def by_id(self, id: int) -> ifcopenshell.entity_instance: + """Return an IFC entity instance filtered by IFC ID. + + :param id: STEP numerical identifier + + :raises RuntimeError: If `id` is not found. + + :returns: An ifcopenshell.entity_instance + """ + return self[id] + + def by_guid(self, guid: str) -> ifcopenshell.entity_instance: + """Return an IFC entity instance filtered by IFC GUID. + + :param guid: GlobalId value in 22-character encoded form + + :raises RuntimeError: If `guid` is not found. + + :returns: An ifcopenshell.entity_instance + """ + return self[guid] + + def add(self, inst: ifcopenshell.entity_instance, _id: int = None) -> ifcopenshell.entity_instance: + """Adds an entity including any dependent entities to an IFC file. + If the entity already exists, it is not re-added. Existence of entity is checked by it's `.identity()`. + + :param inst: The entity instance to add + :returns: An ifcopenshell.entity_instance + """ + + if self.transaction: + max_id = self.wrapped_data.getMaxId() + inst.wrapped_data.this.disown() + result = entity_instance(self.wrapped_data.add(inst.wrapped_data, -1 if _id is None else _id), self) + if self.transaction: + added_elements = [e for e in self.traverse(result) if e.id() > max_id] + [self.transaction.store_create(e) for e in reversed(added_elements)] + return result + + def by_type(self, type: str, include_subtypes=True) -> list[ifcopenshell.entity_instance]: + """Return IFC objects filtered by IFC Type and wrapped with the entity_instance class. + + If an IFC type class has subclasses, all entities of those subclasses are also returned. + + :param type: The case insensitive type of IFC class to return. + :param include_subtypes: Whether or not to return subtypes of the IFC class + + :raises RuntimeError: If `type` is not found in IFC schema. + + :returns: A list of ifcopenshell.entity_instance objects + """ + if include_subtypes: + return [entity_instance(e, self) for e in self.wrapped_data.by_type(type)] + return [entity_instance(e, self) for e in self.wrapped_data.by_type_excl_subtypes(type)] + + def traverse( + self, inst: ifcopenshell.entity_instance, max_levels: Optional[int] = None, breadth_first: bool = False + ) -> list[ifcopenshell.entity_instance]: + """Get a list of all referenced instances for a particular instance including itself + + :param inst: The entity instance to get all sub instances + :param max_levels: How far deep to recursively fetch sub instances. None or -1 means infinite. + :param breadth_first: Whether to use breadth-first search, the default is depth-first. + :returns: A list of ifcopenshell.entity_instance objects + """ + if max_levels is None: + max_levels = -1 + + if breadth_first: + fn = self.wrapped_data.traverse_breadth_first + else: + fn = self.wrapped_data.traverse + + return [entity_instance(e, self) for e in fn(inst.wrapped_data, max_levels)] + + @overload + def get_inverse( + self, + inst: ifcopenshell.entity_instance, + allow_duplicate: Literal[False] = False, + with_attribute_indices: bool = False, + ) -> set[ifcopenshell.entity_instance]: ... + @overload + def get_inverse( + self, + inst: ifcopenshell.entity_instance, + allow_duplicate: Literal[True], + with_attribute_indices: bool = False, + ) -> list[ifcopenshell.entity_instance]: ... + @overload + def get_inverse( + self, + inst: ifcopenshell.entity_instance, + allow_duplicate: bool, + with_attribute_indices: bool = False, + ) -> Union[list[ifcopenshell.entity_instance], set[ifcopenshell.entity_instance]]: ... + def get_inverse( + self, + inst: ifcopenshell.entity_instance, + allow_duplicate: bool = False, + with_attribute_indices: bool = False, + ) -> Union[list[ifcopenshell.entity_instance], set[ifcopenshell.entity_instance]]: + """Return a list of entities that reference this entity + + Warning: this is a slow function, especially when there is a large + number of inverses (such as for a shared owner history). If you are + only interested in the total number of inverses (typically 0, 1, or N), + consider using :func:`get_total_inverses`. + + :param inst: The entity instance to get inverse relationships + :param allow_duplicate: Returns a `list` when True, `set` when False + :param with_attribute_indices: Returns pairs of + where i[idx] is inst or contains inst. Requires allow_duplicate=True + :returns: A list or set of ifcopenshell.entity_instance objects. + """ + if with_attribute_indices and not allow_duplicate: + raise ValueError("with_attribute_indices requires allow_duplicate to be True") + + inverses = [entity_instance(e, self) for e in self.wrapped_data.get_inverse(inst.wrapped_data)] + + if allow_duplicate: + if with_attribute_indices: + idxs = self.wrapped_data.get_inverse_indices(inst.wrapped_data) + # TODO: include in typing. + return list(zip(inverses, idxs)) + else: + return inverses + + return set(inverses) + + def get_total_inverses(self, inst: ifcopenshell.entity_instance) -> int: + """Returns the number of entities that reference this entity + + This is equivalent to `len(model.get_inverse(element))`, but + significantly faster. + + :param inst: The entity instance to get inverse relationships + :returns: The total number of references + """ + return self.wrapped_data.get_total_inverses(inst.wrapped_data) + + def remove(self, inst: ifcopenshell.entity_instance) -> None: + """Deletes an IFC object in the file. + + Attribute values in other entity instances that reference the deleted + object will be set to null. In the case of a list or set of references, + the reference to the deleted will be removed from the aggregate. + + :param inst: The entity instance to delete + """ + if self.transaction: + self.transaction.store_delete(inst) + return self.wrapped_data.remove(inst.wrapped_data) + + def batch(self): + """Low-level mechanism to speed up deletion of large subgraphs""" + if self.transaction: + self.transaction.batch() + return self.wrapped_data.batch() + + def unbatch(self): + """Low-level mechanism to speed up deletion of large subgraphs""" + if self.transaction: + self.transaction.unbatch() + return self.wrapped_data.unbatch() + + def __iter__(self) -> Generator[ifcopenshell.entity_instance, None, None]: + return iter(self[id] for id in self.wrapped_data.entity_names()) + + def assign_header_from(self, other: ifcopenshell.file) -> None: + for k, vs in HEADER_FIELDS.items(): + for v in vs: + try: + setattr(getattr(self.header, k), v, getattr(getattr(other.header, k), v)) + except: + pass # Header is invalid + + def write(self, path: os.PathLike | str, format: Optional[str] = None, zipped: bool = False) -> None: + """Write ifc model to file. + + :param format: Force use of a specific format. Guessed from file name + if None. Supported formats : .ifc, .ifcZIP (equivalent to + format=".ifc" with zipped=True) + :param zipped: zip the file after it is written + + Example: + + .. code:: python + + model.write("path/to/model.ifc") + model.write("path/to/model.ifcZIP") + model.write("path/to/model.anyextension", format=".ifc") + """ + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + + if format == None: + format = ifcopenshell.guess_format(path) + if format == ".ifcXML": + raise NotImplementedError("Writing .ifcXML files is not supported") + if format == ".ifcZIP": + return self.write(path, ".ifc", zipped=True) + self.wrapped_data.write(str(path)) + + if zipped: + unzipped_path = path.with_suffix(format) + path.rename(unzipped_path) + with zipfile.ZipFile(path, "w") as zip_file: + zip_file.write( + unzipped_path, + unzipped_path.name, + compress_type=zipfile.ZIP_DEFLATED, + ) + unzipped_path.unlink() + return + + @staticmethod + def from_string(s: str) -> file: + return file(ifcopenshell_wrapper.read(s)) + + @staticmethod + def from_pointer(address: int) -> file: + assert (f := file_dict[address][0]()) is not None + return f + + def to_string(self) -> str: + return self.wrapped_data.to_string() + + @property + def header(self) -> file_header: + # TODO: Workaround for old builds, remove after build stabilizes. + # TODO: No need for `wrapped_data.header` to be a method - should use `@property`? + header = self.wrapped_data.header + if isinstance(header, types.MethodType): + return file_header(self, self.wrapped_data.header()) + else: + return self.wrapped_data.header + + @property + def storage(self) -> Optional[rocksdb_file_storage]: + """ + Returns: + Optional[rocksdb_file_storage]: underlying key-value store interface when opened as a RocksDB-backed file + """ + if self.wrapped_data.storage_mode() == 1: + return rocksdb_file_storage(self) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/guid.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/guid.py new file mode 100644 index 0000000000000000000000000000000000000000..6e3c6f5b0a6c40f2784ade222a20b398a69ed097 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/guid.py @@ -0,0 +1,157 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Thomas Krijnen +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# IfcOpenShell is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with IfcOpenShell. If not, see . + +""" +Reads and writes encoded GlobalIds. + +IFC entities may be identified using a unique ID (called a UUID or GUID). +This 128-bit label is often represented in the form +``` +xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx. +``` +However, in IFC, it is also usually stored as a +22 character base 64 encoded string. +This module lets you convert between these representations and generate new UUIDs. + +NOTE: The Ifc convention for Base64 encoding differs from the standard. + +The "digits" of a standard Base64 encoding are as follows: +``` +ABC...XYZ abc...XYZ 012...89 +/ +``` +(see , +), +whereas the Ifc convention is +``` +012...89 ABC...XYZ abc...XYZ _$ +``` +cf. . +""" + +# ---------------------------------------------------------------- +# IMPORTS +# ---------------------------------------------------------------- + +from base64 import b64encode +from base64 import b64decode +from uuid import uuid4 +import re +import string + +# ---------------------------------------------------------------- +# EXPORTS +# ---------------------------------------------------------------- + +__all__ = [ + "compress", + "expand", + "new", + "split", +] + +# ---------------------------------------------------------------- +# LOCAL CONSTANTS +# ---------------------------------------------------------------- + +# standard convention +_CHARS64_STD = string.ascii_uppercase + string.ascii_lowercase + string.digits + "+/" + +# ifc convention +_CHARS64_IFC = string.digits + string.ascii_uppercase + string.ascii_lowercase + "_$" + +# translators +_TRANS_IFC_TO_STD = str.maketrans(_CHARS64_IFC, _CHARS64_STD) +_TRANS_STD_TO_IFC = str.maketrans(_CHARS64_STD, _CHARS64_IFC) + +# ---------------------------------------------------------------- +# METHODS +# ---------------------------------------------------------------- + + +def compress(uuid: str, /) -> str: + """ + Converts a hex-encoded UUID to a base64-encoded GUID in IFC-format. + + See + """ + # remove possible separators + uuid = uuid.lower() + uuid = re.sub(pattern=r"\W", repl="", string=uuid) + + # pad with hex "zeroes" + uuid = "0000" + uuid + + # convert to standard base 64 + uuid_bytes = bytes.fromhex(uuid) + guid = b64encode(uuid_bytes).decode() + + # remove result of padding + guid = guid[2:] + + # translate from standard-convention to ifc-convention + guid = guid.translate(_TRANS_STD_TO_IFC) + + return guid + + +def expand(guid: str, /) -> str: + """ + Converts a base64-encoded GUID in IFC-format to a hex-encoded UUID. + + See + """ + # translate from ifc-convention to standard-convention + guid = guid.translate(_TRANS_IFC_TO_STD) + + # pad with base64 "zeroes" + guid = "AA" + guid + + # convert to hex + uuid = b64decode(guid).hex() + + # remove result of padding + uuid = uuid[4:] + + return uuid + + +def split(uuid: str, /) -> str: + """ + Formats a UUID as + ``` + xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx + ``` + """ + return "-".join( + [ + uuid[:8], + uuid[8:12], + uuid[12:16], + uuid[16:20], + uuid[20:], + ] + ) + + +def new() -> str: + """ + Generates a random UUID and compresses it to a Base 64 IFC GUID. + """ + uuid = uuid4().hex + guid = compress(uuid) + return guid diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/ifcopenshell_wrapper.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/ifcopenshell_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..beebb2f0512737e4777ad9e0ed24982931179f82 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/ifcopenshell_wrapper.py @@ -0,0 +1,7033 @@ +# This file was automatically generated by SWIG (http://www.swig.org). +# Version 4.0.2 +# +# Do not make changes to this file unless you know what you are doing--modify +# the SWIG interface file instead. + +from sys import version_info as _swig_python_version_info +if _swig_python_version_info < (2, 7, 0): + raise RuntimeError("Python 2.7 or later required") + +# Import the low-level C/C++ module +if __package__ or "." in __name__: + from . import _ifcopenshell_wrapper +else: + import _ifcopenshell_wrapper + +try: + import builtins as __builtin__ +except ImportError: + import __builtin__ + +def _swig_repr(self): + try: + strthis = "proxy of " + self.this.__repr__() + except __builtin__.Exception: + strthis = "" + return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,) + + +def _swig_setattr_nondynamic_instance_variable(set): + def set_instance_attr(self, name, value): + if name == "thisown": + self.this.own(value) + elif name == "this": + set(self, name, value) + elif hasattr(self, name) and isinstance(getattr(type(self), name), property): + set(self, name, value) + else: + raise AttributeError("You cannot add instance attributes to %s" % self) + return set_instance_attr + + +def _swig_setattr_nondynamic_class_variable(set): + def set_class_attr(cls, name, value): + if hasattr(cls, name) and not isinstance(getattr(cls, name), property): + set(cls, name, value) + else: + raise AttributeError("You cannot add class attributes to %s" % cls) + return set_class_attr + + +def _swig_add_metaclass(metaclass): + """Class decorator for adding a metaclass to a SWIG wrapped class - a slimmed down version of six.add_metaclass""" + def wrapper(cls): + return metaclass(cls.__name__, cls.__bases__, cls.__dict__.copy()) + return wrapper + + +class _SwigNonDynamicMeta(type): + """Meta class to enforce nondynamic attributes (no new attributes) for a class""" + __setattr__ = _swig_setattr_nondynamic_class_variable(type.__setattr__) + + +class SwigPyIterator(object): + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + + def __init__(self, *args, **kwargs): + raise AttributeError("No constructor defined - class is abstract") + __repr__ = _swig_repr + __swig_destroy__ = _ifcopenshell_wrapper.delete_SwigPyIterator + + def value(self): + return _ifcopenshell_wrapper.SwigPyIterator_value(self) + + def incr(self, n=1): + return _ifcopenshell_wrapper.SwigPyIterator_incr(self, n) + + def decr(self, n=1): + return _ifcopenshell_wrapper.SwigPyIterator_decr(self, n) + + def distance(self, x): + return _ifcopenshell_wrapper.SwigPyIterator_distance(self, x) + + def equal(self, x): + return _ifcopenshell_wrapper.SwigPyIterator_equal(self, x) + + def copy(self): + return _ifcopenshell_wrapper.SwigPyIterator_copy(self) + + def next(self): + return _ifcopenshell_wrapper.SwigPyIterator_next(self) + + def __next__(self): + return _ifcopenshell_wrapper.SwigPyIterator___next__(self) + + def previous(self): + return _ifcopenshell_wrapper.SwigPyIterator_previous(self) + + def advance(self, n): + return _ifcopenshell_wrapper.SwigPyIterator_advance(self, n) + + def __eq__(self, x): + return _ifcopenshell_wrapper.SwigPyIterator___eq__(self, x) + + def __ne__(self, x): + return _ifcopenshell_wrapper.SwigPyIterator___ne__(self, x) + + def __iadd__(self, n): + return _ifcopenshell_wrapper.SwigPyIterator___iadd__(self, n) + + def __isub__(self, n): + return _ifcopenshell_wrapper.SwigPyIterator___isub__(self, n) + + def __add__(self, n): + return _ifcopenshell_wrapper.SwigPyIterator___add__(self, n) + + def __sub__(self, *args): + return _ifcopenshell_wrapper.SwigPyIterator___sub__(self, *args) + def __iter__(self): + return self + +# Register SwigPyIterator in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.SwigPyIterator_swigregister(SwigPyIterator) + +SHARED_PTR_DISOWN = _ifcopenshell_wrapper.SHARED_PTR_DISOWN +class DoubleArray3(object): + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def iterator(self): + return _ifcopenshell_wrapper.DoubleArray3_iterator(self) + def __iter__(self): + return self.iterator() + + def __nonzero__(self): + return _ifcopenshell_wrapper.DoubleArray3___nonzero__(self) + + def __bool__(self): + return _ifcopenshell_wrapper.DoubleArray3___bool__(self) + + def __len__(self): + return _ifcopenshell_wrapper.DoubleArray3___len__(self) + + def __getslice__(self, i, j): + return _ifcopenshell_wrapper.DoubleArray3___getslice__(self, i, j) + + def __setslice__(self, *args): + return _ifcopenshell_wrapper.DoubleArray3___setslice__(self, *args) + + def __delslice__(self, i, j): + return _ifcopenshell_wrapper.DoubleArray3___delslice__(self, i, j) + + def __delitem__(self, *args): + return _ifcopenshell_wrapper.DoubleArray3___delitem__(self, *args) + + def __getitem__(self, *args): + return _ifcopenshell_wrapper.DoubleArray3___getitem__(self, *args) + + def __setitem__(self, *args): + return _ifcopenshell_wrapper.DoubleArray3___setitem__(self, *args) + + def __init__(self, *args): + _ifcopenshell_wrapper.DoubleArray3_swiginit(self, _ifcopenshell_wrapper.new_DoubleArray3(*args)) + + def empty(self): + return _ifcopenshell_wrapper.DoubleArray3_empty(self) + + def size(self): + return _ifcopenshell_wrapper.DoubleArray3_size(self) + + def swap(self, v): + return _ifcopenshell_wrapper.DoubleArray3_swap(self, v) + + def begin(self): + return _ifcopenshell_wrapper.DoubleArray3_begin(self) + + def end(self): + return _ifcopenshell_wrapper.DoubleArray3_end(self) + + def rbegin(self): + return _ifcopenshell_wrapper.DoubleArray3_rbegin(self) + + def rend(self): + return _ifcopenshell_wrapper.DoubleArray3_rend(self) + + def front(self): + return _ifcopenshell_wrapper.DoubleArray3_front(self) + + def back(self): + return _ifcopenshell_wrapper.DoubleArray3_back(self) + + def fill(self, u): + return _ifcopenshell_wrapper.DoubleArray3_fill(self, u) + __swig_destroy__ = _ifcopenshell_wrapper.delete_DoubleArray3 + +# Register DoubleArray3 in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.DoubleArray3_swigregister(DoubleArray3) + + +def taxonomy_item_repr(i): + r"""taxonomy_item_repr(ifcopenshell::geometry::taxonomy::item::ptr i) -> std::string""" + return _ifcopenshell_wrapper.taxonomy_item_repr(i) +class OpaqueNumber(object): + r"""Proxy of C++ IfcGeom::OpaqueNumber class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + + def __init__(self, *args, **kwargs): + raise AttributeError("No constructor defined - class is abstract") + __repr__ = _swig_repr + + def to_double(self): + r"""to_double(OpaqueNumber self) -> double""" + return _ifcopenshell_wrapper.OpaqueNumber_to_double(self) + + def to_string(self): + r"""to_string(OpaqueNumber self) -> std::string""" + return _ifcopenshell_wrapper.OpaqueNumber_to_string(self) + __swig_destroy__ = _ifcopenshell_wrapper.delete_OpaqueNumber + + def __add__(self, other): + r"""__add__(OpaqueNumber self, OpaqueNumber other) -> OpaqueNumber""" + return _ifcopenshell_wrapper.OpaqueNumber___add__(self, other) + + def __sub__(self, other): + r"""__sub__(OpaqueNumber self, OpaqueNumber other) -> OpaqueNumber""" + return _ifcopenshell_wrapper.OpaqueNumber___sub__(self, other) + + def __mul__(self, other): + r"""__mul__(OpaqueNumber self, OpaqueNumber other) -> OpaqueNumber""" + return _ifcopenshell_wrapper.OpaqueNumber___mul__(self, other) + + def __truediv__(self, *args): + return _ifcopenshell_wrapper.OpaqueNumber___truediv__(self, *args) + __div__ = __truediv__ + + + + def __eq__(self, other): + r"""__eq__(OpaqueNumber self, OpaqueNumber other) -> bool""" + return _ifcopenshell_wrapper.OpaqueNumber___eq__(self, other) + + def __lt__(self, other): + r"""__lt__(OpaqueNumber self, OpaqueNumber other) -> bool""" + return _ifcopenshell_wrapper.OpaqueNumber___lt__(self, other) + + def __neg__(self): + r"""__neg__(OpaqueNumber self) -> OpaqueNumber""" + return _ifcopenshell_wrapper.OpaqueNumber___neg__(self) + + def clone(self): + r"""clone(OpaqueNumber self) -> OpaqueNumber""" + return _ifcopenshell_wrapper.OpaqueNumber_clone(self) + +# Register OpaqueNumber in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.OpaqueNumber_swigregister(OpaqueNumber) + +class ConversionResultShape(object): + r"""Proxy of C++ IfcGeom::ConversionResultShape class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + + def __init__(self, *args, **kwargs): + raise AttributeError("No constructor defined - class is abstract") + __repr__ = _swig_repr + + def Triangulate(self, *args): + r""" + Triangulate(ConversionResultShape self, Settings settings, matrix4 place, Triangulation t, int item_id, int surface_style_id) + Triangulate(ConversionResultShape self, Settings settings) -> Triangulation + """ + return _ifcopenshell_wrapper.ConversionResultShape_Triangulate(self, *args) + + def Serialize(self, place, arg3): + r"""Serialize(ConversionResultShape self, matrix4 place, std::string & arg3)""" + return _ifcopenshell_wrapper.ConversionResultShape_Serialize(self, place, arg3) + + def surface_genus(self): + r"""surface_genus(ConversionResultShape self) -> int""" + return _ifcopenshell_wrapper.ConversionResultShape_surface_genus(self) + + def is_manifold(self): + r"""is_manifold(ConversionResultShape self) -> bool""" + return _ifcopenshell_wrapper.ConversionResultShape_is_manifold(self) + + def num_vertices(self): + r"""num_vertices(ConversionResultShape self) -> int""" + return _ifcopenshell_wrapper.ConversionResultShape_num_vertices(self) + + def num_edges(self): + r"""num_edges(ConversionResultShape self) -> int""" + return _ifcopenshell_wrapper.ConversionResultShape_num_edges(self) + + def num_faces(self): + r"""num_faces(ConversionResultShape self) -> int""" + return _ifcopenshell_wrapper.ConversionResultShape_num_faces(self) + + def bounding_box(self, *args): + r""" + bounding_box(ConversionResultShape self, void *& arg2) -> double + bounding_box(ConversionResultShape self) -> std::pair< IfcGeom::OpaqueCoordinate< 3 >,IfcGeom::OpaqueCoordinate< 3 > > + """ + return _ifcopenshell_wrapper.ConversionResultShape_bounding_box(self, *args) + + def set_box(self, b): + r"""set_box(ConversionResultShape self, void * b)""" + return _ifcopenshell_wrapper.ConversionResultShape_set_box(self, b) + + def length(self): + r"""length(ConversionResultShape self) -> OpaqueNumber""" + return _ifcopenshell_wrapper.ConversionResultShape_length(self) + + def area(self): + r"""area(ConversionResultShape self) -> OpaqueNumber""" + return _ifcopenshell_wrapper.ConversionResultShape_area(self) + + def volume(self): + r"""volume(ConversionResultShape self) -> OpaqueNumber""" + return _ifcopenshell_wrapper.ConversionResultShape_volume(self) + + def position(self): + r"""position(ConversionResultShape self) -> OpaqueCoordinate_3""" + return _ifcopenshell_wrapper.ConversionResultShape_position(self) + + def axis(self): + r"""axis(ConversionResultShape self) -> OpaqueCoordinate_3""" + return _ifcopenshell_wrapper.ConversionResultShape_axis(self) + + def plane_equation(self): + r"""plane_equation(ConversionResultShape self) -> OpaqueCoordinate_4""" + return _ifcopenshell_wrapper.ConversionResultShape_plane_equation(self) + + def convex_decomposition(self): + r"""convex_decomposition(ConversionResultShape self) -> std::vector< IfcGeom::ConversionResultShape *,std::allocator< IfcGeom::ConversionResultShape * > >""" + return _ifcopenshell_wrapper.ConversionResultShape_convex_decomposition(self) + + def halfspaces(self): + r"""halfspaces(ConversionResultShape self) -> ConversionResultShape""" + return _ifcopenshell_wrapper.ConversionResultShape_halfspaces(self) + + def box(self): + r"""box(ConversionResultShape self) -> ConversionResultShape""" + return _ifcopenshell_wrapper.ConversionResultShape_box(self) + + def solid(self): + r"""solid(ConversionResultShape self) -> ConversionResultShape""" + return _ifcopenshell_wrapper.ConversionResultShape_solid(self) + + def wrap_in_compound(self): + r"""wrap_in_compound(ConversionResultShape self) -> ConversionResultShape""" + return _ifcopenshell_wrapper.ConversionResultShape_wrap_in_compound(self) + + def vertices(self): + r"""vertices(ConversionResultShape self) -> std::vector< IfcGeom::ConversionResultShape *,std::allocator< IfcGeom::ConversionResultShape * > >""" + return _ifcopenshell_wrapper.ConversionResultShape_vertices(self) + + def edges(self): + r"""edges(ConversionResultShape self) -> std::vector< IfcGeom::ConversionResultShape *,std::allocator< IfcGeom::ConversionResultShape * > >""" + return _ifcopenshell_wrapper.ConversionResultShape_edges(self) + + def facets(self): + r"""facets(ConversionResultShape self) -> std::vector< IfcGeom::ConversionResultShape *,std::allocator< IfcGeom::ConversionResultShape * > >""" + return _ifcopenshell_wrapper.ConversionResultShape_facets(self) + + def add(self, arg2): + r"""add(ConversionResultShape self, ConversionResultShape arg2) -> ConversionResultShape""" + return _ifcopenshell_wrapper.ConversionResultShape_add(self, arg2) + + def subtract(self, arg2): + r"""subtract(ConversionResultShape self, ConversionResultShape arg2) -> ConversionResultShape""" + return _ifcopenshell_wrapper.ConversionResultShape_subtract(self, arg2) + + def intersect(self, arg2): + r"""intersect(ConversionResultShape self, ConversionResultShape arg2) -> ConversionResultShape""" + return _ifcopenshell_wrapper.ConversionResultShape_intersect(self, arg2) + + def concat(self, arg2): + r"""concat(ConversionResultShape self, ConversionResultShape arg2) -> ConversionResultShape""" + return _ifcopenshell_wrapper.ConversionResultShape_concat(self, arg2) + + def map(self, *args): + r""" + map(ConversionResultShape self, OpaqueCoordinate_4 _from, OpaqueCoordinate_4 to) + map(ConversionResultShape self, std::vector< IfcGeom::OpaqueCoordinate< 4 >,std::allocator< IfcGeom::OpaqueCoordinate< 4 > > > const & _from, std::vector< IfcGeom::OpaqueCoordinate< 4 >,std::allocator< IfcGeom::OpaqueCoordinate< 4 > > > const & to) + """ + return _ifcopenshell_wrapper.ConversionResultShape_map(self, *args) + + def moved(self, arg2): + r"""moved(ConversionResultShape self, ifcopenshell::geometry::taxonomy::matrix4::ptr arg2) -> ConversionResultShape""" + return _ifcopenshell_wrapper.ConversionResultShape_moved(self, arg2) + + def surface_area_along_direction(self, tol, arg3, along_x, along_y, along_z): + r"""surface_area_along_direction(ConversionResultShape self, double tol, ifcopenshell::geometry::taxonomy::matrix4::ptr const & arg3, double & along_x, double & along_y, double & along_z) -> bool""" + return _ifcopenshell_wrapper.ConversionResultShape_surface_area_along_direction(self, tol, arg3, along_x, along_y, along_z) + __swig_destroy__ = _ifcopenshell_wrapper.delete_ConversionResultShape + + def serialize_obj(self): + r"""serialize_obj(ConversionResultShape self) -> std::string""" + return _ifcopenshell_wrapper.ConversionResultShape_serialize_obj(self) + + def convex_tag(self, b): + r"""convex_tag(ConversionResultShape self, bool b)""" + return _ifcopenshell_wrapper.ConversionResultShape_convex_tag(self, b) + + def serialize(self): + r"""serialize(ConversionResultShape self) -> std::string""" + return _ifcopenshell_wrapper.ConversionResultShape_serialize(self) + + def solid_mt(self): + r"""solid_mt(ConversionResultShape self) -> ConversionResultShape""" + return _ifcopenshell_wrapper.ConversionResultShape_solid_mt(self) + +# Register ConversionResultShape in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.ConversionResultShape_swigregister(ConversionResultShape) + +class ConversionResult(object): + r"""Proxy of C++ IfcGeom::ConversionResult class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def __init__(self, *args): + r""" + __init__(ConversionResult self, int id, ifcopenshell::geometry::taxonomy::matrix4::ptr placement, ConversionResultShape shape, ifcopenshell::geometry::taxonomy::style::ptr style) -> ConversionResult + __init__(ConversionResult self, int id, ifcopenshell::geometry::taxonomy::matrix4::ptr placement, ConversionResultShape shape) -> ConversionResult + __init__(ConversionResult self, int id, ConversionResultShape shape, ifcopenshell::geometry::taxonomy::style::ptr style) -> ConversionResult + __init__(ConversionResult self, int id, ConversionResultShape shape) -> ConversionResult + """ + _ifcopenshell_wrapper.ConversionResult_swiginit(self, _ifcopenshell_wrapper.new_ConversionResult(*args)) + + def append(self, trsf): + r"""append(ConversionResult self, ifcopenshell::geometry::taxonomy::matrix4::ptr trsf)""" + return _ifcopenshell_wrapper.ConversionResult_append(self, trsf) + + def prepend(self, trsf): + r"""prepend(ConversionResult self, ifcopenshell::geometry::taxonomy::matrix4::ptr trsf)""" + return _ifcopenshell_wrapper.ConversionResult_prepend(self, trsf) + + def Shape(self): + r"""Shape(ConversionResult self) -> std::shared_ptr< IfcGeom::ConversionResultShape >""" + return _ifcopenshell_wrapper.ConversionResult_Shape(self) + + def Placement(self): + r"""Placement(ConversionResult self) -> ifcopenshell::geometry::taxonomy::matrix4::ptr""" + return _ifcopenshell_wrapper.ConversionResult_Placement(self) + + def hasStyle(self): + r"""hasStyle(ConversionResult self) -> bool""" + return _ifcopenshell_wrapper.ConversionResult_hasStyle(self) + + def Style(self): + r"""Style(ConversionResult self) -> style""" + return _ifcopenshell_wrapper.ConversionResult_Style(self) + + def StylePtr(self): + r"""StylePtr(ConversionResult self) -> ifcopenshell::geometry::taxonomy::style::ptr""" + return _ifcopenshell_wrapper.ConversionResult_StylePtr(self) + + def setStyle(self, newStyle): + r"""setStyle(ConversionResult self, ifcopenshell::geometry::taxonomy::style::ptr newStyle)""" + return _ifcopenshell_wrapper.ConversionResult_setStyle(self, newStyle) + + def ItemId(self): + r"""ItemId(ConversionResult self) -> int""" + return _ifcopenshell_wrapper.ConversionResult_ItemId(self) + + def apply_transform(self, unit_scale=1.): + r"""apply_transform(ConversionResult self, double unit_scale=1.) -> ConversionResultShape""" + return _ifcopenshell_wrapper.ConversionResult_apply_transform(self, unit_scale) + __swig_destroy__ = _ifcopenshell_wrapper.delete_ConversionResult + +# Register ConversionResult in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.ConversionResult_swigregister(ConversionResult) + +CURVES = _ifcopenshell_wrapper.CURVES + +SURFACES_AND_SOLIDS = _ifcopenshell_wrapper.SURFACES_AND_SOLIDS + +CURVES_SURFACES_AND_SOLIDS = _ifcopenshell_wrapper.CURVES_SURFACES_AND_SOLIDS + +TRIANGULATED = _ifcopenshell_wrapper.TRIANGULATED + +NATIVE = _ifcopenshell_wrapper.NATIVE + +SERIALIZED = _ifcopenshell_wrapper.SERIALIZED + +MAXSTEPSIZE = _ifcopenshell_wrapper.MAXSTEPSIZE + +MINSTEPS = _ifcopenshell_wrapper.MINSTEPS + +TRIANGLE_MESH = _ifcopenshell_wrapper.TRIANGLE_MESH + +POLYHEDRON_WITHOUT_HOLES = _ifcopenshell_wrapper.POLYHEDRON_WITHOUT_HOLES + +POLYHEDRON_WITH_HOLES = _ifcopenshell_wrapper.POLYHEDRON_WITH_HOLES + + +def __rshift__(*args): + r""" + __rshift__(std::istream & _in, ifcopenshell::geometry::settings::OutputDimensionalityTypes & ioo) -> std::istream + __rshift__(std::istream & _in, ifcopenshell::geometry::settings::IteratorOutputOptions & ioo) -> std::istream + __rshift__(std::istream & _in, ifcopenshell::geometry::settings::FunctionStepMethod & ioo) -> std::istream + __rshift__(std::istream & _in, ifcopenshell::geometry::settings::TriangulationMethod & ioo) -> std::istream & + """ + return _ifcopenshell_wrapper.__rshift__(*args) +class Settings(object): + r"""Proxy of C++ ifcopenshell::geometry::Settings class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def set_(self, *args): + r""" + set_(Settings self, std::string const & name, bool val) + set_(Settings self, std::string const & name, int val) + set_(Settings self, std::string const & name, ifcopenshell::geometry::settings::IteratorOutputOptions val) + set_(Settings self, std::string const & name, ifcopenshell::geometry::settings::FunctionStepMethod val) + set_(Settings self, std::string const & name, ifcopenshell::geometry::settings::OutputDimensionalityTypes val) + set_(Settings self, std::string const & name, double val) + set_(Settings self, std::string const & name, std::string const & val) + set_(Settings self, std::string const & name, std::set< int > const & val) + set_(Settings self, std::string const & name, std::set< std::string > const & val) + set_(Settings self, std::string const & name, std::vector< double,std::allocator< double > > const & val) + """ + return _ifcopenshell_wrapper.Settings_set_(self, *args) + + def get_(self, name): + r"""get_(Settings self, std::string const & name) -> ifcopenshell::geometry::Settings::value_variant_t""" + return _ifcopenshell_wrapper.Settings_get_(self, name) + + def setting_names(self): + r"""setting_names(Settings self) -> std::vector< std::string,std::allocator< std::string > >""" + return _ifcopenshell_wrapper.Settings_setting_names(self) + + def get_type(self, name): + r"""get_type(Settings self, std::string const & name) -> std::string""" + return _ifcopenshell_wrapper.Settings_get_type(self, name) + + def __init__(self): + r"""__init__(Settings self) -> Settings""" + _ifcopenshell_wrapper.Settings_swiginit(self, _ifcopenshell_wrapper.new_Settings()) + __swig_destroy__ = _ifcopenshell_wrapper.delete_Settings + +# Register Settings in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.Settings_swigregister(Settings) + +class Transformation(object): + r"""Proxy of C++ IfcGeom::Transformation class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def __init__(self, settings, matrix): + r"""__init__(Transformation self, Settings settings, ifcopenshell::geometry::taxonomy::matrix4::ptr const & matrix) -> Transformation""" + _ifcopenshell_wrapper.Transformation_swiginit(self, _ifcopenshell_wrapper.new_Transformation(settings, matrix)) + + def data(self): + r"""data(Transformation self) -> ifcopenshell::geometry::taxonomy::matrix4::ptr const &""" + return _ifcopenshell_wrapper.Transformation_data(self) + + def matrix_(self): + r"""matrix_(Transformation self) -> PyObject *""" + return _ifcopenshell_wrapper.Transformation_matrix_(self) + + # Hide the getters with read-only property implementations + matrix = property(matrix_) + + __swig_destroy__ = _ifcopenshell_wrapper.delete_Transformation + +# Register Transformation in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.Transformation_swigregister(Transformation) + +class Element(object): + r"""Proxy of C++ IfcGeom::Element class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def id(self): + r"""id(Element self) -> int""" + return _ifcopenshell_wrapper.Element_id(self) + + def parent_id(self): + r"""parent_id(Element self) -> int""" + return _ifcopenshell_wrapper.Element_parent_id(self) + + def name(self): + r"""name(Element self) -> std::string const &""" + return _ifcopenshell_wrapper.Element_name(self) + + def type(self): + r"""type(Element self) -> std::string const &""" + return _ifcopenshell_wrapper.Element_type(self) + + def guid(self): + r"""guid(Element self) -> std::string const &""" + return _ifcopenshell_wrapper.Element_guid(self) + + def context(self): + r"""context(Element self) -> std::string const &""" + return _ifcopenshell_wrapper.Element_context(self) + + def unique_id(self): + r"""unique_id(Element self) -> std::string const &""" + return _ifcopenshell_wrapper.Element_unique_id(self) + + def transformation(self): + r"""transformation(Element self) -> Transformation""" + return _ifcopenshell_wrapper.Element_transformation(self) + + def product(self): + r"""product(Element self) -> IfcBaseEntity""" + return _ifcopenshell_wrapper.Element_product(self) + + def parents(self): + r"""parents(Element self) -> std::vector< IfcGeom::Element const *,std::allocator< IfcGeom::Element const * > > const &""" + return _ifcopenshell_wrapper.Element_parents(self) + + def SetParents(self, newparents): + r"""SetParents(Element self, std::vector< IfcGeom::Element const *,std::allocator< IfcGeom::Element const * > > & newparents)""" + return _ifcopenshell_wrapper.Element_SetParents(self, newparents) + + def __init__(self, settings, id, parent_id, name, type, guid, context, trsf, product): + r"""__init__(Element self, Settings settings, int id, int parent_id, std::string const & name, std::string const & type, std::string const & guid, std::string const & context, ifcopenshell::geometry::taxonomy::matrix4::ptr const & trsf, IfcBaseEntity product) -> Element""" + _ifcopenshell_wrapper.Element_swiginit(self, _ifcopenshell_wrapper.new_Element(settings, id, parent_id, name, type, guid, context, trsf, product)) + __swig_destroy__ = _ifcopenshell_wrapper.delete_Element + + def transformation_buffer(self): + r"""transformation_buffer(Element self) -> std::pair< char const *,size_t >""" + return _ifcopenshell_wrapper.Element_transformation_buffer(self) + + def product_(self): + r"""product_(Element self) -> entity_instance""" + return _ifcopenshell_wrapper.Element_product_(self) + + # Hide the getters with read-only property implementations + id = property(id) + parent_id = property(parent_id) + name = property(name) + type = property(type) + guid = property(guid) + context = property(context) + unique_id = property(unique_id) + transformation = property(transformation) + product = property(product_) + + transformation_buffer = property(transformation_buffer) + + +# Register Element in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.Element_swigregister(Element) + +def __eq__(element1, element2): + r"""__eq__(Element element1, Element element2) -> bool""" + return _ifcopenshell_wrapper.__eq__(element1, element2) + +def __lt__(element1, element2): + r"""__lt__(Element element1, Element element2) -> bool""" + return _ifcopenshell_wrapper.__lt__(element1, element2) + +class BRepElement(Element): + r"""Proxy of C++ IfcGeom::BRepElement class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def geometry_pointer(self): + r"""geometry_pointer(BRepElement self) -> boost::shared_ptr< IfcGeom::Representation::BRep > const &""" + return _ifcopenshell_wrapper.BRepElement_geometry_pointer(self) + + def geometry(self): + r"""geometry(BRepElement self) -> BRep""" + return _ifcopenshell_wrapper.BRepElement_geometry(self) + + def __init__(self, id, parent_id, name, type, guid, context, trsf, geometry, product): + r"""__init__(BRepElement self, int id, int parent_id, std::string const & name, std::string const & type, std::string const & guid, std::string const & context, ifcopenshell::geometry::taxonomy::matrix4::ptr const & trsf, boost::shared_ptr< IfcGeom::Representation::BRep > const & geometry, IfcBaseEntity product) -> BRepElement""" + _ifcopenshell_wrapper.BRepElement_swiginit(self, _ifcopenshell_wrapper.new_BRepElement(id, parent_id, name, type, guid, context, trsf, geometry, product)) + + def calculate_projected_surface_area(self, along_x, along_y, along_z): + r"""calculate_projected_surface_area(BRepElement self, double & along_x, double & along_y, double & along_z) -> bool""" + return _ifcopenshell_wrapper.BRepElement_calculate_projected_surface_area(self, along_x, along_y, along_z) + + def calc_volume_(self): + r"""calc_volume_(BRepElement self) -> double""" + return _ifcopenshell_wrapper.BRepElement_calc_volume_(self) + + def calc_surface_area_(self): + r"""calc_surface_area_(BRepElement self) -> double""" + return _ifcopenshell_wrapper.BRepElement_calc_surface_area_(self) + + # Hide the getters with read-only property implementations + geometry = property(geometry) + volume = property(calc_volume_) + surface_area = property(calc_surface_area_) + + __swig_destroy__ = _ifcopenshell_wrapper.delete_BRepElement + +# Register BRepElement in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.BRepElement_swigregister(BRepElement) + +class TriangulationElement(Element): + r"""Proxy of C++ IfcGeom::TriangulationElement class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def geometry(self): + r"""geometry(TriangulationElement self) -> Triangulation""" + return _ifcopenshell_wrapper.TriangulationElement_geometry(self) + + def geometry_pointer(self): + r"""geometry_pointer(TriangulationElement self) -> boost::shared_ptr< IfcGeom::Representation::Triangulation > const &""" + return _ifcopenshell_wrapper.TriangulationElement_geometry_pointer(self) + + def __init__(self, *args): + r""" + __init__(TriangulationElement self, BRepElement shape_model) -> TriangulationElement + __init__(TriangulationElement self, Element element, boost::shared_ptr< IfcGeom::Representation::Triangulation > const & geometry) -> TriangulationElement + """ + _ifcopenshell_wrapper.TriangulationElement_swiginit(self, _ifcopenshell_wrapper.new_TriangulationElement(*args)) + + # Hide the getters with read-only property implementations + geometry = property(geometry) + + __swig_destroy__ = _ifcopenshell_wrapper.delete_TriangulationElement + +# Register TriangulationElement in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.TriangulationElement_swigregister(TriangulationElement) + +class SerializedElement(Element): + r"""Proxy of C++ IfcGeom::SerializedElement class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def geometry(self): + r"""geometry(SerializedElement self) -> Serialization""" + return _ifcopenshell_wrapper.SerializedElement_geometry(self) + + def __init__(self, shape_model): + r"""__init__(SerializedElement self, BRepElement shape_model) -> SerializedElement""" + _ifcopenshell_wrapper.SerializedElement_swiginit(self, _ifcopenshell_wrapper.new_SerializedElement(shape_model)) + __swig_destroy__ = _ifcopenshell_wrapper.delete_SerializedElement + + # Hide the getters with read-only property implementations + geometry = property(geometry) + + +# Register SerializedElement in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.SerializedElement_swigregister(SerializedElement) + +class Representation(object): + r"""Proxy of C++ IfcGeom::Representation::Representation class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def __init__(self, settings, entity, id): + r"""__init__(Representation self, Settings settings, std::string const & entity, std::string const & id) -> Representation""" + _ifcopenshell_wrapper.Representation_swiginit(self, _ifcopenshell_wrapper.new_Representation(settings, entity, id)) + + def settings(self): + r"""settings(Representation self) -> Settings""" + return _ifcopenshell_wrapper.Representation_settings(self) + + def entity(self): + r"""entity(Representation self) -> std::string const &""" + return _ifcopenshell_wrapper.Representation_entity(self) + + def id(self): + r"""id(Representation self) -> std::string const &""" + return _ifcopenshell_wrapper.Representation_id(self) + __swig_destroy__ = _ifcopenshell_wrapper.delete_Representation + + # Hide the getters with read-only property implementations + id = property(id) + + +# Register Representation in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.Representation_swigregister(Representation) + +class BRep(Representation): + r"""Proxy of C++ IfcGeom::Representation::BRep class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def __init__(self, settings, entity, id, shapes): + r"""__init__(BRep self, Settings settings, std::string const & entity, std::string const & id, IfcGeom::ConversionResults const & shapes) -> BRep""" + _ifcopenshell_wrapper.BRep_swiginit(self, _ifcopenshell_wrapper.new_BRep(settings, entity, id, shapes)) + __swig_destroy__ = _ifcopenshell_wrapper.delete_BRep + + def begin(self): + r"""begin(BRep self) -> IfcGeom::ConversionResults::const_iterator""" + return _ifcopenshell_wrapper.BRep_begin(self) + + def end(self): + r"""end(BRep self) -> IfcGeom::ConversionResults::const_iterator""" + return _ifcopenshell_wrapper.BRep_end(self) + + def shapes(self): + r"""shapes(BRep self) -> IfcGeom::ConversionResults const &""" + return _ifcopenshell_wrapper.BRep_shapes(self) + + def as_compound(self, force_meters=False): + r"""as_compound(BRep self, bool force_meters=False) -> ConversionResultShape""" + return _ifcopenshell_wrapper.BRep_as_compound(self, force_meters) + + def calculate_volume(self, arg2): + r"""calculate_volume(BRep self, double & arg2) -> bool""" + return _ifcopenshell_wrapper.BRep_calculate_volume(self, arg2) + + def calculate_surface_area(self, arg2): + r"""calculate_surface_area(BRep self, double & arg2) -> bool""" + return _ifcopenshell_wrapper.BRep_calculate_surface_area(self, arg2) + + def calculate_projected_surface_area(self, ax, along_x, along_y, along_z): + r"""calculate_projected_surface_area(BRep self, ifcopenshell::geometry::taxonomy::matrix4::ptr const & ax, double & along_x, double & along_y, double & along_z) -> bool""" + return _ifcopenshell_wrapper.BRep_calculate_projected_surface_area(self, ax, along_x, along_y, along_z) + + def size(self): + r"""size(BRep self) -> int""" + return _ifcopenshell_wrapper.BRep_size(self) + + def item(self, i): + r"""item(BRep self, int i) -> ConversionResultShape""" + return _ifcopenshell_wrapper.BRep_item(self, i) + + def item_id(self, i): + r"""item_id(BRep self, int i) -> int""" + return _ifcopenshell_wrapper.BRep_item_id(self, i) + +# Register BRep in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.BRep_swigregister(BRep) + +class Serialization(Representation): + r"""Proxy of C++ IfcGeom::Representation::Serialization class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def brep_data(self): + r"""brep_data(Serialization self) -> std::string const &""" + return _ifcopenshell_wrapper.Serialization_brep_data(self) + + def surface_styles(self): + r"""surface_styles(Serialization self) -> std::vector< double,std::allocator< double > > const &""" + return _ifcopenshell_wrapper.Serialization_surface_styles(self) + + def surface_style_ids(self): + r"""surface_style_ids(Serialization self) -> std::vector< int,std::allocator< int > > const &""" + return _ifcopenshell_wrapper.Serialization_surface_style_ids(self) + + def __init__(self, brep): + r"""__init__(Serialization self, BRep brep) -> Serialization""" + _ifcopenshell_wrapper.Serialization_swiginit(self, _ifcopenshell_wrapper.new_Serialization(brep)) + __swig_destroy__ = _ifcopenshell_wrapper.delete_Serialization + + # Hide the getters with read-only property implementations + brep_data = property(brep_data) + surface_styles = property(surface_styles) + surface_style_ids = property(surface_style_ids) + + +# Register Serialization in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.Serialization_swigregister(Serialization) + +class Triangulation(Representation): + r"""Proxy of C++ IfcGeom::Representation::Triangulation class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def verts(self): + r"""verts(Triangulation self) -> std::vector< double,std::allocator< double > > const &""" + return _ifcopenshell_wrapper.Triangulation_verts(self) + + def faces(self): + r"""faces(Triangulation self) -> std::vector< int,std::allocator< int > > const &""" + return _ifcopenshell_wrapper.Triangulation_faces(self) + + def polyhedral_faces_without_holes(self): + r"""polyhedral_faces_without_holes(Triangulation self) -> std::vector< std::vector< int,std::allocator< int > >,std::allocator< std::vector< int,std::allocator< int > > > > const &""" + return _ifcopenshell_wrapper.Triangulation_polyhedral_faces_without_holes(self) + + def polyhedral_faces_with_holes(self): + r"""polyhedral_faces_with_holes(Triangulation self) -> std::vector< std::vector< std::vector< int,std::allocator< int > >,std::allocator< std::vector< int,std::allocator< int > > > >,std::allocator< std::vector< std::vector< int,std::allocator< int > >,std::allocator< std::vector< int,std::allocator< int > > > > > > const &""" + return _ifcopenshell_wrapper.Triangulation_polyhedral_faces_with_holes(self) + + def edges(self): + r"""edges(Triangulation self) -> std::vector< int,std::allocator< int > > const &""" + return _ifcopenshell_wrapper.Triangulation_edges(self) + + def normals(self): + r"""normals(Triangulation self) -> std::vector< double,std::allocator< double > > const &""" + return _ifcopenshell_wrapper.Triangulation_normals(self) + + def uvs(self): + r"""uvs(Triangulation self) -> std::vector< double,std::allocator< double > > const &""" + return _ifcopenshell_wrapper.Triangulation_uvs(self) + + def uvs_ref(self): + r"""uvs_ref(Triangulation self) -> std::vector< double,std::allocator< double > > &""" + return _ifcopenshell_wrapper.Triangulation_uvs_ref(self) + + def material_ids(self): + r"""material_ids(Triangulation self) -> std::vector< int,std::allocator< int > > const &""" + return _ifcopenshell_wrapper.Triangulation_material_ids(self) + + def materials(self): + r"""materials(Triangulation self) -> std::vector< ifcopenshell::geometry::taxonomy::style::ptr,std::allocator< ifcopenshell::geometry::taxonomy::style::ptr > > const &""" + return _ifcopenshell_wrapper.Triangulation_materials(self) + + def item_ids(self): + r"""item_ids(Triangulation self) -> std::vector< int,std::allocator< int > > const &""" + return _ifcopenshell_wrapper.Triangulation_item_ids(self) + + def edges_item_ids(self): + r"""edges_item_ids(Triangulation self) -> std::vector< int,std::allocator< int > > const &""" + return _ifcopenshell_wrapper.Triangulation_edges_item_ids(self) + + def __init__(self, *args): + r""" + __init__(Triangulation self, BRep shape_model) -> Triangulation + __init__(Triangulation self, Settings settings, std::string const & entity, std::string const & id, std::vector< double,std::allocator< double > > const & verts, std::vector< int,std::allocator< int > > const & faces, std::vector< int,std::allocator< int > > const & edges, std::vector< double,std::allocator< double > > const & normals, std::vector< double,std::allocator< double > > const & uvs, std::vector< int,std::allocator< int > > const & material_ids, std::vector< ifcopenshell::geometry::taxonomy::style::ptr,std::allocator< ifcopenshell::geometry::taxonomy::style::ptr > > const & materials, std::vector< int,std::allocator< int > > const & item_ids, std::vector< int,std::allocator< int > > const & edges_item_ids) -> Triangulation + """ + _ifcopenshell_wrapper.Triangulation_swiginit(self, _ifcopenshell_wrapper.new_Triangulation(*args)) + __swig_destroy__ = _ifcopenshell_wrapper.delete_Triangulation + + @staticmethod + def box_project_uvs(vertices, normals): + r"""box_project_uvs(std::vector< double,std::allocator< double > > const & vertices, std::vector< double,std::allocator< double > > const & normals) -> std::vector< double,std::allocator< double > >""" + return _ifcopenshell_wrapper.Triangulation_box_project_uvs(vertices, normals) + + @staticmethod + def empty(settings): + r"""empty(Settings settings) -> Triangulation""" + return _ifcopenshell_wrapper.Triangulation_empty(settings) + + def addVertex(self, item_index, material_index, X, Y, Z): + r"""addVertex(Triangulation self, int item_index, int material_index, double X, double Y, double Z) -> int""" + return _ifcopenshell_wrapper.Triangulation_addVertex(self, item_index, material_index, X, Y, Z) + + def addNormal(self, X, Y, Z): + r"""addNormal(Triangulation self, double X, double Y, double Z)""" + return _ifcopenshell_wrapper.Triangulation_addNormal(self, X, Y, Z) + + def addFace(self, *args): + r""" + addFace(Triangulation self, int item_id, int style, int i0, int i1, int i2) + addFace(Triangulation self, int item_id, int style, std::vector< int,std::allocator< int > > const & outer_bound) + addFace(Triangulation self, int item_id, int style, std::vector< std::vector< int,std::allocator< int > >,std::allocator< std::vector< int,std::allocator< int > > > > const & bounds) + """ + return _ifcopenshell_wrapper.Triangulation_addFace(self, *args) + + def addEdge(self, item_id, style, i0, i1): + r"""addEdge(Triangulation self, int item_id, int style, int i0, int i1)""" + return _ifcopenshell_wrapper.Triangulation_addEdge(self, item_id, style, i0, i1) + + def registerEdge(self, item_id, i0, i1): + r"""registerEdge(Triangulation self, int item_id, int i0, int i1)""" + return _ifcopenshell_wrapper.Triangulation_registerEdge(self, item_id, i0, i1) + + def registerEdgeCount(self, n1, n2, edgecount): + r"""registerEdgeCount(Triangulation self, int n1, int n2, std::map< std::pair< int,int >,int > & edgecount)""" + return _ifcopenshell_wrapper.Triangulation_registerEdgeCount(self, n1, n2, edgecount) + + def resetWelds(self): + r"""resetWelds(Triangulation self)""" + return _ifcopenshell_wrapper.Triangulation_resetWelds(self) + + def faces_buffer(self): + r"""faces_buffer(Triangulation self) -> std::pair< char const *,size_t >""" + return _ifcopenshell_wrapper.Triangulation_faces_buffer(self) + + def edges_buffer(self): + r"""edges_buffer(Triangulation self) -> std::pair< char const *,size_t >""" + return _ifcopenshell_wrapper.Triangulation_edges_buffer(self) + + def material_ids_buffer(self): + r"""material_ids_buffer(Triangulation self) -> std::pair< char const *,size_t >""" + return _ifcopenshell_wrapper.Triangulation_material_ids_buffer(self) + + def item_ids_buffer(self): + r"""item_ids_buffer(Triangulation self) -> std::pair< char const *,size_t >""" + return _ifcopenshell_wrapper.Triangulation_item_ids_buffer(self) + + def edges_item_ids_buffer(self): + r"""edges_item_ids_buffer(Triangulation self) -> std::pair< char const *,size_t >""" + return _ifcopenshell_wrapper.Triangulation_edges_item_ids_buffer(self) + + def verts_buffer(self): + r"""verts_buffer(Triangulation self) -> std::pair< char const *,size_t >""" + return _ifcopenshell_wrapper.Triangulation_verts_buffer(self) + + def normals_buffer(self): + r"""normals_buffer(Triangulation self) -> std::pair< char const *,size_t >""" + return _ifcopenshell_wrapper.Triangulation_normals_buffer(self) + + def colors_buffer(self): + r"""colors_buffer(Triangulation self) -> PyObject *""" + return _ifcopenshell_wrapper.Triangulation_colors_buffer(self) + + # Hide the getters with read-only property implementations + faces_tri = property(faces) + polyhedral_faces_without_holes = property(polyhedral_faces_without_holes) + polyhedral_faces_with_holes = property(polyhedral_faces_with_holes) + def get_faces(self): + if self.faces_tri: + return self.faces_tri + elif self.polyhedral_faces_without_holes: + return self.polyhedral_faces_without_holes + else: + return self.polyhedral_faces_with_holes + faces = property(get_faces) + edges = property(edges) + material_ids = property(material_ids) + materials = property(materials) + verts = property(verts) + normals = property(normals) + item_ids = property(item_ids) + uvs = property(uvs) + edges_item_ids = property(edges_item_ids) + + faces_buffer = property(faces_buffer) + edges_buffer = property(edges_buffer) + material_ids_buffer = property(material_ids_buffer) + item_ids_buffer = property(item_ids_buffer) + edges_item_ids_buffer = property(edges_item_ids_buffer) + verts_buffer = property(verts_buffer) + normals_buffer = property(normals_buffer) + colors_buffer = property(colors_buffer) + + +# Register Triangulation in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.Triangulation_swigregister(Triangulation) + +def Triangulation_box_project_uvs(vertices, normals): + r"""Triangulation_box_project_uvs(std::vector< double,std::allocator< double > > const & vertices, std::vector< double,std::allocator< double > > const & normals) -> std::vector< double,std::allocator< double > >""" + return _ifcopenshell_wrapper.Triangulation_box_project_uvs(vertices, normals) + +def Triangulation_empty(settings): + r"""Triangulation_empty(Settings settings) -> Triangulation""" + return _ifcopenshell_wrapper.Triangulation_empty(settings) + +class geometry_conversion_result(object): + r"""Proxy of C++ IfcGeom::geometry_conversion_result class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + index = property(_ifcopenshell_wrapper.geometry_conversion_result_index_get, _ifcopenshell_wrapper.geometry_conversion_result_index_set, doc=r"""index : int""") + item = property(_ifcopenshell_wrapper.geometry_conversion_result_item_get, _ifcopenshell_wrapper.geometry_conversion_result_item_set, doc=r"""item : ifcopenshell::geometry::taxonomy::ptr""") + products = property(_ifcopenshell_wrapper.geometry_conversion_result_products_get, _ifcopenshell_wrapper.geometry_conversion_result_products_set, doc=r"""products : std::vector<(std::pair<(p.IfcUtil::IfcBaseEntity,ifcopenshell::geometry::taxonomy::matrix4::ptr)>,std::allocator<(std::pair<(p.IfcUtil::IfcBaseEntity,ifcopenshell::geometry::taxonomy::matrix4::ptr)>)>)>""") + representation = property(_ifcopenshell_wrapper.geometry_conversion_result_representation_get, _ifcopenshell_wrapper.geometry_conversion_result_representation_set, doc=r"""representation : p.IfcUtil::IfcBaseEntity""") + products_2 = property(_ifcopenshell_wrapper.geometry_conversion_result_products_2_get, _ifcopenshell_wrapper.geometry_conversion_result_products_2_set, doc=r"""products_2 : aggregate_of_instance::ptr""") + breps = property(_ifcopenshell_wrapper.geometry_conversion_result_breps_get, _ifcopenshell_wrapper.geometry_conversion_result_breps_set, doc=r"""breps : std::vector<(p.IfcGeom::BRepElement,std::allocator<(p.IfcGeom::BRepElement)>)>""") + elements = property(_ifcopenshell_wrapper.geometry_conversion_result_elements_get, _ifcopenshell_wrapper.geometry_conversion_result_elements_set, doc=r"""elements : std::vector<(p.IfcGeom::Element,std::allocator<(p.IfcGeom::Element)>)>""") + + def __init__(self): + r"""__init__(geometry_conversion_result self) -> geometry_conversion_result""" + _ifcopenshell_wrapper.geometry_conversion_result_swiginit(self, _ifcopenshell_wrapper.new_geometry_conversion_result()) + __swig_destroy__ = _ifcopenshell_wrapper.delete_geometry_conversion_result + +# Register geometry_conversion_result in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.geometry_conversion_result_swigregister(geometry_conversion_result) + +class Iterator(object): + r"""Proxy of C++ IfcGeom::Iterator class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def __init__(self, *args): + r""" + __init__(Iterator self, std::unique_ptr< ifcopenshell::geometry::kernels::AbstractKernel > && geometry_library, Settings settings, file file, std::vector< IfcGeom::filter_t,std::allocator< IfcGeom::filter_t > > const & filters, int num_threads) -> Iterator + __init__(Iterator self, std::unique_ptr< ifcopenshell::geometry::kernels::AbstractKernel > && geometry_library, Settings settings, file file) -> Iterator + __init__(Iterator self, std::unique_ptr< ifcopenshell::geometry::kernels::AbstractKernel > && geometry_library, Settings settings, file file, int num_threads) -> Iterator + """ + _ifcopenshell_wrapper.Iterator_swiginit(self, _ifcopenshell_wrapper.new_Iterator(*args)) + __swig_destroy__ = _ifcopenshell_wrapper.delete_Iterator + + def set_cache(self, cache): + r"""set_cache(Iterator self, GeometrySerializer cache)""" + return _ifcopenshell_wrapper.Iterator_set_cache(self, cache) + + def get_task_items(self): + r"""get_task_items(Iterator self) -> std::vector< ifcopenshell::geometry::taxonomy::item::ptr,std::allocator< ifcopenshell::geometry::taxonomy::item::ptr > >""" + return _ifcopenshell_wrapper.Iterator_get_task_items(self) + + def get_task_products(self): + r"""get_task_products(Iterator self) -> aggregate_of_aggregate_of_instance::ptr""" + return _ifcopenshell_wrapper.Iterator_get_task_products(self) + + def unit_name(self): + r"""unit_name(Iterator self) -> std::string const &""" + return _ifcopenshell_wrapper.Iterator_unit_name(self) + + def unit_magnitude(self): + r"""unit_magnitude(Iterator self) -> double""" + return _ifcopenshell_wrapper.Iterator_unit_magnitude(self) + + def had_error_processing_elements(self): + r"""had_error_processing_elements(Iterator self) -> bool""" + return _ifcopenshell_wrapper.Iterator_had_error_processing_elements(self) + initialization_outcome_ = property(_ifcopenshell_wrapper.Iterator_initialization_outcome__get, _ifcopenshell_wrapper.Iterator_initialization_outcome__set, doc=r"""initialization_outcome_ : boost::optional<(bool)>""") + + def initialize(self): + r"""initialize(Iterator self) -> bool""" + return _ifcopenshell_wrapper.Iterator_initialize(self) + processed_ = property(_ifcopenshell_wrapper.Iterator_processed__get, _ifcopenshell_wrapper.Iterator_processed__set, doc=r"""processed_ : size_t""") + + def process_finished_rep(self, rep): + r"""process_finished_rep(Iterator self, geometry_conversion_result rep)""" + return _ifcopenshell_wrapper.Iterator_process_finished_rep(self, rep) + + def process_concurrently(self): + r"""process_concurrently(Iterator self)""" + return _ifcopenshell_wrapper.Iterator_process_concurrently(self) + + def compute_bounds(self, with_geometry): + r"""compute_bounds(Iterator self, bool with_geometry)""" + return _ifcopenshell_wrapper.Iterator_compute_bounds(self, with_geometry) + + def progress(self): + r"""progress(Iterator self) -> int""" + return _ifcopenshell_wrapper.Iterator_progress(self) + + def getLog(self): + r"""getLog(Iterator self) -> std::string""" + return _ifcopenshell_wrapper.Iterator_getLog(self) + + def file(self): + r"""file(Iterator self) -> file""" + return _ifcopenshell_wrapper.Iterator_file(self) + + def filters(self, *args): + r""" + filters(Iterator self) -> std::vector< IfcGeom::filter_t,std::allocator< IfcGeom::filter_t > > const + filters(Iterator self) -> std::vector< IfcGeom::filter_t,std::allocator< IfcGeom::filter_t > > & + """ + return _ifcopenshell_wrapper.Iterator_filters(self, *args) + + def bounds_min(self): + r"""bounds_min(Iterator self) -> point3""" + return _ifcopenshell_wrapper.Iterator_bounds_min(self) + + def bounds_max(self): + r"""bounds_max(Iterator self) -> point3""" + return _ifcopenshell_wrapper.Iterator_bounds_max(self) + + def next(self): + r"""next(Iterator self) -> entity_instance""" + return _ifcopenshell_wrapper.Iterator_next(self) + + def get(self): + r"""get(Iterator self) -> Element""" + return _ifcopenshell_wrapper.Iterator_get(self) + + def get_native(self): + r"""get_native(Iterator self) -> BRepElement""" + return _ifcopenshell_wrapper.Iterator_get_native(self) + + def get_object(self, id): + r"""get_object(Iterator self, int id) -> Element""" + return _ifcopenshell_wrapper.Iterator_get_object(self, id) + + def create(self): + r"""create(Iterator self) -> entity_instance""" + return _ifcopenshell_wrapper.Iterator_create(self) + +# Register Iterator in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.Iterator_swigregister(Iterator) + +class SerializerSettings(object): + r"""Proxy of C++ ifcopenshell::geometry::SerializerSettings class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def set_(self, *args): + r""" + set_(SerializerSettings self, std::string const & name, bool val) + set_(SerializerSettings self, std::string const & name, int val) + set_(SerializerSettings self, std::string const & name, double val) + set_(SerializerSettings self, std::string const & name, std::string const & val) + set_(SerializerSettings self, std::string const & name, std::set< int > const & val) + """ + return _ifcopenshell_wrapper.SerializerSettings_set_(self, *args) + + def get_(self, name): + r"""get_(SerializerSettings self, std::string const & name) -> ifcopenshell::geometry::SerializerSettings::value_variant_t""" + return _ifcopenshell_wrapper.SerializerSettings_get_(self, name) + + def setting_names(self): + r"""setting_names(SerializerSettings self) -> std::vector< std::string,std::allocator< std::string > >""" + return _ifcopenshell_wrapper.SerializerSettings_setting_names(self) + + def get_type(self, name): + r"""get_type(SerializerSettings self, std::string const & name) -> std::string""" + return _ifcopenshell_wrapper.SerializerSettings_get_type(self, name) + + def __init__(self): + r"""__init__(SerializerSettings self) -> SerializerSettings""" + _ifcopenshell_wrapper.SerializerSettings_swiginit(self, _ifcopenshell_wrapper.new_SerializerSettings()) + __swig_destroy__ = _ifcopenshell_wrapper.delete_SerializerSettings + +# Register SerializerSettings in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.SerializerSettings_swigregister(SerializerSettings) + +class buffer(object): + r"""Proxy of C++ stream_or_filename class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def __init__(self, *args): + r""" + __init__(buffer self, std::string const & fn) -> buffer + __init__(buffer self) -> buffer + """ + _ifcopenshell_wrapper.buffer_swiginit(self, _ifcopenshell_wrapper.new_buffer(*args)) + + def get_value(self): + r"""get_value(buffer self) -> std::string""" + return _ifcopenshell_wrapper.buffer_get_value(self) + + def filename(self): + r"""filename(buffer self) -> boost::optional< std::string >""" + return _ifcopenshell_wrapper.buffer_filename(self) + + def is_ready(self): + r"""is_ready(buffer self) -> bool""" + return _ifcopenshell_wrapper.buffer_is_ready(self) + __swig_destroy__ = _ifcopenshell_wrapper.delete_buffer + +# Register buffer in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.buffer_swigregister(buffer) + +class GeometrySerializer(object): + r"""Proxy of C++ GeometrySerializer class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + + def __init__(self, *args, **kwargs): + raise AttributeError("No constructor defined - class is abstract") + __repr__ = _swig_repr + READ_BREP = _ifcopenshell_wrapper.GeometrySerializer_READ_BREP + + READ_TRIANGULATION = _ifcopenshell_wrapper.GeometrySerializer_READ_TRIANGULATION + + __swig_destroy__ = _ifcopenshell_wrapper.delete_GeometrySerializer + + def isTesselated(self): + r"""isTesselated(GeometrySerializer self) -> bool""" + return _ifcopenshell_wrapper.GeometrySerializer_isTesselated(self) + + def write(self, *args): + r""" + write(GeometrySerializer self, TriangulationElement o) + write(GeometrySerializer self, BRepElement o) + """ + return _ifcopenshell_wrapper.GeometrySerializer_write(self, *args) + + def setUnitNameAndMagnitude(self, name, magnitude): + r"""setUnitNameAndMagnitude(GeometrySerializer self, std::string const & name, float magnitude)""" + return _ifcopenshell_wrapper.GeometrySerializer_setUnitNameAndMagnitude(self, name, magnitude) + + def read(self, *args): + r"""read(GeometrySerializer self, file f, std::string const & guid, std::string const & representation_id, GeometrySerializer::read_type rt=READ_BREP) -> Element""" + return _ifcopenshell_wrapper.GeometrySerializer_read(self, *args) + + def settings(self, *args): + r""" + settings(GeometrySerializer self) -> SerializerSettings + settings(GeometrySerializer self) -> SerializerSettings + """ + return _ifcopenshell_wrapper.GeometrySerializer_settings(self, *args) + + def geometry_settings(self, *args): + r""" + geometry_settings(GeometrySerializer self) -> Settings + geometry_settings(GeometrySerializer self) -> Settings + """ + return _ifcopenshell_wrapper.GeometrySerializer_geometry_settings(self, *args) + + def object_id(self, o): + r"""object_id(GeometrySerializer self, Element o) -> std::string""" + return _ifcopenshell_wrapper.GeometrySerializer_object_id(self, o) + +# Register GeometrySerializer in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.GeometrySerializer_swigregister(GeometrySerializer) + +class WriteOnlyGeometrySerializer(GeometrySerializer): + r"""Proxy of C++ WriteOnlyGeometrySerializer class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + + def __init__(self, *args, **kwargs): + raise AttributeError("No constructor defined - class is abstract") + __repr__ = _swig_repr + + def read(self, *args): + r"""read(WriteOnlyGeometrySerializer self, file arg2, std::string const & arg3, std::string const & arg4, GeometrySerializer::read_type arg5=READ_BREP) -> Element""" + return _ifcopenshell_wrapper.WriteOnlyGeometrySerializer_read(self, *args) + __swig_destroy__ = _ifcopenshell_wrapper.delete_WriteOnlyGeometrySerializer + +# Register WriteOnlyGeometrySerializer in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.WriteOnlyGeometrySerializer_swigregister(WriteOnlyGeometrySerializer) + +MATRIX4 = _ifcopenshell_wrapper.MATRIX4 + +POINT3 = _ifcopenshell_wrapper.POINT3 + +DIRECTION3 = _ifcopenshell_wrapper.DIRECTION3 + +LINE = _ifcopenshell_wrapper.LINE + +CIRCLE = _ifcopenshell_wrapper.CIRCLE + +ELLIPSE = _ifcopenshell_wrapper.ELLIPSE + +BSPLINE_CURVE = _ifcopenshell_wrapper.BSPLINE_CURVE + +OFFSET_CURVE = _ifcopenshell_wrapper.OFFSET_CURVE + +PLANE = _ifcopenshell_wrapper.PLANE + +CYLINDER = _ifcopenshell_wrapper.CYLINDER + +SPHERE = _ifcopenshell_wrapper.SPHERE + +TORUS = _ifcopenshell_wrapper.TORUS + +BSPLINE_SURFACE = _ifcopenshell_wrapper.BSPLINE_SURFACE + +EDGE = _ifcopenshell_wrapper.EDGE + +LOOP = _ifcopenshell_wrapper.LOOP + +FACE = _ifcopenshell_wrapper.FACE + +SHELL = _ifcopenshell_wrapper.SHELL + +SOLID = _ifcopenshell_wrapper.SOLID + +LOFT = _ifcopenshell_wrapper.LOFT + +EXTRUSION = _ifcopenshell_wrapper.EXTRUSION + +REVOLVE = _ifcopenshell_wrapper.REVOLVE + +SWEEP_ALONG_CURVE = _ifcopenshell_wrapper.SWEEP_ALONG_CURVE + +NODE = _ifcopenshell_wrapper.NODE + +COLLECTION = _ifcopenshell_wrapper.COLLECTION + +BOOLEAN_RESULT = _ifcopenshell_wrapper.BOOLEAN_RESULT + +FUNCTION_ITEM = _ifcopenshell_wrapper.FUNCTION_ITEM + +FUNCTOR_ITEM = _ifcopenshell_wrapper.FUNCTOR_ITEM + +PIECEWISE_FUNCTION = _ifcopenshell_wrapper.PIECEWISE_FUNCTION + +GRADIENT_FUNCTION = _ifcopenshell_wrapper.GRADIENT_FUNCTION + +CANT_FUNCTION = _ifcopenshell_wrapper.CANT_FUNCTION + +OFFSET_FUNCTION = _ifcopenshell_wrapper.OFFSET_FUNCTION + +COLOUR = _ifcopenshell_wrapper.COLOUR + +STYLE = _ifcopenshell_wrapper.STYLE + + +def kind_to_string(k): + r"""kind_to_string(ifcopenshell::geometry::taxonomy::kinds k) -> std::string const &""" + return _ifcopenshell_wrapper.kind_to_string(k) +class item(object): + r"""Proxy of C++ ifcopenshell::geometry::taxonomy::item class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + + def __init__(self, *args, **kwargs): + raise AttributeError("No constructor defined - class is abstract") + __repr__ = _swig_repr + instance = property(_ifcopenshell_wrapper.item_instance_get, _ifcopenshell_wrapper.item_instance_set, doc=r"""instance : p.q(const).IfcUtil::IfcBaseInterface""") + orientation = property(_ifcopenshell_wrapper.item_orientation_get, _ifcopenshell_wrapper.item_orientation_set, doc=r"""orientation : boost::optional<(bool)>""") + + def clone_(self): + r"""clone_(item self) -> item""" + return _ifcopenshell_wrapper.item_clone_(self) + + def kind(self): + r"""kind(item self) -> ifcopenshell::geometry::taxonomy::kinds""" + return _ifcopenshell_wrapper.item_kind(self) + + def reverse(self): + r"""reverse(item self)""" + return _ifcopenshell_wrapper.item_reverse(self) + + def calc_hash(self): + r"""calc_hash(item self) -> size_t""" + return _ifcopenshell_wrapper.item_calc_hash(self) + + def hash(self): + r"""hash(item self) -> size_t""" + return _ifcopenshell_wrapper.item_hash(self) + __swig_destroy__ = _ifcopenshell_wrapper.delete_item + + def identity(self): + r"""identity(item self) -> uint32_t""" + return _ifcopenshell_wrapper.item_identity(self) + +# Register item in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.item_swigregister(item) + +class matrix4(item): + r"""Proxy of C++ ifcopenshell::geometry::taxonomy::matrix4 class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + IDENTITY = _ifcopenshell_wrapper.matrix4_IDENTITY + + AFFINE_WO_SCALE = _ifcopenshell_wrapper.matrix4_AFFINE_WO_SCALE + + AFFINE_W_UNIFORM_SCALE = _ifcopenshell_wrapper.matrix4_AFFINE_W_UNIFORM_SCALE + + AFFINE_W_NONUNIFORM_SCALE = _ifcopenshell_wrapper.matrix4_AFFINE_W_NONUNIFORM_SCALE + + OTHER = _ifcopenshell_wrapper.matrix4_OTHER + + tag = property(_ifcopenshell_wrapper.matrix4_tag_get, _ifcopenshell_wrapper.matrix4_tag_set, doc=r"""tag : ifcopenshell::geometry::taxonomy::matrix4::tag_t""") + + def __init__(self, *args): + r""" + __init__(matrix4 self) -> matrix4 + __init__(matrix4 self, Eigen::Matrix4d const & c) -> matrix4 + __init__(matrix4 self, Eigen::Vector3d const & o, Eigen::Vector3d const & z, Eigen::Vector3d const & x) -> matrix4 + __init__(matrix4 self, Eigen::Vector3d const & o, Eigen::Vector3d const & z) -> matrix4 + """ + _ifcopenshell_wrapper.matrix4_swiginit(self, _ifcopenshell_wrapper.new_matrix4(*args)) + + def is_identity(self): + r"""is_identity(matrix4 self) -> bool""" + return _ifcopenshell_wrapper.matrix4_is_identity(self) + + def clone_(self): + r"""clone_(matrix4 self) -> matrix4""" + return _ifcopenshell_wrapper.matrix4_clone_(self) + + def kind(self): + r"""kind(matrix4 self) -> ifcopenshell::geometry::taxonomy::kinds""" + return _ifcopenshell_wrapper.matrix4_kind(self) + + def calc_hash(self): + r"""calc_hash(matrix4 self) -> size_t""" + return _ifcopenshell_wrapper.matrix4_calc_hash(self) + + def pre_multiply_scale(self, s): + r"""pre_multiply_scale(matrix4 self, double s)""" + return _ifcopenshell_wrapper.matrix4_pre_multiply_scale(self, s) + + def post_multiply_scale(self, s): + r"""post_multiply_scale(matrix4 self, double s)""" + return _ifcopenshell_wrapper.matrix4_post_multiply_scale(self, s) + + def translation_part(self): + r"""translation_part(matrix4 self) -> Eigen::Vector3d""" + return _ifcopenshell_wrapper.matrix4_translation_part(self) + + def components_(self): + r"""components_(matrix4 self) -> PyObject *""" + return _ifcopenshell_wrapper.matrix4_components_(self) + + components = property(components_) + + + __repr__ = taxonomy_item_repr + + __swig_destroy__ = _ifcopenshell_wrapper.delete_matrix4 + +# Register matrix4 in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.matrix4_swigregister(matrix4) + +class colour(item): + r"""Proxy of C++ ifcopenshell::geometry::taxonomy::colour class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def clone_(self): + r"""clone_(colour self) -> colour""" + return _ifcopenshell_wrapper.colour_clone_(self) + + def kind(self): + r"""kind(colour self) -> ifcopenshell::geometry::taxonomy::kinds""" + return _ifcopenshell_wrapper.colour_kind(self) + + def calc_hash(self): + r"""calc_hash(colour self) -> size_t""" + return _ifcopenshell_wrapper.colour_calc_hash(self) + + def __init__(self, *args): + r""" + __init__(colour self) -> colour + __init__(colour self, double r, double g, double b) -> colour + """ + _ifcopenshell_wrapper.colour_swiginit(self, _ifcopenshell_wrapper.new_colour(*args)) + + def r(self): + r"""r(colour self) -> double const &""" + return _ifcopenshell_wrapper.colour_r(self) + + def g(self): + r"""g(colour self) -> double const &""" + return _ifcopenshell_wrapper.colour_g(self) + + def b(self): + r"""b(colour self) -> double const &""" + return _ifcopenshell_wrapper.colour_b(self) + + def components_(self): + r"""components_(colour self) -> PyObject *""" + return _ifcopenshell_wrapper.colour_components_(self) + + components = property(components_) + + + __repr__ = taxonomy_item_repr + + __swig_destroy__ = _ifcopenshell_wrapper.delete_colour + +# Register colour in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.colour_swigregister(colour) + +class style(item): + r"""Proxy of C++ ifcopenshell::geometry::taxonomy::style class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + name = property(_ifcopenshell_wrapper.style_name_get, _ifcopenshell_wrapper.style_name_set, doc=r"""name : std::string""") + diffuse = property(_ifcopenshell_wrapper.style_diffuse_get, _ifcopenshell_wrapper.style_diffuse_set, doc=r"""diffuse : ifcopenshell::geometry::taxonomy::colour""") + surface = property(_ifcopenshell_wrapper.style_surface_get, _ifcopenshell_wrapper.style_surface_set, doc=r"""surface : ifcopenshell::geometry::taxonomy::colour""") + specular = property(_ifcopenshell_wrapper.style_specular_get, _ifcopenshell_wrapper.style_specular_set, doc=r"""specular : ifcopenshell::geometry::taxonomy::colour""") + specularity = property(_ifcopenshell_wrapper.style_specularity_get, _ifcopenshell_wrapper.style_specularity_set, doc=r"""specularity : double""") + transparency = property(_ifcopenshell_wrapper.style_transparency_get, _ifcopenshell_wrapper.style_transparency_set, doc=r"""transparency : double""") + use_surface_color = property(_ifcopenshell_wrapper.style_use_surface_color_get, _ifcopenshell_wrapper.style_use_surface_color_set, doc=r"""use_surface_color : bool""") + + def clone_(self): + r"""clone_(style self) -> style""" + return _ifcopenshell_wrapper.style_clone_(self) + + def kind(self): + r"""kind(style self) -> ifcopenshell::geometry::taxonomy::kinds""" + return _ifcopenshell_wrapper.style_kind(self) + + def calc_hash(self): + r"""calc_hash(style self) -> size_t""" + return _ifcopenshell_wrapper.style_calc_hash(self) + + def __eq__(self, other): + r"""__eq__(style self, style other) -> bool""" + return _ifcopenshell_wrapper.style___eq__(self, other) + + def __init__(self, *args): + r""" + __init__(style self) -> style + __init__(style self, std::string const & name) -> style + """ + _ifcopenshell_wrapper.style_swiginit(self, _ifcopenshell_wrapper.new_style(*args)) + + def get_color(self): + r"""get_color(style self) -> colour""" + return _ifcopenshell_wrapper.style_get_color(self) + + def has_specularity(self): + r"""has_specularity(style self) -> bool""" + return _ifcopenshell_wrapper.style_has_specularity(self) + + def has_transparency(self): + r"""has_transparency(style self) -> bool""" + return _ifcopenshell_wrapper.style_has_transparency(self) + + def instance_id(self): + r"""instance_id(style self) -> size_t""" + return _ifcopenshell_wrapper.style_instance_id(self) + + __repr__ = taxonomy_item_repr + + __swig_destroy__ = _ifcopenshell_wrapper.delete_style + +# Register style in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.style_swigregister(style) + +class geom_item(item): + r"""Proxy of C++ ifcopenshell::geometry::taxonomy::geom_item class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + + def __init__(self, *args, **kwargs): + raise AttributeError("No constructor defined - class is abstract") + __repr__ = _swig_repr + surface_style = property(_ifcopenshell_wrapper.geom_item_surface_style_get, _ifcopenshell_wrapper.geom_item_surface_style_set, doc=r"""surface_style : ifcopenshell::geometry::taxonomy::style::ptr""") + matrix = property(_ifcopenshell_wrapper.geom_item_matrix_get, _ifcopenshell_wrapper.geom_item_matrix_set, doc=r"""matrix : ifcopenshell::geometry::taxonomy::matrix4::ptr""") + __swig_destroy__ = _ifcopenshell_wrapper.delete_geom_item + +# Register geom_item in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.geom_item_swigregister(geom_item) + +class implicit_item(geom_item): + r"""Proxy of C++ ifcopenshell::geometry::taxonomy::implicit_item class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + + def __init__(self, *args, **kwargs): + raise AttributeError("No constructor defined - class is abstract") + __repr__ = _swig_repr + __swig_destroy__ = _ifcopenshell_wrapper.delete_implicit_item + +# Register implicit_item in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.implicit_item_swigregister(implicit_item) + +class function_item(implicit_item): + r"""Proxy of C++ ifcopenshell::geometry::taxonomy::function_item class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + + def __init__(self, *args, **kwargs): + raise AttributeError("No constructor defined - class is abstract") + __repr__ = _swig_repr + __swig_destroy__ = _ifcopenshell_wrapper.delete_function_item + + def start(self): + r"""start(function_item self) -> double""" + return _ifcopenshell_wrapper.function_item_start(self) + + def end(self): + r"""end(function_item self) -> double""" + return _ifcopenshell_wrapper.function_item_end(self) + + def length(self): + r"""length(function_item self) -> double""" + return _ifcopenshell_wrapper.function_item_length(self) + + def kind(self): + r"""kind(function_item self) -> ifcopenshell::geometry::taxonomy::kinds""" + return _ifcopenshell_wrapper.function_item_kind(self) + + def calc_hash(self): + r"""calc_hash(function_item self) -> size_t""" + return _ifcopenshell_wrapper.function_item_calc_hash(self) + + __repr__ = taxonomy_item_repr + + +# Register function_item in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.function_item_swigregister(function_item) + +class functor_item(function_item): + r"""Proxy of C++ ifcopenshell::geometry::taxonomy::functor_item class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def __init__(self, *args): + r""" + __init__(functor_item self, double length, std::function< Eigen::Matrix4d (double) > fn, IfcUtil::IfcBaseInterface const * instance=None) -> functor_item + __init__(functor_item self, functor_item arg2) -> functor_item + __init__(functor_item self, functor_item arg2) -> functor_item + """ + _ifcopenshell_wrapper.functor_item_swiginit(self, _ifcopenshell_wrapper.new_functor_item(*args)) + __swig_destroy__ = _ifcopenshell_wrapper.delete_functor_item + + def start(self): + r"""start(functor_item self) -> double""" + return _ifcopenshell_wrapper.functor_item_start(self) + + def end(self): + r"""end(functor_item self) -> double""" + return _ifcopenshell_wrapper.functor_item_end(self) + + def __call__(self, u): + r"""__call__(functor_item self, double u) -> Eigen::Matrix4d""" + return _ifcopenshell_wrapper.functor_item___call__(self, u) + + def clone_(self): + r"""clone_(functor_item self) -> functor_item""" + return _ifcopenshell_wrapper.functor_item_clone_(self) + + def kind(self): + r"""kind(functor_item self) -> ifcopenshell::geometry::taxonomy::kinds""" + return _ifcopenshell_wrapper.functor_item_kind(self) + + def calc_hash(self): + r"""calc_hash(functor_item self) -> size_t""" + return _ifcopenshell_wrapper.functor_item_calc_hash(self) + + __repr__ = taxonomy_item_repr + + +# Register functor_item in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.functor_item_swigregister(functor_item) + +class piecewise_function(function_item): + r"""Proxy of C++ ifcopenshell::geometry::taxonomy::piecewise_function class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def __init__(self, *args): + r""" + __init__(piecewise_function self, double start, ifcopenshell::geometry::taxonomy::piecewise_function::spans_t const & s, IfcUtil::IfcBaseInterface const * instance=None) -> piecewise_function + __init__(piecewise_function self, double start, std::vector< ifcopenshell::geometry::taxonomy::piecewise_function::ptr,std::allocator< ifcopenshell::geometry::taxonomy::piecewise_function::ptr > > const & pwfs, IfcUtil::IfcBaseInterface const * instance=None) -> piecewise_function + __init__(piecewise_function self, piecewise_function arg2) -> piecewise_function + __init__(piecewise_function self, piecewise_function arg2) -> piecewise_function + """ + _ifcopenshell_wrapper.piecewise_function_swiginit(self, _ifcopenshell_wrapper.new_piecewise_function(*args)) + __swig_destroy__ = _ifcopenshell_wrapper.delete_piecewise_function + + def spans(self): + r"""spans(piecewise_function self) -> ifcopenshell::geometry::taxonomy::piecewise_function::spans_t const &""" + return _ifcopenshell_wrapper.piecewise_function_spans(self) + + def span_count(self): + r"""span_count(piecewise_function self) -> size_t""" + return _ifcopenshell_wrapper.piecewise_function_span_count(self) + + def span_fn(self, i): + r"""span_fn(piecewise_function self, size_t i) -> ifcopenshell::geometry::taxonomy::function_item::const_ptr""" + return _ifcopenshell_wrapper.piecewise_function_span_fn(self, i) + + def is_empty(self): + r"""is_empty(piecewise_function self) -> bool""" + return _ifcopenshell_wrapper.piecewise_function_is_empty(self) + + def start(self): + r"""start(piecewise_function self) -> double""" + return _ifcopenshell_wrapper.piecewise_function_start(self) + + def end(self): + r"""end(piecewise_function self) -> double""" + return _ifcopenshell_wrapper.piecewise_function_end(self) + + def length(self): + r"""length(piecewise_function self) -> double""" + return _ifcopenshell_wrapper.piecewise_function_length(self) + + def clone_(self): + r"""clone_(piecewise_function self) -> piecewise_function""" + return _ifcopenshell_wrapper.piecewise_function_clone_(self) + + def kind(self): + r"""kind(piecewise_function self) -> ifcopenshell::geometry::taxonomy::kinds""" + return _ifcopenshell_wrapper.piecewise_function_kind(self) + + def calc_hash(self): + r"""calc_hash(piecewise_function self) -> size_t""" + return _ifcopenshell_wrapper.piecewise_function_calc_hash(self) + + __repr__ = taxonomy_item_repr + + +# Register piecewise_function in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.piecewise_function_swigregister(piecewise_function) + +class gradient_function(function_item): + r"""Proxy of C++ ifcopenshell::geometry::taxonomy::gradient_function class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def __init__(self, *args): + r""" + __init__(gradient_function self, ifcopenshell::geometry::taxonomy::piecewise_function::const_ptr horizontal, ifcopenshell::geometry::taxonomy::piecewise_function::const_ptr vertical, IfcUtil::IfcBaseInterface const * instance=None) -> gradient_function + __init__(gradient_function self, gradient_function arg2) -> gradient_function + __init__(gradient_function self, gradient_function arg2) -> gradient_function + """ + _ifcopenshell_wrapper.gradient_function_swiginit(self, _ifcopenshell_wrapper.new_gradient_function(*args)) + __swig_destroy__ = _ifcopenshell_wrapper.delete_gradient_function + + def start(self): + r"""start(gradient_function self) -> double""" + return _ifcopenshell_wrapper.gradient_function_start(self) + + def end(self): + r"""end(gradient_function self) -> double""" + return _ifcopenshell_wrapper.gradient_function_end(self) + + def get_horizontal(self): + r"""get_horizontal(gradient_function self) -> ifcopenshell::geometry::taxonomy::piecewise_function::const_ptr""" + return _ifcopenshell_wrapper.gradient_function_get_horizontal(self) + + def get_vertical(self): + r"""get_vertical(gradient_function self) -> ifcopenshell::geometry::taxonomy::piecewise_function::const_ptr""" + return _ifcopenshell_wrapper.gradient_function_get_vertical(self) + + def clone_(self): + r"""clone_(gradient_function self) -> gradient_function""" + return _ifcopenshell_wrapper.gradient_function_clone_(self) + + def kind(self): + r"""kind(gradient_function self) -> ifcopenshell::geometry::taxonomy::kinds""" + return _ifcopenshell_wrapper.gradient_function_kind(self) + + def calc_hash(self): + r"""calc_hash(gradient_function self) -> size_t""" + return _ifcopenshell_wrapper.gradient_function_calc_hash(self) + + __repr__ = taxonomy_item_repr + + +# Register gradient_function in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.gradient_function_swigregister(gradient_function) + +class cant_function(function_item): + r"""Proxy of C++ ifcopenshell::geometry::taxonomy::cant_function class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def __init__(self, *args): + r""" + __init__(cant_function self, ifcopenshell::geometry::taxonomy::gradient_function::const_ptr gradient, ifcopenshell::geometry::taxonomy::piecewise_function::const_ptr cant, IfcUtil::IfcBaseInterface const * instance=None) -> cant_function + __init__(cant_function self, cant_function arg2) -> cant_function + __init__(cant_function self, cant_function arg2) -> cant_function + """ + _ifcopenshell_wrapper.cant_function_swiginit(self, _ifcopenshell_wrapper.new_cant_function(*args)) + __swig_destroy__ = _ifcopenshell_wrapper.delete_cant_function + + def start(self): + r"""start(cant_function self) -> double""" + return _ifcopenshell_wrapper.cant_function_start(self) + + def end(self): + r"""end(cant_function self) -> double""" + return _ifcopenshell_wrapper.cant_function_end(self) + + def get_gradient(self): + r"""get_gradient(cant_function self) -> ifcopenshell::geometry::taxonomy::gradient_function::const_ptr""" + return _ifcopenshell_wrapper.cant_function_get_gradient(self) + + def get_cant(self): + r"""get_cant(cant_function self) -> ifcopenshell::geometry::taxonomy::piecewise_function::const_ptr""" + return _ifcopenshell_wrapper.cant_function_get_cant(self) + + def clone_(self): + r"""clone_(cant_function self) -> cant_function""" + return _ifcopenshell_wrapper.cant_function_clone_(self) + + def kind(self): + r"""kind(cant_function self) -> ifcopenshell::geometry::taxonomy::kinds""" + return _ifcopenshell_wrapper.cant_function_kind(self) + + def calc_hash(self): + r"""calc_hash(cant_function self) -> size_t""" + return _ifcopenshell_wrapper.cant_function_calc_hash(self) + + __repr__ = taxonomy_item_repr + + +# Register cant_function in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.cant_function_swigregister(cant_function) + +class offset_function(function_item): + r"""Proxy of C++ ifcopenshell::geometry::taxonomy::offset_function class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def __init__(self, *args): + r""" + __init__(offset_function self, ifcopenshell::geometry::taxonomy::function_item::const_ptr basis, ifcopenshell::geometry::taxonomy::piecewise_function::const_ptr offset, IfcUtil::IfcBaseInterface const * instance=None) -> offset_function + __init__(offset_function self, offset_function arg2) -> offset_function + __init__(offset_function self, offset_function arg2) -> offset_function + """ + _ifcopenshell_wrapper.offset_function_swiginit(self, _ifcopenshell_wrapper.new_offset_function(*args)) + __swig_destroy__ = _ifcopenshell_wrapper.delete_offset_function + + def start(self): + r"""start(offset_function self) -> double""" + return _ifcopenshell_wrapper.offset_function_start(self) + + def end(self): + r"""end(offset_function self) -> double""" + return _ifcopenshell_wrapper.offset_function_end(self) + + def get_basis(self): + r"""get_basis(offset_function self) -> ifcopenshell::geometry::taxonomy::function_item::const_ptr""" + return _ifcopenshell_wrapper.offset_function_get_basis(self) + + def get_offset(self): + r"""get_offset(offset_function self) -> ifcopenshell::geometry::taxonomy::piecewise_function::const_ptr""" + return _ifcopenshell_wrapper.offset_function_get_offset(self) + + def clone_(self): + r"""clone_(offset_function self) -> offset_function""" + return _ifcopenshell_wrapper.offset_function_clone_(self) + + def kind(self): + r"""kind(offset_function self) -> ifcopenshell::geometry::taxonomy::kinds""" + return _ifcopenshell_wrapper.offset_function_kind(self) + + def calc_hash(self): + r"""calc_hash(offset_function self) -> size_t""" + return _ifcopenshell_wrapper.offset_function_calc_hash(self) + + __repr__ = taxonomy_item_repr + + +# Register offset_function in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.offset_function_swigregister(offset_function) + + +def less(arg1, arg2): + r"""less(ifcopenshell::geometry::taxonomy::item::const_ptr arg1, ifcopenshell::geometry::taxonomy::item::const_ptr arg2) -> bool""" + return _ifcopenshell_wrapper.less(arg1, arg2) +class less_functor(object): + r"""Proxy of C++ ifcopenshell::geometry::taxonomy::less_functor class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def __call__(self, a, b): + r"""__call__(less_functor self, ifcopenshell::geometry::taxonomy::item::const_ptr a, ifcopenshell::geometry::taxonomy::item::const_ptr b) -> bool""" + return _ifcopenshell_wrapper.less_functor___call__(self, a, b) + + def __init__(self): + r"""__init__(less_functor self) -> less_functor""" + _ifcopenshell_wrapper.less_functor_swiginit(self, _ifcopenshell_wrapper.new_less_functor()) + __swig_destroy__ = _ifcopenshell_wrapper.delete_less_functor + +# Register less_functor in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.less_functor_swigregister(less_functor) + +class equal_functor(object): + r"""Proxy of C++ ifcopenshell::geometry::taxonomy::equal_functor class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def __call__(self, a, b): + r"""__call__(equal_functor self, ifcopenshell::geometry::taxonomy::item::ptr const & a, ifcopenshell::geometry::taxonomy::item::ptr const & b) -> bool""" + return _ifcopenshell_wrapper.equal_functor___call__(self, a, b) + + def __init__(self): + r"""__init__(equal_functor self) -> equal_functor""" + _ifcopenshell_wrapper.equal_functor_swiginit(self, _ifcopenshell_wrapper.new_equal_functor()) + __swig_destroy__ = _ifcopenshell_wrapper.delete_equal_functor + +# Register equal_functor in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.equal_functor_swigregister(equal_functor) + +class hash_functor(object): + r"""Proxy of C++ ifcopenshell::geometry::taxonomy::hash_functor class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def __call__(self, a): + r"""__call__(hash_functor self, ifcopenshell::geometry::taxonomy::item::ptr const & a) -> size_t""" + return _ifcopenshell_wrapper.hash_functor___call__(self, a) + + def __init__(self): + r"""__init__(hash_functor self) -> hash_functor""" + _ifcopenshell_wrapper.hash_functor_swiginit(self, _ifcopenshell_wrapper.new_hash_functor()) + __swig_destroy__ = _ifcopenshell_wrapper.delete_hash_functor + +# Register hash_functor in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.hash_functor_swigregister(hash_functor) + +class point3(object): + r"""Proxy of C++ ifcopenshell::geometry::taxonomy::point3 class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def clone_(self): + r"""clone_(point3 self) -> point3""" + return _ifcopenshell_wrapper.point3_clone_(self) + + def kind(self): + r"""kind(point3 self) -> ifcopenshell::geometry::taxonomy::kinds""" + return _ifcopenshell_wrapper.point3_kind(self) + + def calc_hash(self): + r"""calc_hash(point3 self) -> size_t""" + return _ifcopenshell_wrapper.point3_calc_hash(self) + + def _print(self, o, indent=0): + r"""_print(point3 self, std::ostream & o, int indent=0)""" + return _ifcopenshell_wrapper.point3__print(self, o, indent) + + def __init__(self, *args): + r""" + __init__(point3 self) -> point3 + __init__(point3 self, Eigen::Vector3d const & c) -> point3 + __init__(point3 self, double x, double y, double z=0.) -> point3 + """ + _ifcopenshell_wrapper.point3_swiginit(self, _ifcopenshell_wrapper.new_point3(*args)) + + def components_(self): + r"""components_(point3 self) -> PyObject *""" + return _ifcopenshell_wrapper.point3_components_(self) + + components = property(components_) + + + __repr__ = taxonomy_item_repr + + __swig_destroy__ = _ifcopenshell_wrapper.delete_point3 + +# Register point3 in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.point3_swigregister(point3) + +class direction3(object): + r"""Proxy of C++ ifcopenshell::geometry::taxonomy::direction3 class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def clone_(self): + r"""clone_(direction3 self) -> direction3""" + return _ifcopenshell_wrapper.direction3_clone_(self) + + def kind(self): + r"""kind(direction3 self) -> ifcopenshell::geometry::taxonomy::kinds""" + return _ifcopenshell_wrapper.direction3_kind(self) + + def calc_hash(self): + r"""calc_hash(direction3 self) -> size_t""" + return _ifcopenshell_wrapper.direction3_calc_hash(self) + + def _print(self, o, indent=0): + r"""_print(direction3 self, std::ostream & o, int indent=0)""" + return _ifcopenshell_wrapper.direction3__print(self, o, indent) + + def __init__(self, *args): + r""" + __init__(direction3 self) -> direction3 + __init__(direction3 self, Eigen::Vector3d const & c) -> direction3 + __init__(direction3 self, double x, double y, double z=0.) -> direction3 + """ + _ifcopenshell_wrapper.direction3_swiginit(self, _ifcopenshell_wrapper.new_direction3(*args)) + + def components_(self): + r"""components_(direction3 self) -> PyObject *""" + return _ifcopenshell_wrapper.direction3_components_(self) + + components = property(components_) + + + __repr__ = taxonomy_item_repr + + __swig_destroy__ = _ifcopenshell_wrapper.delete_direction3 + +# Register direction3 in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.direction3_swigregister(direction3) + +class curve(geom_item): + r"""Proxy of C++ ifcopenshell::geometry::taxonomy::curve class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + + def __init__(self, *args, **kwargs): + raise AttributeError("No constructor defined - class is abstract") + __repr__ = _swig_repr + + def print_impl(self, o, classname, indent=0): + r"""print_impl(curve self, std::ostream & o, std::string const & classname, int indent=0)""" + return _ifcopenshell_wrapper.curve_print_impl(self, o, classname, indent) + __swig_destroy__ = _ifcopenshell_wrapper.delete_curve + +# Register curve in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.curve_swigregister(curve) + +class line(curve): + r"""Proxy of C++ ifcopenshell::geometry::taxonomy::line class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def clone_(self): + r"""clone_(line self) -> line""" + return _ifcopenshell_wrapper.line_clone_(self) + + def kind(self): + r"""kind(line self) -> ifcopenshell::geometry::taxonomy::kinds""" + return _ifcopenshell_wrapper.line_kind(self) + + def calc_hash(self): + r"""calc_hash(line self) -> size_t""" + return _ifcopenshell_wrapper.line_calc_hash(self) + + def matrix_(self): + r"""matrix_(line self) -> ifcopenshell::geometry::taxonomy::matrix4::ptr const &""" + return _ifcopenshell_wrapper.line_matrix_(self) + + matrix = property(matrix_) + + + __repr__ = taxonomy_item_repr + + + def __init__(self): + r"""__init__(line self) -> line""" + _ifcopenshell_wrapper.line_swiginit(self, _ifcopenshell_wrapper.new_line()) + __swig_destroy__ = _ifcopenshell_wrapper.delete_line + +# Register line in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.line_swigregister(line) + +class circle(curve): + r"""Proxy of C++ ifcopenshell::geometry::taxonomy::circle class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + radius = property(_ifcopenshell_wrapper.circle_radius_get, _ifcopenshell_wrapper.circle_radius_set, doc=r"""radius : double""") + + def clone_(self): + r"""clone_(circle self) -> circle""" + return _ifcopenshell_wrapper.circle_clone_(self) + + def kind(self): + r"""kind(circle self) -> ifcopenshell::geometry::taxonomy::kinds""" + return _ifcopenshell_wrapper.circle_kind(self) + + def calc_hash(self): + r"""calc_hash(circle self) -> size_t""" + return _ifcopenshell_wrapper.circle_calc_hash(self) + + @staticmethod + def from_3_points(p1, p2, p3): + r"""from_3_points(Eigen::Vector3d const & p1, Eigen::Vector3d const & p2, Eigen::Vector3d const & p3) -> ifcopenshell::geometry::taxonomy::circle::ptr""" + return _ifcopenshell_wrapper.circle_from_3_points(p1, p2, p3) + + def matrix_(self): + r"""matrix_(circle self) -> ifcopenshell::geometry::taxonomy::matrix4::ptr const &""" + return _ifcopenshell_wrapper.circle_matrix_(self) + + matrix = property(matrix_) + + + __repr__ = taxonomy_item_repr + + + def __init__(self): + r"""__init__(circle self) -> circle""" + _ifcopenshell_wrapper.circle_swiginit(self, _ifcopenshell_wrapper.new_circle()) + __swig_destroy__ = _ifcopenshell_wrapper.delete_circle + +# Register circle in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.circle_swigregister(circle) + +def circle_from_3_points(p1, p2, p3): + r"""circle_from_3_points(Eigen::Vector3d const & p1, Eigen::Vector3d const & p2, Eigen::Vector3d const & p3) -> ifcopenshell::geometry::taxonomy::circle::ptr""" + return _ifcopenshell_wrapper.circle_from_3_points(p1, p2, p3) + +class ellipse(curve): + r"""Proxy of C++ ifcopenshell::geometry::taxonomy::ellipse class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + radius = property(_ifcopenshell_wrapper.ellipse_radius_get, _ifcopenshell_wrapper.ellipse_radius_set, doc=r"""radius : double""") + radius2 = property(_ifcopenshell_wrapper.ellipse_radius2_get, _ifcopenshell_wrapper.ellipse_radius2_set, doc=r"""radius2 : double""") + + def clone_(self): + r"""clone_(ellipse self) -> ellipse""" + return _ifcopenshell_wrapper.ellipse_clone_(self) + + def kind(self): + r"""kind(ellipse self) -> ifcopenshell::geometry::taxonomy::kinds""" + return _ifcopenshell_wrapper.ellipse_kind(self) + + def calc_hash(self): + r"""calc_hash(ellipse self) -> size_t""" + return _ifcopenshell_wrapper.ellipse_calc_hash(self) + + def matrix_(self): + r"""matrix_(ellipse self) -> ifcopenshell::geometry::taxonomy::matrix4::ptr const &""" + return _ifcopenshell_wrapper.ellipse_matrix_(self) + + matrix = property(matrix_) + + + __repr__ = taxonomy_item_repr + + + def __init__(self): + r"""__init__(ellipse self) -> ellipse""" + _ifcopenshell_wrapper.ellipse_swiginit(self, _ifcopenshell_wrapper.new_ellipse()) + __swig_destroy__ = _ifcopenshell_wrapper.delete_ellipse + +# Register ellipse in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.ellipse_swigregister(ellipse) + +class bspline_curve(curve): + r"""Proxy of C++ ifcopenshell::geometry::taxonomy::bspline_curve class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def clone_(self): + r"""clone_(bspline_curve self) -> bspline_curve""" + return _ifcopenshell_wrapper.bspline_curve_clone_(self) + + def kind(self): + r"""kind(bspline_curve self) -> ifcopenshell::geometry::taxonomy::kinds""" + return _ifcopenshell_wrapper.bspline_curve_kind(self) + + def calc_hash(self): + r"""calc_hash(bspline_curve self) -> size_t""" + return _ifcopenshell_wrapper.bspline_curve_calc_hash(self) + control_points = property(_ifcopenshell_wrapper.bspline_curve_control_points_get, _ifcopenshell_wrapper.bspline_curve_control_points_set, doc=r"""control_points : std::vector<(ifcopenshell::geometry::taxonomy::point3::ptr,std::allocator<(ifcopenshell::geometry::taxonomy::point3::ptr)>)>""") + multiplicities = property(_ifcopenshell_wrapper.bspline_curve_multiplicities_get, _ifcopenshell_wrapper.bspline_curve_multiplicities_set, doc=r"""multiplicities : std::vector<(int,std::allocator<(int)>)>""") + knots = property(_ifcopenshell_wrapper.bspline_curve_knots_get, _ifcopenshell_wrapper.bspline_curve_knots_set, doc=r"""knots : std::vector<(double,std::allocator<(double)>)>""") + weights = property(_ifcopenshell_wrapper.bspline_curve_weights_get, _ifcopenshell_wrapper.bspline_curve_weights_set, doc=r"""weights : boost::optional<(std::vector<(double,std::allocator<(double)>)>)>""") + degree = property(_ifcopenshell_wrapper.bspline_curve_degree_get, _ifcopenshell_wrapper.bspline_curve_degree_set, doc=r"""degree : int""") + + __repr__ = taxonomy_item_repr + + + def __init__(self): + r"""__init__(bspline_curve self) -> bspline_curve""" + _ifcopenshell_wrapper.bspline_curve_swiginit(self, _ifcopenshell_wrapper.new_bspline_curve()) + __swig_destroy__ = _ifcopenshell_wrapper.delete_bspline_curve + +# Register bspline_curve in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.bspline_curve_swigregister(bspline_curve) + +class offset_curve(curve): + r"""Proxy of C++ ifcopenshell::geometry::taxonomy::offset_curve class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + reference = property(_ifcopenshell_wrapper.offset_curve_reference_get, _ifcopenshell_wrapper.offset_curve_reference_set, doc=r"""reference : ifcopenshell::geometry::taxonomy::direction3::ptr""") + offset = property(_ifcopenshell_wrapper.offset_curve_offset_get, _ifcopenshell_wrapper.offset_curve_offset_set, doc=r"""offset : double""") + basis = property(_ifcopenshell_wrapper.offset_curve_basis_get, _ifcopenshell_wrapper.offset_curve_basis_set, doc=r"""basis : ifcopenshell::geometry::taxonomy::item::ptr""") + + def clone_(self): + r"""clone_(offset_curve self) -> offset_curve""" + return _ifcopenshell_wrapper.offset_curve_clone_(self) + + def kind(self): + r"""kind(offset_curve self) -> ifcopenshell::geometry::taxonomy::kinds""" + return _ifcopenshell_wrapper.offset_curve_kind(self) + + def calc_hash(self): + r"""calc_hash(offset_curve self) -> size_t""" + return _ifcopenshell_wrapper.offset_curve_calc_hash(self) + + __repr__ = taxonomy_item_repr + + + def __init__(self): + r"""__init__(offset_curve self) -> offset_curve""" + _ifcopenshell_wrapper.offset_curve_swiginit(self, _ifcopenshell_wrapper.new_offset_curve()) + __swig_destroy__ = _ifcopenshell_wrapper.delete_offset_curve + +# Register offset_curve in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.offset_curve_swigregister(offset_curve) + +class trimmed_curve(geom_item): + r"""Proxy of C++ ifcopenshell::geometry::taxonomy::trimmed_curve class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + + def __init__(self, *args, **kwargs): + raise AttributeError("No constructor defined - class is abstract") + __repr__ = _swig_repr + start = property(_ifcopenshell_wrapper.trimmed_curve_start_get, _ifcopenshell_wrapper.trimmed_curve_start_set, doc=r"""start : boost::variant<(boost::blank,ifcopenshell::geometry::taxonomy::point3::ptr,double)>""") + end = property(_ifcopenshell_wrapper.trimmed_curve_end_get, _ifcopenshell_wrapper.trimmed_curve_end_set, doc=r"""end : boost::variant<(boost::blank,ifcopenshell::geometry::taxonomy::point3::ptr,double)>""") + basis = property(_ifcopenshell_wrapper.trimmed_curve_basis_get, _ifcopenshell_wrapper.trimmed_curve_basis_set, doc=r"""basis : ifcopenshell::geometry::taxonomy::item::ptr""") + curve_sense = property(_ifcopenshell_wrapper.trimmed_curve_curve_sense_get, _ifcopenshell_wrapper.trimmed_curve_curve_sense_set, doc=r"""curve_sense : boost::optional<(bool)>""") + + def reverse(self): + r"""reverse(trimmed_curve self)""" + return _ifcopenshell_wrapper.trimmed_curve_reverse(self) + __swig_destroy__ = _ifcopenshell_wrapper.delete_trimmed_curve + +# Register trimmed_curve in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.trimmed_curve_swigregister(trimmed_curve) + +class edge(trimmed_curve): + r"""Proxy of C++ ifcopenshell::geometry::taxonomy::edge class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def __init__(self, *args): + r""" + __init__(edge self) -> edge + __init__(edge self, ifcopenshell::geometry::taxonomy::point3::ptr const & a, ifcopenshell::geometry::taxonomy::point3::ptr const & b) -> edge + """ + _ifcopenshell_wrapper.edge_swiginit(self, _ifcopenshell_wrapper.new_edge(*args)) + + def clone_(self): + r"""clone_(edge self) -> edge""" + return _ifcopenshell_wrapper.edge_clone_(self) + + def kind(self): + r"""kind(edge self) -> ifcopenshell::geometry::taxonomy::kinds""" + return _ifcopenshell_wrapper.edge_kind(self) + + def calc_hash(self): + r"""calc_hash(edge self) -> size_t""" + return _ifcopenshell_wrapper.edge_calc_hash(self) + + __repr__ = taxonomy_item_repr + + __swig_destroy__ = _ifcopenshell_wrapper.delete_edge + +# Register edge in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.edge_swigregister(edge) + +class collection(object): + r"""Proxy of C++ ifcopenshell::geometry::taxonomy::collection class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def clone_(self): + r"""clone_(collection self) -> collection""" + return _ifcopenshell_wrapper.collection_clone_(self) + + def kind(self): + r"""kind(collection self) -> ifcopenshell::geometry::taxonomy::kinds""" + return _ifcopenshell_wrapper.collection_kind(self) + + def calc_hash(self): + r"""calc_hash(collection self) -> size_t""" + return _ifcopenshell_wrapper.collection_calc_hash(self) + + def children_(self): + r"""children_(collection self) -> std::vector< ifcopenshell::geometry::taxonomy::geom_item::ptr,std::allocator< ifcopenshell::geometry::taxonomy::geom_item::ptr > > const &""" + return _ifcopenshell_wrapper.collection_children_(self) + + def __getitem__(self, index): + r"""__getitem__(collection self, int index) -> ifcopenshell::geometry::taxonomy::geom_item::ptr const &""" + return _ifcopenshell_wrapper.collection___getitem__(self, index) + + children = property(children_) + def __iter__(self): + return iter(self.children) + + + def matrix_(self): + r"""matrix_(collection self) -> ifcopenshell::geometry::taxonomy::matrix4::ptr const &""" + return _ifcopenshell_wrapper.collection_matrix_(self) + + matrix = property(matrix_) + + + __repr__ = taxonomy_item_repr + + + def __init__(self): + r"""__init__(collection self) -> collection""" + _ifcopenshell_wrapper.collection_swiginit(self, _ifcopenshell_wrapper.new_collection()) + __swig_destroy__ = _ifcopenshell_wrapper.delete_collection + +# Register collection in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.collection_swigregister(collection) + +class loop(object): + r"""Proxy of C++ ifcopenshell::geometry::taxonomy::loop class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + external = property(_ifcopenshell_wrapper.loop_external_get, _ifcopenshell_wrapper.loop_external_set, doc=r"""external : boost::optional<(bool)>""") + closed = property(_ifcopenshell_wrapper.loop_closed_get, _ifcopenshell_wrapper.loop_closed_set, doc=r"""closed : boost::optional<(bool)>""") + fi = property(_ifcopenshell_wrapper.loop_fi_get, _ifcopenshell_wrapper.loop_fi_set, doc=r"""fi : boost::optional<(ifcopenshell::geometry::taxonomy::function_item::ptr)>""") + + def is_polyhedron(self): + r"""is_polyhedron(loop self) -> bool""" + return _ifcopenshell_wrapper.loop_is_polyhedron(self) + + def calculate_linear_edge_curves(self): + r"""calculate_linear_edge_curves(loop self)""" + return _ifcopenshell_wrapper.loop_calculate_linear_edge_curves(self) + + def remove_linear_edge_curves(self): + r"""remove_linear_edge_curves(loop self)""" + return _ifcopenshell_wrapper.loop_remove_linear_edge_curves(self) + + def clone_(self): + r"""clone_(loop self) -> loop""" + return _ifcopenshell_wrapper.loop_clone_(self) + + def kind(self): + r"""kind(loop self) -> ifcopenshell::geometry::taxonomy::kinds""" + return _ifcopenshell_wrapper.loop_kind(self) + + def calc_hash(self): + r"""calc_hash(loop self) -> size_t""" + return _ifcopenshell_wrapper.loop_calc_hash(self) + + def centroid(self): + r"""centroid(loop self) -> ifcopenshell::geometry::taxonomy::point3::ptr""" + return _ifcopenshell_wrapper.loop_centroid(self) + + def children_(self): + r"""children_(loop self) -> std::vector< ifcopenshell::geometry::taxonomy::edge::ptr,std::allocator< ifcopenshell::geometry::taxonomy::edge::ptr > > const &""" + return _ifcopenshell_wrapper.loop_children_(self) + + def __getitem__(self, index): + r"""__getitem__(loop self, int index) -> ifcopenshell::geometry::taxonomy::edge::ptr const &""" + return _ifcopenshell_wrapper.loop___getitem__(self, index) + + children = property(children_) + def __iter__(self): + return iter(self.children) + + + __repr__ = taxonomy_item_repr + + + def __init__(self): + r"""__init__(loop self) -> loop""" + _ifcopenshell_wrapper.loop_swiginit(self, _ifcopenshell_wrapper.new_loop()) + __swig_destroy__ = _ifcopenshell_wrapper.delete_loop + +# Register loop in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.loop_swigregister(loop) + +class face(object): + r"""Proxy of C++ ifcopenshell::geometry::taxonomy::face class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + basis = property(_ifcopenshell_wrapper.face_basis_get, _ifcopenshell_wrapper.face_basis_set, doc=r"""basis : ifcopenshell::geometry::taxonomy::item::ptr""") + + def clone_(self): + r"""clone_(face self) -> face""" + return _ifcopenshell_wrapper.face_clone_(self) + + def kind(self): + r"""kind(face self) -> ifcopenshell::geometry::taxonomy::kinds""" + return _ifcopenshell_wrapper.face_kind(self) + + def print_impl(self, o, indent): + r"""print_impl(face self, std::ostream & o, int indent)""" + return _ifcopenshell_wrapper.face_print_impl(self, o, indent) + + def calc_hash(self): + r"""calc_hash(face self) -> size_t""" + return _ifcopenshell_wrapper.face_calc_hash(self) + + def children_(self): + r"""children_(face self) -> std::vector< ifcopenshell::geometry::taxonomy::loop::ptr,std::allocator< ifcopenshell::geometry::taxonomy::loop::ptr > > const &""" + return _ifcopenshell_wrapper.face_children_(self) + + def __getitem__(self, index): + r"""__getitem__(face self, int index) -> ifcopenshell::geometry::taxonomy::loop::ptr const &""" + return _ifcopenshell_wrapper.face___getitem__(self, index) + + children = property(children_) + def __iter__(self): + return iter(self.children) + + + def matrix_(self): + r"""matrix_(face self) -> ifcopenshell::geometry::taxonomy::matrix4::ptr const &""" + return _ifcopenshell_wrapper.face_matrix_(self) + + matrix = property(matrix_) + + + __repr__ = taxonomy_item_repr + + + def __init__(self): + r"""__init__(face self) -> face""" + _ifcopenshell_wrapper.face_swiginit(self, _ifcopenshell_wrapper.new_face()) + __swig_destroy__ = _ifcopenshell_wrapper.delete_face + +# Register face in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.face_swigregister(face) + +class shell(object): + r"""Proxy of C++ ifcopenshell::geometry::taxonomy::shell class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + closed = property(_ifcopenshell_wrapper.shell_closed_get, _ifcopenshell_wrapper.shell_closed_set, doc=r"""closed : boost::optional<(bool)>""") + + def print_impl(self, o, indent): + r"""print_impl(shell self, std::ostream & o, int indent)""" + return _ifcopenshell_wrapper.shell_print_impl(self, o, indent) + + def clone_(self): + r"""clone_(shell self) -> shell""" + return _ifcopenshell_wrapper.shell_clone_(self) + + def kind(self): + r"""kind(shell self) -> ifcopenshell::geometry::taxonomy::kinds""" + return _ifcopenshell_wrapper.shell_kind(self) + + def calc_hash(self): + r"""calc_hash(shell self) -> size_t""" + return _ifcopenshell_wrapper.shell_calc_hash(self) + + def centroid(self): + r"""centroid(shell self) -> ifcopenshell::geometry::taxonomy::point3::ptr""" + return _ifcopenshell_wrapper.shell_centroid(self) + + def children_(self): + r"""children_(shell self) -> std::vector< ifcopenshell::geometry::taxonomy::face::ptr,std::allocator< ifcopenshell::geometry::taxonomy::face::ptr > > const &""" + return _ifcopenshell_wrapper.shell_children_(self) + + def __getitem__(self, index): + r"""__getitem__(shell self, int index) -> ifcopenshell::geometry::taxonomy::face::ptr const &""" + return _ifcopenshell_wrapper.shell___getitem__(self, index) + + children = property(children_) + def __iter__(self): + return iter(self.children) + + + __repr__ = taxonomy_item_repr + + + def __init__(self): + r"""__init__(shell self) -> shell""" + _ifcopenshell_wrapper.shell_swiginit(self, _ifcopenshell_wrapper.new_shell()) + __swig_destroy__ = _ifcopenshell_wrapper.delete_shell + +# Register shell in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.shell_swigregister(shell) + +class solid(object): + r"""Proxy of C++ ifcopenshell::geometry::taxonomy::solid class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def clone_(self): + r"""clone_(solid self) -> solid""" + return _ifcopenshell_wrapper.solid_clone_(self) + + def kind(self): + r"""kind(solid self) -> ifcopenshell::geometry::taxonomy::kinds""" + return _ifcopenshell_wrapper.solid_kind(self) + + def calc_hash(self): + r"""calc_hash(solid self) -> size_t""" + return _ifcopenshell_wrapper.solid_calc_hash(self) + + def children_(self): + r"""children_(solid self) -> std::vector< ifcopenshell::geometry::taxonomy::shell::ptr,std::allocator< ifcopenshell::geometry::taxonomy::shell::ptr > > const &""" + return _ifcopenshell_wrapper.solid_children_(self) + + def __getitem__(self, index): + r"""__getitem__(solid self, int index) -> ifcopenshell::geometry::taxonomy::shell::ptr const &""" + return _ifcopenshell_wrapper.solid___getitem__(self, index) + + children = property(children_) + def __iter__(self): + return iter(self.children) + + + def matrix_(self): + r"""matrix_(solid self) -> ifcopenshell::geometry::taxonomy::matrix4::ptr const &""" + return _ifcopenshell_wrapper.solid_matrix_(self) + + matrix = property(matrix_) + + + __repr__ = taxonomy_item_repr + + + def __init__(self): + r"""__init__(solid self) -> solid""" + _ifcopenshell_wrapper.solid_swiginit(self, _ifcopenshell_wrapper.new_solid()) + __swig_destroy__ = _ifcopenshell_wrapper.delete_solid + +# Register solid in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.solid_swigregister(solid) + +class loft(object): + r"""Proxy of C++ ifcopenshell::geometry::taxonomy::loft class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + axis = property(_ifcopenshell_wrapper.loft_axis_get, _ifcopenshell_wrapper.loft_axis_set, doc=r"""axis : ifcopenshell::geometry::taxonomy::item::ptr""") + + def clone_(self): + r"""clone_(loft self) -> loft""" + return _ifcopenshell_wrapper.loft_clone_(self) + + def kind(self): + r"""kind(loft self) -> ifcopenshell::geometry::taxonomy::kinds""" + return _ifcopenshell_wrapper.loft_kind(self) + + def print_impl(self, o, indent): + r"""print_impl(loft self, std::ostream & o, int indent)""" + return _ifcopenshell_wrapper.loft_print_impl(self, o, indent) + + def calc_hash(self): + r"""calc_hash(loft self) -> size_t""" + return _ifcopenshell_wrapper.loft_calc_hash(self) + + def children_(self): + r"""children_(loft self) -> std::vector< ifcopenshell::geometry::taxonomy::geom_item::ptr,std::allocator< ifcopenshell::geometry::taxonomy::geom_item::ptr > > const &""" + return _ifcopenshell_wrapper.loft_children_(self) + + def __getitem__(self, index): + r"""__getitem__(loft self, int index) -> ifcopenshell::geometry::taxonomy::geom_item::ptr const &""" + return _ifcopenshell_wrapper.loft___getitem__(self, index) + + children = property(children_) + def __iter__(self): + return iter(self.children) + + + __repr__ = taxonomy_item_repr + + + def __init__(self): + r"""__init__(loft self) -> loft""" + _ifcopenshell_wrapper.loft_swiginit(self, _ifcopenshell_wrapper.new_loft()) + __swig_destroy__ = _ifcopenshell_wrapper.delete_loft + +# Register loft in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.loft_swigregister(loft) + +class surface(geom_item): + r"""Proxy of C++ ifcopenshell::geometry::taxonomy::surface class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + + def __init__(self, *args, **kwargs): + raise AttributeError("No constructor defined - class is abstract") + __repr__ = _swig_repr + __swig_destroy__ = _ifcopenshell_wrapper.delete_surface + +# Register surface in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.surface_swigregister(surface) + +class plane(surface): + r"""Proxy of C++ ifcopenshell::geometry::taxonomy::plane class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def clone_(self): + r"""clone_(plane self) -> plane""" + return _ifcopenshell_wrapper.plane_clone_(self) + + def kind(self): + r"""kind(plane self) -> ifcopenshell::geometry::taxonomy::kinds""" + return _ifcopenshell_wrapper.plane_kind(self) + + def calc_hash(self): + r"""calc_hash(plane self) -> size_t""" + return _ifcopenshell_wrapper.plane_calc_hash(self) + + def matrix_(self): + r"""matrix_(plane self) -> ifcopenshell::geometry::taxonomy::matrix4::ptr const &""" + return _ifcopenshell_wrapper.plane_matrix_(self) + + matrix = property(matrix_) + + + __repr__ = taxonomy_item_repr + + + def __init__(self): + r"""__init__(plane self) -> plane""" + _ifcopenshell_wrapper.plane_swiginit(self, _ifcopenshell_wrapper.new_plane()) + __swig_destroy__ = _ifcopenshell_wrapper.delete_plane + +# Register plane in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.plane_swigregister(plane) + +class cylinder(surface): + r"""Proxy of C++ ifcopenshell::geometry::taxonomy::cylinder class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + radius = property(_ifcopenshell_wrapper.cylinder_radius_get, _ifcopenshell_wrapper.cylinder_radius_set, doc=r"""radius : double""") + + def clone_(self): + r"""clone_(cylinder self) -> cylinder""" + return _ifcopenshell_wrapper.cylinder_clone_(self) + + def kind(self): + r"""kind(cylinder self) -> ifcopenshell::geometry::taxonomy::kinds""" + return _ifcopenshell_wrapper.cylinder_kind(self) + + def calc_hash(self): + r"""calc_hash(cylinder self) -> size_t""" + return _ifcopenshell_wrapper.cylinder_calc_hash(self) + + def matrix_(self): + r"""matrix_(cylinder self) -> ifcopenshell::geometry::taxonomy::matrix4::ptr const &""" + return _ifcopenshell_wrapper.cylinder_matrix_(self) + + matrix = property(matrix_) + + + __repr__ = taxonomy_item_repr + + + def __init__(self): + r"""__init__(cylinder self) -> cylinder""" + _ifcopenshell_wrapper.cylinder_swiginit(self, _ifcopenshell_wrapper.new_cylinder()) + __swig_destroy__ = _ifcopenshell_wrapper.delete_cylinder + +# Register cylinder in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.cylinder_swigregister(cylinder) + +class sphere(surface): + r"""Proxy of C++ ifcopenshell::geometry::taxonomy::sphere class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + radius = property(_ifcopenshell_wrapper.sphere_radius_get, _ifcopenshell_wrapper.sphere_radius_set, doc=r"""radius : double""") + + def clone_(self): + r"""clone_(sphere self) -> sphere""" + return _ifcopenshell_wrapper.sphere_clone_(self) + + def kind(self): + r"""kind(sphere self) -> ifcopenshell::geometry::taxonomy::kinds""" + return _ifcopenshell_wrapper.sphere_kind(self) + + def calc_hash(self): + r"""calc_hash(sphere self) -> size_t""" + return _ifcopenshell_wrapper.sphere_calc_hash(self) + + def matrix_(self): + r"""matrix_(sphere self) -> ifcopenshell::geometry::taxonomy::matrix4::ptr const &""" + return _ifcopenshell_wrapper.sphere_matrix_(self) + + matrix = property(matrix_) + + + __repr__ = taxonomy_item_repr + + + def __init__(self): + r"""__init__(sphere self) -> sphere""" + _ifcopenshell_wrapper.sphere_swiginit(self, _ifcopenshell_wrapper.new_sphere()) + __swig_destroy__ = _ifcopenshell_wrapper.delete_sphere + +# Register sphere in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.sphere_swigregister(sphere) + +class torus(surface): + r"""Proxy of C++ ifcopenshell::geometry::taxonomy::torus class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + radius1 = property(_ifcopenshell_wrapper.torus_radius1_get, _ifcopenshell_wrapper.torus_radius1_set, doc=r"""radius1 : double""") + radius2 = property(_ifcopenshell_wrapper.torus_radius2_get, _ifcopenshell_wrapper.torus_radius2_set, doc=r"""radius2 : double""") + + def clone_(self): + r"""clone_(torus self) -> torus""" + return _ifcopenshell_wrapper.torus_clone_(self) + + def kind(self): + r"""kind(torus self) -> ifcopenshell::geometry::taxonomy::kinds""" + return _ifcopenshell_wrapper.torus_kind(self) + + def calc_hash(self): + r"""calc_hash(torus self) -> size_t""" + return _ifcopenshell_wrapper.torus_calc_hash(self) + + def matrix_(self): + r"""matrix_(torus self) -> ifcopenshell::geometry::taxonomy::matrix4::ptr const &""" + return _ifcopenshell_wrapper.torus_matrix_(self) + + matrix = property(matrix_) + + + __repr__ = taxonomy_item_repr + + + def __init__(self): + r"""__init__(torus self) -> torus""" + _ifcopenshell_wrapper.torus_swiginit(self, _ifcopenshell_wrapper.new_torus()) + __swig_destroy__ = _ifcopenshell_wrapper.delete_torus + +# Register torus in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.torus_swigregister(torus) + +class bspline_surface(surface): + r"""Proxy of C++ ifcopenshell::geometry::taxonomy::bspline_surface class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def clone_(self): + r"""clone_(bspline_surface self) -> bspline_surface""" + return _ifcopenshell_wrapper.bspline_surface_clone_(self) + + def kind(self): + r"""kind(bspline_surface self) -> ifcopenshell::geometry::taxonomy::kinds""" + return _ifcopenshell_wrapper.bspline_surface_kind(self) + + def calc_hash(self): + r"""calc_hash(bspline_surface self) -> size_t""" + return _ifcopenshell_wrapper.bspline_surface_calc_hash(self) + control_points = property(_ifcopenshell_wrapper.bspline_surface_control_points_get, _ifcopenshell_wrapper.bspline_surface_control_points_set, doc=r"""control_points : std::vector<(std::vector<(ifcopenshell::geometry::taxonomy::point3::ptr,std::allocator<(ifcopenshell::geometry::taxonomy::point3::ptr)>)>,std::allocator<(std::vector<(ifcopenshell::geometry::taxonomy::point3::ptr,std::allocator<(ifcopenshell::geometry::taxonomy::point3::ptr)>)>)>)>""") + multiplicities = property(_ifcopenshell_wrapper.bspline_surface_multiplicities_get, _ifcopenshell_wrapper.bspline_surface_multiplicities_set, doc=r"""multiplicities : std::array<(std::vector<(int,std::allocator<(int)>)>,2)>""") + knots = property(_ifcopenshell_wrapper.bspline_surface_knots_get, _ifcopenshell_wrapper.bspline_surface_knots_set, doc=r"""knots : std::array<(std::vector<(double,std::allocator<(double)>)>,2)>""") + weights = property(_ifcopenshell_wrapper.bspline_surface_weights_get, _ifcopenshell_wrapper.bspline_surface_weights_set, doc=r"""weights : boost::optional<(std::vector<(std::vector<(double,std::allocator<(double)>)>,std::allocator<(std::vector<(double,std::allocator<(double)>)>)>)>)>""") + degree = property(_ifcopenshell_wrapper.bspline_surface_degree_get, _ifcopenshell_wrapper.bspline_surface_degree_set, doc=r"""degree : std::array<(int,2)>""") + + __repr__ = taxonomy_item_repr + + + def __init__(self): + r"""__init__(bspline_surface self) -> bspline_surface""" + _ifcopenshell_wrapper.bspline_surface_swiginit(self, _ifcopenshell_wrapper.new_bspline_surface()) + __swig_destroy__ = _ifcopenshell_wrapper.delete_bspline_surface + +# Register bspline_surface in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.bspline_surface_swigregister(bspline_surface) + +class sweep(geom_item): + r"""Proxy of C++ ifcopenshell::geometry::taxonomy::sweep class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + + def __init__(self, *args, **kwargs): + raise AttributeError("No constructor defined - class is abstract") + __repr__ = _swig_repr + basis = property(_ifcopenshell_wrapper.sweep_basis_get, _ifcopenshell_wrapper.sweep_basis_set, doc=r"""basis : ifcopenshell::geometry::taxonomy::item::ptr""") + __swig_destroy__ = _ifcopenshell_wrapper.delete_sweep + +# Register sweep in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.sweep_swigregister(sweep) + +class extrusion(sweep): + r"""Proxy of C++ ifcopenshell::geometry::taxonomy::extrusion class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + direction = property(_ifcopenshell_wrapper.extrusion_direction_get, _ifcopenshell_wrapper.extrusion_direction_set, doc=r"""direction : ifcopenshell::geometry::taxonomy::direction3::ptr""") + depth = property(_ifcopenshell_wrapper.extrusion_depth_get, _ifcopenshell_wrapper.extrusion_depth_set, doc=r"""depth : double""") + + def clone_(self): + r"""clone_(extrusion self) -> extrusion""" + return _ifcopenshell_wrapper.extrusion_clone_(self) + + def kind(self): + r"""kind(extrusion self) -> ifcopenshell::geometry::taxonomy::kinds""" + return _ifcopenshell_wrapper.extrusion_kind(self) + + def __init__(self, m, basis, dir, d): + r"""__init__(extrusion self, ifcopenshell::geometry::taxonomy::matrix4::ptr m, ifcopenshell::geometry::taxonomy::item::ptr basis, ifcopenshell::geometry::taxonomy::direction3::ptr dir, double d) -> extrusion""" + _ifcopenshell_wrapper.extrusion_swiginit(self, _ifcopenshell_wrapper.new_extrusion(m, basis, dir, d)) + + def calc_hash(self): + r"""calc_hash(extrusion self) -> size_t""" + return _ifcopenshell_wrapper.extrusion_calc_hash(self) + + def matrix_(self): + r"""matrix_(extrusion self) -> ifcopenshell::geometry::taxonomy::matrix4::ptr const &""" + return _ifcopenshell_wrapper.extrusion_matrix_(self) + + matrix = property(matrix_) + + + __repr__ = taxonomy_item_repr + + __swig_destroy__ = _ifcopenshell_wrapper.delete_extrusion + +# Register extrusion in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.extrusion_swigregister(extrusion) + +class revolve(sweep): + r"""Proxy of C++ ifcopenshell::geometry::taxonomy::revolve class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + axis_origin = property(_ifcopenshell_wrapper.revolve_axis_origin_get, _ifcopenshell_wrapper.revolve_axis_origin_set, doc=r"""axis_origin : ifcopenshell::geometry::taxonomy::point3::ptr""") + direction = property(_ifcopenshell_wrapper.revolve_direction_get, _ifcopenshell_wrapper.revolve_direction_set, doc=r"""direction : ifcopenshell::geometry::taxonomy::direction3::ptr""") + angle = property(_ifcopenshell_wrapper.revolve_angle_get, _ifcopenshell_wrapper.revolve_angle_set, doc=r"""angle : boost::optional<(double)>""") + + def clone_(self): + r"""clone_(revolve self) -> revolve""" + return _ifcopenshell_wrapper.revolve_clone_(self) + + def kind(self): + r"""kind(revolve self) -> ifcopenshell::geometry::taxonomy::kinds""" + return _ifcopenshell_wrapper.revolve_kind(self) + + def __init__(self, m, basis, pnt, dir, a): + r"""__init__(revolve self, ifcopenshell::geometry::taxonomy::matrix4::ptr m, ifcopenshell::geometry::taxonomy::item::ptr basis, ifcopenshell::geometry::taxonomy::point3::ptr pnt, ifcopenshell::geometry::taxonomy::direction3::ptr dir, boost::optional< double > const & a) -> revolve""" + _ifcopenshell_wrapper.revolve_swiginit(self, _ifcopenshell_wrapper.new_revolve(m, basis, pnt, dir, a)) + + def calc_hash(self): + r"""calc_hash(revolve self) -> size_t""" + return _ifcopenshell_wrapper.revolve_calc_hash(self) + + def matrix_(self): + r"""matrix_(revolve self) -> ifcopenshell::geometry::taxonomy::matrix4::ptr const &""" + return _ifcopenshell_wrapper.revolve_matrix_(self) + + matrix = property(matrix_) + + + __repr__ = taxonomy_item_repr + + __swig_destroy__ = _ifcopenshell_wrapper.delete_revolve + +# Register revolve in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.revolve_swigregister(revolve) + +class sweep_along_curve(sweep): + r"""Proxy of C++ ifcopenshell::geometry::taxonomy::sweep_along_curve class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + surface = property(_ifcopenshell_wrapper.sweep_along_curve_surface_get, _ifcopenshell_wrapper.sweep_along_curve_surface_set, doc=r"""surface : ifcopenshell::geometry::taxonomy::item::ptr""") + curve = property(_ifcopenshell_wrapper.sweep_along_curve_curve_get, _ifcopenshell_wrapper.sweep_along_curve_curve_set, doc=r"""curve : ifcopenshell::geometry::taxonomy::item::ptr""") + direction = property(_ifcopenshell_wrapper.sweep_along_curve_direction_get, _ifcopenshell_wrapper.sweep_along_curve_direction_set, doc=r"""direction : ifcopenshell::geometry::taxonomy::direction3::ptr""") + + def clone_(self): + r"""clone_(sweep_along_curve self) -> sweep_along_curve""" + return _ifcopenshell_wrapper.sweep_along_curve_clone_(self) + + def kind(self): + r"""kind(sweep_along_curve self) -> ifcopenshell::geometry::taxonomy::kinds""" + return _ifcopenshell_wrapper.sweep_along_curve_kind(self) + + def __init__(self, *args): + r""" + __init__(sweep_along_curve self, ifcopenshell::geometry::taxonomy::matrix4::ptr m, ifcopenshell::geometry::taxonomy::face::ptr basis, ifcopenshell::geometry::taxonomy::item::ptr surf, ifcopenshell::geometry::taxonomy::item::ptr crv) -> sweep_along_curve + __init__(sweep_along_curve self, ifcopenshell::geometry::taxonomy::matrix4::ptr m, ifcopenshell::geometry::taxonomy::face::ptr profile, ifcopenshell::geometry::taxonomy::item::ptr directrix, ifcopenshell::geometry::taxonomy::direction3::ptr ref) -> sweep_along_curve + """ + _ifcopenshell_wrapper.sweep_along_curve_swiginit(self, _ifcopenshell_wrapper.new_sweep_along_curve(*args)) + + def calc_hash(self): + r"""calc_hash(sweep_along_curve self) -> size_t""" + return _ifcopenshell_wrapper.sweep_along_curve_calc_hash(self) + + __repr__ = taxonomy_item_repr + + __swig_destroy__ = _ifcopenshell_wrapper.delete_sweep_along_curve + +# Register sweep_along_curve in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.sweep_along_curve_swigregister(sweep_along_curve) + +class node(item): + r"""Proxy of C++ ifcopenshell::geometry::taxonomy::node class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def clone_(self): + r"""clone_(node self) -> node""" + return _ifcopenshell_wrapper.node_clone_(self) + + def kind(self): + r"""kind(node self) -> ifcopenshell::geometry::taxonomy::kinds""" + return _ifcopenshell_wrapper.node_kind(self) + + def calc_hash(self): + r"""calc_hash(node self) -> size_t""" + return _ifcopenshell_wrapper.node_calc_hash(self) + + __repr__ = taxonomy_item_repr + + + def __init__(self): + r"""__init__(node self) -> node""" + _ifcopenshell_wrapper.node_swiginit(self, _ifcopenshell_wrapper.new_node()) + __swig_destroy__ = _ifcopenshell_wrapper.delete_node + +# Register node in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.node_swigregister(node) + +class boolean_result(object): + r"""Proxy of C++ ifcopenshell::geometry::taxonomy::boolean_result class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + UNION = _ifcopenshell_wrapper.boolean_result_UNION + + SUBTRACTION = _ifcopenshell_wrapper.boolean_result_SUBTRACTION + + INTERSECTION = _ifcopenshell_wrapper.boolean_result_INTERSECTION + + + def clone_(self): + r"""clone_(boolean_result self) -> boolean_result""" + return _ifcopenshell_wrapper.boolean_result_clone_(self) + + def kind(self): + r"""kind(boolean_result self) -> ifcopenshell::geometry::taxonomy::kinds""" + return _ifcopenshell_wrapper.boolean_result_kind(self) + operation = property(_ifcopenshell_wrapper.boolean_result_operation_get, _ifcopenshell_wrapper.boolean_result_operation_set, doc=r"""operation : ifcopenshell::geometry::taxonomy::boolean_result::operation_t""") + + @staticmethod + def operation_str(op): + r"""operation_str(ifcopenshell::geometry::taxonomy::boolean_result::operation_t op) -> std::string const &""" + return _ifcopenshell_wrapper.boolean_result_operation_str(op) + + def calc_hash(self): + r"""calc_hash(boolean_result self) -> size_t""" + return _ifcopenshell_wrapper.boolean_result_calc_hash(self) + + def children_(self): + r"""children_(boolean_result self) -> std::vector< ifcopenshell::geometry::taxonomy::geom_item::ptr,std::allocator< ifcopenshell::geometry::taxonomy::geom_item::ptr > > const &""" + return _ifcopenshell_wrapper.boolean_result_children_(self) + + def __getitem__(self, index): + r"""__getitem__(boolean_result self, int index) -> ifcopenshell::geometry::taxonomy::geom_item::ptr const &""" + return _ifcopenshell_wrapper.boolean_result___getitem__(self, index) + + children = property(children_) + def __iter__(self): + return iter(self.children) + + + __repr__ = taxonomy_item_repr + + + def __init__(self): + r"""__init__(boolean_result self) -> boolean_result""" + _ifcopenshell_wrapper.boolean_result_swiginit(self, _ifcopenshell_wrapper.new_boolean_result()) + __swig_destroy__ = _ifcopenshell_wrapper.delete_boolean_result + +# Register boolean_result in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.boolean_result_swigregister(boolean_result) + +def boolean_result_operation_str(op): + r"""boolean_result_operation_str(ifcopenshell::geometry::taxonomy::boolean_result::operation_t op) -> std::string const &""" + return _ifcopenshell_wrapper.boolean_result_operation_str(op) + +class type_by_kind(object): + r"""Proxy of C++ ifcopenshell::geometry::taxonomy::type_by_kind class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + max = _ifcopenshell_wrapper.type_by_kind_max + + + def __init__(self): + r"""__init__(type_by_kind self) -> type_by_kind""" + _ifcopenshell_wrapper.type_by_kind_swiginit(self, _ifcopenshell_wrapper.new_type_by_kind()) + __swig_destroy__ = _ifcopenshell_wrapper.delete_type_by_kind + +# Register type_by_kind in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.type_by_kind_swigregister(type_by_kind) + + +def flatten(deep): + r"""flatten(ifcopenshell::geometry::taxonomy::collection::ptr const & deep) -> ifcopenshell::geometry::taxonomy::collection::ptr""" + return _ifcopenshell_wrapper.flatten(deep) + +def create_box(*args): + r""" + create_box(double dx, double dy, double dz) -> ifcopenshell::geometry::taxonomy::solid::ptr + create_box(double x, double y, double z, double dx, double dy, double dz) -> ifcopenshell::geometry::taxonomy::solid::ptr + """ + return _ifcopenshell_wrapper.create_box(*args) +ATPATH = _ifcopenshell_wrapper.ATPATH + +ATSTART = _ifcopenshell_wrapper.ATSTART + +ATEND = _ifcopenshell_wrapper.ATEND + +NOTDEFINED = _ifcopenshell_wrapper.NOTDEFINED + + +def helmert_curve_point(A0, A1, A2, s): + r"""helmert_curve_point(double A0, double A1, double A2, double s) -> std::vector< double,std::allocator< double > >""" + return _ifcopenshell_wrapper.helmert_curve_point(A0, A1, A2, s) + +def convert_loop_to_function_item(loop): + r"""convert_loop_to_function_item(ifcopenshell::geometry::taxonomy::loop::ptr loop) -> ifcopenshell::geometry::taxonomy::function_item::ptr""" + return _ifcopenshell_wrapper.convert_loop_to_function_item(loop) +class fn_evaluator(object): + r"""Proxy of C++ ifcopenshell::geometry::fn_evaluator class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + + def __init__(self, *args, **kwargs): + raise AttributeError("No constructor defined - class is abstract") + __repr__ = _swig_repr + __swig_destroy__ = _ifcopenshell_wrapper.delete_fn_evaluator + + def clone(self): + r"""clone(fn_evaluator self) -> fn_evaluator""" + return _ifcopenshell_wrapper.fn_evaluator_clone(self) + + def evaluate(self, u): + r"""evaluate(fn_evaluator self, double u) -> Eigen::Matrix4d""" + return _ifcopenshell_wrapper.fn_evaluator_evaluate(self, u) + + def start(self): + r"""start(fn_evaluator self) -> double""" + return _ifcopenshell_wrapper.fn_evaluator_start(self) + + def end(self): + r"""end(fn_evaluator self) -> double""" + return _ifcopenshell_wrapper.fn_evaluator_end(self) + + def length(self): + r"""length(fn_evaluator self) -> double""" + return _ifcopenshell_wrapper.fn_evaluator_length(self) + settings_ = property(_ifcopenshell_wrapper.fn_evaluator_settings__get, _ifcopenshell_wrapper.fn_evaluator_settings__set, doc=r"""settings_ : ifcopenshell::geometry::Settings""") + +# Register fn_evaluator in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.fn_evaluator_swigregister(fn_evaluator) + +class function_item_evaluator(object): + r"""Proxy of C++ ifcopenshell::geometry::function_item_evaluator class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def __init__(self, *args): + r""" + __init__(function_item_evaluator self, Settings settings, ifcopenshell::geometry::taxonomy::function_item::const_ptr fn) -> function_item_evaluator + __init__(function_item_evaluator self, function_item_evaluator other) -> function_item_evaluator + """ + _ifcopenshell_wrapper.function_item_evaluator_swiginit(self, _ifcopenshell_wrapper.new_function_item_evaluator(*args)) + __swig_destroy__ = _ifcopenshell_wrapper.delete_function_item_evaluator + + def evaluation_points(self, *args): + r""" + evaluation_points(function_item_evaluator self) -> std::vector< double,std::allocator< double > > + evaluation_points(function_item_evaluator self, double ustart, double uend, unsigned int nsteps) -> std::vector< double,std::allocator< double > > + """ + return _ifcopenshell_wrapper.function_item_evaluator_evaluation_points(self, *args) + + def evaluate(self, *args): + r""" + evaluate(function_item_evaluator self) -> ifcopenshell::geometry::taxonomy::item::ptr + evaluate(function_item_evaluator self, double ustart, double uend, unsigned int nsteps) -> ifcopenshell::geometry::taxonomy::item::ptr + evaluate(function_item_evaluator self, double u) -> Eigen::Matrix4d + """ + return _ifcopenshell_wrapper.function_item_evaluator_evaluate(self, *args) + +# Register function_item_evaluator in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.function_item_evaluator_swigregister(function_item_evaluator) + +class horizontal_plan_at_element(object): + r"""Proxy of C++ horizontal_plan_at_element class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def __init__(self): + r"""__init__(horizontal_plan_at_element self) -> horizontal_plan_at_element""" + _ifcopenshell_wrapper.horizontal_plan_at_element_swiginit(self, _ifcopenshell_wrapper.new_horizontal_plan_at_element()) + __swig_destroy__ = _ifcopenshell_wrapper.delete_horizontal_plan_at_element + +# Register horizontal_plan_at_element in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.horizontal_plan_at_element_swigregister(horizontal_plan_at_element) + +class drawing_meta(object): + r"""Proxy of C++ drawing_meta class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + pln_3d = property(_ifcopenshell_wrapper.drawing_meta_pln_3d_get, _ifcopenshell_wrapper.drawing_meta_pln_3d_set, doc=r"""pln_3d : gp_Pln""") + matrix_3 = property(_ifcopenshell_wrapper.drawing_meta_matrix_3_get, _ifcopenshell_wrapper.drawing_meta_matrix_3_set, doc=r"""matrix_3 : std::array<(std::array<(double,3)>,3)>""") + + def __init__(self): + r"""__init__(drawing_meta self) -> drawing_meta""" + _ifcopenshell_wrapper.drawing_meta_swiginit(self, _ifcopenshell_wrapper.new_drawing_meta()) + __swig_destroy__ = _ifcopenshell_wrapper.delete_drawing_meta + +# Register drawing_meta in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.drawing_meta_swigregister(drawing_meta) + +ON_SLABS_AT_FLOORPLANS = _ifcopenshell_wrapper.ON_SLABS_AT_FLOORPLANS + +ON_SLABS_AND_WALLS = _ifcopenshell_wrapper.ON_SLABS_AND_WALLS + +ALWAYS = _ifcopenshell_wrapper.ALWAYS + +class SvgSerializer(WriteOnlyGeometrySerializer): + r"""Proxy of C++ SvgSerializer class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + SH_NONE = _ifcopenshell_wrapper.SvgSerializer_SH_NONE + + SH_FULL = _ifcopenshell_wrapper.SvgSerializer_SH_FULL + + SH_LEFT = _ifcopenshell_wrapper.SvgSerializer_SH_LEFT + + + def __init__(self, out_filename, geometry_settings, settings): + r"""__init__(SvgSerializer self, buffer out_filename, Settings geometry_settings, SerializerSettings settings) -> SvgSerializer""" + _ifcopenshell_wrapper.SvgSerializer_swiginit(self, _ifcopenshell_wrapper.new_SvgSerializer(out_filename, geometry_settings, settings)) + + def addXCoordinate(self, fi): + r"""addXCoordinate(SvgSerializer self, boost::shared_ptr< util::string_buffer::float_item > const & fi)""" + return _ifcopenshell_wrapper.SvgSerializer_addXCoordinate(self, fi) + + def addYCoordinate(self, fi): + r"""addYCoordinate(SvgSerializer self, boost::shared_ptr< util::string_buffer::float_item > const & fi)""" + return _ifcopenshell_wrapper.SvgSerializer_addYCoordinate(self, fi) + + def addSizeComponent(self, fi): + r"""addSizeComponent(SvgSerializer self, boost::shared_ptr< util::string_buffer::float_item > const & fi)""" + return _ifcopenshell_wrapper.SvgSerializer_addSizeComponent(self, fi) + + def growBoundingBox(self, x, y): + r"""growBoundingBox(SvgSerializer self, double x, double y)""" + return _ifcopenshell_wrapper.SvgSerializer_growBoundingBox(self, x, y) + + def writeHeader(self): + r"""writeHeader(SvgSerializer self)""" + return _ifcopenshell_wrapper.SvgSerializer_writeHeader(self) + + def doWriteHeader(self): + r"""doWriteHeader(SvgSerializer self)""" + return _ifcopenshell_wrapper.SvgSerializer_doWriteHeader(self) + + def ready(self): + r"""ready(SvgSerializer self) -> bool""" + return _ifcopenshell_wrapper.SvgSerializer_ready(self) + + def write(self, *args): + r""" + write(SvgSerializer self, TriangulationElement arg2) + write(SvgSerializer self, BRepElement o) + write(SvgSerializer self, SvgSerializer::path_object & p, TopoDS_Shape const & wire, boost::optional< std::vector< double,std::allocator< double > > > dash_array=boost::none) + write(SvgSerializer self, geometry_data const & data) + """ + return _ifcopenshell_wrapper.SvgSerializer_write(self, *args) + + def start_path(self, *args): + r""" + start_path(SvgSerializer self, gp_Pln const & p, IfcBaseEntity storey, std::string const & id) -> SvgSerializer::path_object + start_path(SvgSerializer self, gp_Pln const & p, std::string const & drawing_name, std::string const & id) -> SvgSerializer::path_object & + """ + return _ifcopenshell_wrapper.SvgSerializer_start_path(self, *args) + + def isTesselated(self): + r"""isTesselated(SvgSerializer self) -> bool""" + return _ifcopenshell_wrapper.SvgSerializer_isTesselated(self) + + def finalize(self): + r"""finalize(SvgSerializer self)""" + return _ifcopenshell_wrapper.SvgSerializer_finalize(self) + + def setUnitNameAndMagnitude(self, arg2, arg3): + r"""setUnitNameAndMagnitude(SvgSerializer self, std::string const & arg2, float arg3)""" + return _ifcopenshell_wrapper.SvgSerializer_setUnitNameAndMagnitude(self, arg2, arg3) + + def setFile(self, f): + r"""setFile(SvgSerializer self, file f)""" + return _ifcopenshell_wrapper.SvgSerializer_setFile(self, f) + + def setBoundingRectangle(self, width, height): + r"""setBoundingRectangle(SvgSerializer self, double width, double height)""" + return _ifcopenshell_wrapper.SvgSerializer_setBoundingRectangle(self, width, height) + + def setSectionHeight(self, h, storey=None): + r"""setSectionHeight(SvgSerializer self, double h, IfcBaseEntity storey=None)""" + return _ifcopenshell_wrapper.SvgSerializer_setSectionHeight(self, h, storey) + + def setSectionHeightsFromStoreys(self, offset=1.2): + r"""setSectionHeightsFromStoreys(SvgSerializer self, double offset=1.2)""" + return _ifcopenshell_wrapper.SvgSerializer_setSectionHeightsFromStoreys(self, offset) + + def setPrintSpaceNames(self, b): + r"""setPrintSpaceNames(SvgSerializer self, bool b)""" + return _ifcopenshell_wrapper.SvgSerializer_setPrintSpaceNames(self, b) + + def setPrintSpaceAreas(self, b): + r"""setPrintSpaceAreas(SvgSerializer self, bool b)""" + return _ifcopenshell_wrapper.SvgSerializer_setPrintSpaceAreas(self, b) + + def setDrawStoreyHeights(self, sh): + r"""setDrawStoreyHeights(SvgSerializer self, SvgSerializer::storey_height_display_types sh)""" + return _ifcopenshell_wrapper.SvgSerializer_setDrawStoreyHeights(self, sh) + + def setDrawDoorArcs(self, b): + r"""setDrawDoorArcs(SvgSerializer self, bool b)""" + return _ifcopenshell_wrapper.SvgSerializer_setDrawDoorArcs(self, b) + + def setStoreyHeightLineLength(self, d): + r"""setStoreyHeightLineLength(SvgSerializer self, double d)""" + return _ifcopenshell_wrapper.SvgSerializer_setStoreyHeightLineLength(self, d) + + def setSpaceNameTransform(self, v): + r"""setSpaceNameTransform(SvgSerializer self, std::string const & v)""" + return _ifcopenshell_wrapper.SvgSerializer_setSpaceNameTransform(self, v) + + def addTextAnnotations(self, k): + r"""addTextAnnotations(SvgSerializer self, drawing_key const & k)""" + return _ifcopenshell_wrapper.SvgSerializer_addTextAnnotations(self, k) + + def resize(self): + r"""resize(SvgSerializer self) -> std::array< std::array< double,3 >,3 >""" + return _ifcopenshell_wrapper.SvgSerializer_resize(self) + + def resetScale(self): + r"""resetScale(SvgSerializer self)""" + return _ifcopenshell_wrapper.SvgSerializer_resetScale(self) + + def setSectionRef(self, s): + r"""setSectionRef(SvgSerializer self, boost::optional< std::string > const & s)""" + return _ifcopenshell_wrapper.SvgSerializer_setSectionRef(self, s) + + def setElevationRef(self, s): + r"""setElevationRef(SvgSerializer self, boost::optional< std::string > const & s)""" + return _ifcopenshell_wrapper.SvgSerializer_setElevationRef(self, s) + + def setElevationRefGuid(self, s): + r"""setElevationRefGuid(SvgSerializer self, boost::optional< std::string > const & s)""" + return _ifcopenshell_wrapper.SvgSerializer_setElevationRefGuid(self, s) + + def setAutoSection(self, b): + r"""setAutoSection(SvgSerializer self, bool b)""" + return _ifcopenshell_wrapper.SvgSerializer_setAutoSection(self, b) + + def setAutoElevation(self, b): + r"""setAutoElevation(SvgSerializer self, bool b)""" + return _ifcopenshell_wrapper.SvgSerializer_setAutoElevation(self, b) + + def setUseNamespace(self, b): + r"""setUseNamespace(SvgSerializer self, bool b)""" + return _ifcopenshell_wrapper.SvgSerializer_setUseNamespace(self, b) + + def setUseHlrPoly(self, b): + r"""setUseHlrPoly(SvgSerializer self, bool b)""" + return _ifcopenshell_wrapper.SvgSerializer_setUseHlrPoly(self, b) + + def setUsePrefiltering(self, b): + r"""setUsePrefiltering(SvgSerializer self, bool b)""" + return _ifcopenshell_wrapper.SvgSerializer_setUsePrefiltering(self, b) + + def getUsePrefiltering(self): + r"""getUsePrefiltering(SvgSerializer self) -> bool""" + return _ifcopenshell_wrapper.SvgSerializer_getUsePrefiltering(self) + + def setSegmentProjection(self, b): + r"""setSegmentProjection(SvgSerializer self, bool b)""" + return _ifcopenshell_wrapper.SvgSerializer_setSegmentProjection(self, b) + + def getSegmentProjection(self): + r"""getSegmentProjection(SvgSerializer self) -> bool""" + return _ifcopenshell_wrapper.SvgSerializer_getSegmentProjection(self) + + def setPolygonal(self, b): + r"""setPolygonal(SvgSerializer self, bool b)""" + return _ifcopenshell_wrapper.SvgSerializer_setPolygonal(self, b) + + def setAlwaysProject(self, b): + r"""setAlwaysProject(SvgSerializer self, bool b)""" + return _ifcopenshell_wrapper.SvgSerializer_setAlwaysProject(self, b) + + def setWithoutStoreys(self, b): + r"""setWithoutStoreys(SvgSerializer self, bool b)""" + return _ifcopenshell_wrapper.SvgSerializer_setWithoutStoreys(self, b) + + def setNoCSS(self, b): + r"""setNoCSS(SvgSerializer self, bool b)""" + return _ifcopenshell_wrapper.SvgSerializer_setNoCSS(self, b) + + def setUnifyInputs(self, b): + r"""setUnifyInputs(SvgSerializer self, bool b)""" + return _ifcopenshell_wrapper.SvgSerializer_setUnifyInputs(self, b) + + def getUnifyInputs(self): + r"""getUnifyInputs(SvgSerializer self) -> bool""" + return _ifcopenshell_wrapper.SvgSerializer_getUnifyInputs(self) + + def setOnlyValid(self, b): + r"""setOnlyValid(SvgSerializer self, bool b)""" + return _ifcopenshell_wrapper.SvgSerializer_setOnlyValid(self, b) + + def getOnlyValid(self, b): + r"""getOnlyValid(SvgSerializer self, bool b) -> bool""" + return _ifcopenshell_wrapper.SvgSerializer_getOnlyValid(self, b) + + def setScale(self, s): + r"""setScale(SvgSerializer self, double s)""" + return _ifcopenshell_wrapper.SvgSerializer_setScale(self, s) + + def setDrawingCenter(self, x, y): + r"""setDrawingCenter(SvgSerializer self, double x, double y)""" + return _ifcopenshell_wrapper.SvgSerializer_setDrawingCenter(self, x, y) + + def nameElement(self, *args): + r""" + nameElement(SvgSerializer self, IfcBaseEntity storey, Element elem) -> std::string + nameElement(SvgSerializer self, IfcBaseEntity elem) -> std::string + """ + return _ifcopenshell_wrapper.SvgSerializer_nameElement(self, *args) + + def idElement(self, elem): + r"""idElement(SvgSerializer self, IfcBaseEntity elem) -> std::string""" + return _ifcopenshell_wrapper.SvgSerializer_idElement(self, elem) + + def object_id(self, storey, o): + r"""object_id(SvgSerializer self, IfcBaseEntity storey, Element o) -> std::string""" + return _ifcopenshell_wrapper.SvgSerializer_object_id(self, storey, o) + + def addDrawing(self, pos, dir, ref, name, include_projection): + r"""addDrawing(SvgSerializer self, gp_Pnt const & pos, gp_Dir const & dir, gp_Dir const & ref, std::string const & name, bool include_projection)""" + return _ifcopenshell_wrapper.SvgSerializer_addDrawing(self, pos, dir, ref, name, include_projection) + + def setSubtractionSettings(self, sbp): + r"""setSubtractionSettings(SvgSerializer self, subtract_before_project sbp)""" + return _ifcopenshell_wrapper.SvgSerializer_setSubtractionSettings(self, sbp) + + def getSubtractionSettings(self): + r"""getSubtractionSettings(SvgSerializer self) -> subtract_before_project""" + return _ifcopenshell_wrapper.SvgSerializer_getSubtractionSettings(self) + + def setProfileThreshold(self, i): + r"""setProfileThreshold(SvgSerializer self, int i)""" + return _ifcopenshell_wrapper.SvgSerializer_setProfileThreshold(self, i) + + def getProfileThreshold(self): + r"""getProfileThreshold(SvgSerializer self) -> int""" + return _ifcopenshell_wrapper.SvgSerializer_getProfileThreshold(self) + + def setMirrorY(self, b): + r"""setMirrorY(SvgSerializer self, bool b)""" + return _ifcopenshell_wrapper.SvgSerializer_setMirrorY(self, b) + + def getMirrorY(self): + r"""getMirrorY(SvgSerializer self) -> bool""" + return _ifcopenshell_wrapper.SvgSerializer_getMirrorY(self) + + def setMirrorX(self, b): + r"""setMirrorX(SvgSerializer self, bool b)""" + return _ifcopenshell_wrapper.SvgSerializer_setMirrorX(self, b) + + def getMirrorX(self): + r"""getMirrorX(SvgSerializer self) -> bool""" + return _ifcopenshell_wrapper.SvgSerializer_getMirrorX(self) + __swig_destroy__ = _ifcopenshell_wrapper.delete_SvgSerializer + +# Register SvgSerializer in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.SvgSerializer_swigregister(SvgSerializer) + +class HdfSerializer(GeometrySerializer): + r"""Proxy of C++ HdfSerializer class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def __init__(self, hdf_filename, geometry_settings, settings, read_only=False): + r"""__init__(HdfSerializer self, std::string const & hdf_filename, Settings geometry_settings, SerializerSettings settings, bool read_only=False) -> HdfSerializer""" + _ifcopenshell_wrapper.HdfSerializer_swiginit(self, _ifcopenshell_wrapper.new_HdfSerializer(hdf_filename, geometry_settings, settings, read_only)) + __swig_destroy__ = _ifcopenshell_wrapper.delete_HdfSerializer + + def ready(self): + r"""ready(HdfSerializer self) -> bool""" + return _ifcopenshell_wrapper.HdfSerializer_ready(self) + + def writeHeader(self): + r"""writeHeader(HdfSerializer self)""" + return _ifcopenshell_wrapper.HdfSerializer_writeHeader(self) + + def write(self, *args): + r""" + write(HdfSerializer self, Element o) -> H5::Group + write(HdfSerializer self, BRepElement o) + write(HdfSerializer self, TriangulationElement o) + """ + return _ifcopenshell_wrapper.HdfSerializer_write(self, *args) + + def remove(self, guid): + r"""remove(HdfSerializer self, std::string const & guid)""" + return _ifcopenshell_wrapper.HdfSerializer_remove(self, guid) + + def read(self, *args): + r"""read(HdfSerializer self, file f, std::string const & guid, std::string const & arg4, GeometrySerializer::read_type rt=READ_BREP) -> Element""" + return _ifcopenshell_wrapper.HdfSerializer_read(self, *args) + + def finalize(self): + r"""finalize(HdfSerializer self)""" + return _ifcopenshell_wrapper.HdfSerializer_finalize(self) + + def isTesselated(self): + r"""isTesselated(HdfSerializer self) -> bool""" + return _ifcopenshell_wrapper.HdfSerializer_isTesselated(self) + + def setUnitNameAndMagnitude(self, arg2, arg3): + r"""setUnitNameAndMagnitude(HdfSerializer self, std::string const & arg2, float arg3)""" + return _ifcopenshell_wrapper.HdfSerializer_setUnitNameAndMagnitude(self, arg2, arg3) + + def setFile(self, arg2): + r"""setFile(HdfSerializer self, file arg2)""" + return _ifcopenshell_wrapper.HdfSerializer_setFile(self, arg2) + +# Register HdfSerializer in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.HdfSerializer_swigregister(HdfSerializer) + +class WaveFrontOBJSerializer(WriteOnlyGeometrySerializer): + r"""Proxy of C++ WaveFrontOBJSerializer class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def __init__(self, obj_filename, mtl_filename, geometry_settings, settings): + r"""__init__(WaveFrontOBJSerializer self, buffer obj_filename, buffer mtl_filename, Settings geometry_settings, SerializerSettings settings) -> WaveFrontOBJSerializer""" + _ifcopenshell_wrapper.WaveFrontOBJSerializer_swiginit(self, _ifcopenshell_wrapper.new_WaveFrontOBJSerializer(obj_filename, mtl_filename, geometry_settings, settings)) + __swig_destroy__ = _ifcopenshell_wrapper.delete_WaveFrontOBJSerializer + + def ready(self): + r"""ready(WaveFrontOBJSerializer self) -> bool""" + return _ifcopenshell_wrapper.WaveFrontOBJSerializer_ready(self) + + def writeHeader(self): + r"""writeHeader(WaveFrontOBJSerializer self)""" + return _ifcopenshell_wrapper.WaveFrontOBJSerializer_writeHeader(self) + + def writeMaterial(self, style): + r"""writeMaterial(WaveFrontOBJSerializer self, ifcopenshell::geometry::taxonomy::style::ptr const style)""" + return _ifcopenshell_wrapper.WaveFrontOBJSerializer_writeMaterial(self, style) + + def write(self, *args): + r""" + write(WaveFrontOBJSerializer self, TriangulationElement o) + write(WaveFrontOBJSerializer self, BRepElement arg2) + """ + return _ifcopenshell_wrapper.WaveFrontOBJSerializer_write(self, *args) + + def finalize(self): + r"""finalize(WaveFrontOBJSerializer self)""" + return _ifcopenshell_wrapper.WaveFrontOBJSerializer_finalize(self) + + def isTesselated(self): + r"""isTesselated(WaveFrontOBJSerializer self) -> bool""" + return _ifcopenshell_wrapper.WaveFrontOBJSerializer_isTesselated(self) + + def setUnitNameAndMagnitude(self, arg2, arg3): + r"""setUnitNameAndMagnitude(WaveFrontOBJSerializer self, std::string const & arg2, float arg3)""" + return _ifcopenshell_wrapper.WaveFrontOBJSerializer_setUnitNameAndMagnitude(self, arg2, arg3) + + def setFile(self, arg2): + r"""setFile(WaveFrontOBJSerializer self, file arg2)""" + return _ifcopenshell_wrapper.WaveFrontOBJSerializer_setFile(self, arg2) + +# Register WaveFrontOBJSerializer in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.WaveFrontOBJSerializer_swigregister(WaveFrontOBJSerializer) + +class ColladaSerializer(WriteOnlyGeometrySerializer): + r"""Proxy of C++ ColladaSerializer class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def __init__(self, dae_filename, geometry_settings, settings): + r"""__init__(ColladaSerializer self, std::string const & dae_filename, Settings geometry_settings, SerializerSettings settings) -> ColladaSerializer""" + _ifcopenshell_wrapper.ColladaSerializer_swiginit(self, _ifcopenshell_wrapper.new_ColladaSerializer(dae_filename, geometry_settings, settings)) + + def ready(self): + r"""ready(ColladaSerializer self) -> bool""" + return _ifcopenshell_wrapper.ColladaSerializer_ready(self) + + def writeHeader(self): + r"""writeHeader(ColladaSerializer self)""" + return _ifcopenshell_wrapper.ColladaSerializer_writeHeader(self) + + def write(self, *args): + r""" + write(ColladaSerializer self, TriangulationElement o) + write(ColladaSerializer self, BRepElement arg2) + """ + return _ifcopenshell_wrapper.ColladaSerializer_write(self, *args) + + def finalize(self): + r"""finalize(ColladaSerializer self)""" + return _ifcopenshell_wrapper.ColladaSerializer_finalize(self) + + def isTesselated(self): + r"""isTesselated(ColladaSerializer self) -> bool""" + return _ifcopenshell_wrapper.ColladaSerializer_isTesselated(self) + + def setUnitNameAndMagnitude(self, name, magnitude): + r"""setUnitNameAndMagnitude(ColladaSerializer self, std::string const & name, float magnitude)""" + return _ifcopenshell_wrapper.ColladaSerializer_setUnitNameAndMagnitude(self, name, magnitude) + + def setFile(self, arg2): + r"""setFile(ColladaSerializer self, file arg2)""" + return _ifcopenshell_wrapper.ColladaSerializer_setFile(self, arg2) + + def object_id(self, o): + r"""object_id(ColladaSerializer self, Element o) -> std::string""" + return _ifcopenshell_wrapper.ColladaSerializer_object_id(self, o) + __swig_destroy__ = _ifcopenshell_wrapper.delete_ColladaSerializer + +# Register ColladaSerializer in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.ColladaSerializer_swigregister(ColladaSerializer) + +class XmlSerializer(object): + r"""Proxy of C++ XmlSerializer class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def __init__(self, file, xml_filename): + r"""__init__(XmlSerializer self, file file, std::string const & xml_filename) -> XmlSerializer""" + _ifcopenshell_wrapper.XmlSerializer_swiginit(self, _ifcopenshell_wrapper.new_XmlSerializer(file, xml_filename)) + __swig_destroy__ = _ifcopenshell_wrapper.delete_XmlSerializer + + def ready(self): + r"""ready(XmlSerializer self) -> bool""" + return _ifcopenshell_wrapper.XmlSerializer_ready(self) + + def writeHeader(self): + r"""writeHeader(XmlSerializer self)""" + return _ifcopenshell_wrapper.XmlSerializer_writeHeader(self) + + def finalize(self): + r"""finalize(XmlSerializer self)""" + return _ifcopenshell_wrapper.XmlSerializer_finalize(self) + + def setFile(self, arg2): + r"""setFile(XmlSerializer self, file arg2)""" + return _ifcopenshell_wrapper.XmlSerializer_setFile(self, arg2) + +# Register XmlSerializer in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.XmlSerializer_swigregister(XmlSerializer) + +class XmlSerializerFactory(object): + r"""Proxy of C++ XmlSerializerFactory class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + @staticmethod + def implementations(): + r"""implementations() -> XmlSerializerFactory::Factory &""" + return _ifcopenshell_wrapper.XmlSerializerFactory_implementations() + + def __init__(self): + r"""__init__(XmlSerializerFactory self) -> XmlSerializerFactory""" + _ifcopenshell_wrapper.XmlSerializerFactory_swiginit(self, _ifcopenshell_wrapper.new_XmlSerializerFactory()) + __swig_destroy__ = _ifcopenshell_wrapper.delete_XmlSerializerFactory + +# Register XmlSerializerFactory in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.XmlSerializerFactory_swigregister(XmlSerializerFactory) + +def XmlSerializerFactory_implementations(): + r"""XmlSerializerFactory_implementations() -> XmlSerializerFactory::Factory &""" + return _ifcopenshell_wrapper.XmlSerializerFactory_implementations() + +class GltfSerializer(WriteOnlyGeometrySerializer): + r"""Proxy of C++ GltfSerializer class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def __init__(self, filename, geometry_settings, settings): + r"""__init__(GltfSerializer self, std::string const & filename, Settings geometry_settings, SerializerSettings settings) -> GltfSerializer""" + _ifcopenshell_wrapper.GltfSerializer_swiginit(self, _ifcopenshell_wrapper.new_GltfSerializer(filename, geometry_settings, settings)) + __swig_destroy__ = _ifcopenshell_wrapper.delete_GltfSerializer + + def ready(self): + r"""ready(GltfSerializer self) -> bool""" + return _ifcopenshell_wrapper.GltfSerializer_ready(self) + + def writeHeader(self): + r"""writeHeader(GltfSerializer self)""" + return _ifcopenshell_wrapper.GltfSerializer_writeHeader(self) + + def write(self, *args): + r""" + write(GltfSerializer self, TriangulationElement o) + write(GltfSerializer self, BRepElement arg2) + """ + return _ifcopenshell_wrapper.GltfSerializer_write(self, *args) + + def finalize(self): + r"""finalize(GltfSerializer self)""" + return _ifcopenshell_wrapper.GltfSerializer_finalize(self) + + def isTesselated(self): + r"""isTesselated(GltfSerializer self) -> bool""" + return _ifcopenshell_wrapper.GltfSerializer_isTesselated(self) + + def setUnitNameAndMagnitude(self, arg2, arg3): + r"""setUnitNameAndMagnitude(GltfSerializer self, std::string const & arg2, float arg3)""" + return _ifcopenshell_wrapper.GltfSerializer_setUnitNameAndMagnitude(self, arg2, arg3) + + def setFile(self, arg2): + r"""setFile(GltfSerializer self, file arg2)""" + return _ifcopenshell_wrapper.GltfSerializer_setFile(self, arg2) + +# Register GltfSerializer in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.GltfSerializer_swigregister(GltfSerializer) + +class TtlWktSerializer(WriteOnlyGeometrySerializer): + r"""Proxy of C++ TtlWktSerializer class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def __init__(self, filename, geometry_settings, settings): + r"""__init__(TtlWktSerializer self, buffer filename, Settings geometry_settings, SerializerSettings settings) -> TtlWktSerializer""" + _ifcopenshell_wrapper.TtlWktSerializer_swiginit(self, _ifcopenshell_wrapper.new_TtlWktSerializer(filename, geometry_settings, settings)) + __swig_destroy__ = _ifcopenshell_wrapper.delete_TtlWktSerializer + + def ready(self): + r"""ready(TtlWktSerializer self) -> bool""" + return _ifcopenshell_wrapper.TtlWktSerializer_ready(self) + + def writeHeader(self): + r"""writeHeader(TtlWktSerializer self)""" + return _ifcopenshell_wrapper.TtlWktSerializer_writeHeader(self) + + def write(self, *args): + r""" + write(TtlWktSerializer self, TriangulationElement o) + write(TtlWktSerializer self, BRepElement arg2) + """ + return _ifcopenshell_wrapper.TtlWktSerializer_write(self, *args) + + def finalize(self): + r"""finalize(TtlWktSerializer self)""" + return _ifcopenshell_wrapper.TtlWktSerializer_finalize(self) + + def isTesselated(self): + r"""isTesselated(TtlWktSerializer self) -> bool""" + return _ifcopenshell_wrapper.TtlWktSerializer_isTesselated(self) + + def setUnitNameAndMagnitude(self, arg2, arg3): + r"""setUnitNameAndMagnitude(TtlWktSerializer self, std::string const & arg2, float arg3)""" + return _ifcopenshell_wrapper.TtlWktSerializer_setUnitNameAndMagnitude(self, arg2, arg3) + + def setFile(self, arg2): + r"""setFile(TtlWktSerializer self, file arg2)""" + return _ifcopenshell_wrapper.TtlWktSerializer_setFile(self, arg2) + + def ttl_object_id(self, o, postfix=None): + r"""ttl_object_id(TtlWktSerializer self, Element o, char const *const postfix=None) -> std::string""" + return _ifcopenshell_wrapper.TtlWktSerializer_ttl_object_id(self, o, postfix) + +# Register TtlWktSerializer in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.TtlWktSerializer_swigregister(TtlWktSerializer) + +class ray_intersection_results(object): + r"""Proxy of C++ std::vector< IfcGeom::ray_intersection_result > class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def iterator(self): + r"""iterator(ray_intersection_results self) -> SwigPyIterator""" + return _ifcopenshell_wrapper.ray_intersection_results_iterator(self) + def __iter__(self): + return self.iterator() + + def __nonzero__(self): + r"""__nonzero__(ray_intersection_results self) -> bool""" + return _ifcopenshell_wrapper.ray_intersection_results___nonzero__(self) + + def __bool__(self): + r"""__bool__(ray_intersection_results self) -> bool""" + return _ifcopenshell_wrapper.ray_intersection_results___bool__(self) + + def __len__(self): + r"""__len__(ray_intersection_results self) -> std::vector< IfcGeom::ray_intersection_result >::size_type""" + return _ifcopenshell_wrapper.ray_intersection_results___len__(self) + + def __getslice__(self, i, j): + r"""__getslice__(ray_intersection_results self, std::vector< IfcGeom::ray_intersection_result >::difference_type i, std::vector< IfcGeom::ray_intersection_result >::difference_type j) -> ray_intersection_results""" + return _ifcopenshell_wrapper.ray_intersection_results___getslice__(self, i, j) + + def __setslice__(self, *args): + r""" + __setslice__(ray_intersection_results self, std::vector< IfcGeom::ray_intersection_result >::difference_type i, std::vector< IfcGeom::ray_intersection_result >::difference_type j) + __setslice__(ray_intersection_results self, std::vector< IfcGeom::ray_intersection_result >::difference_type i, std::vector< IfcGeom::ray_intersection_result >::difference_type j, ray_intersection_results v) + """ + return _ifcopenshell_wrapper.ray_intersection_results___setslice__(self, *args) + + def __delslice__(self, i, j): + r"""__delslice__(ray_intersection_results self, std::vector< IfcGeom::ray_intersection_result >::difference_type i, std::vector< IfcGeom::ray_intersection_result >::difference_type j)""" + return _ifcopenshell_wrapper.ray_intersection_results___delslice__(self, i, j) + + def __delitem__(self, *args): + r""" + __delitem__(ray_intersection_results self, std::vector< IfcGeom::ray_intersection_result >::difference_type i) + __delitem__(ray_intersection_results self, PySliceObject * slice) + """ + return _ifcopenshell_wrapper.ray_intersection_results___delitem__(self, *args) + + def __getitem__(self, *args): + r""" + __getitem__(ray_intersection_results self, PySliceObject * slice) -> ray_intersection_results + __getitem__(ray_intersection_results self, std::vector< IfcGeom::ray_intersection_result >::difference_type i) -> ray_intersection_result + """ + return _ifcopenshell_wrapper.ray_intersection_results___getitem__(self, *args) + + def __setitem__(self, *args): + r""" + __setitem__(ray_intersection_results self, PySliceObject * slice, ray_intersection_results v) + __setitem__(ray_intersection_results self, PySliceObject * slice) + __setitem__(ray_intersection_results self, std::vector< IfcGeom::ray_intersection_result >::difference_type i, ray_intersection_result x) + """ + return _ifcopenshell_wrapper.ray_intersection_results___setitem__(self, *args) + + def pop(self): + r"""pop(ray_intersection_results self) -> ray_intersection_result""" + return _ifcopenshell_wrapper.ray_intersection_results_pop(self) + + def append(self, x): + r"""append(ray_intersection_results self, ray_intersection_result x)""" + return _ifcopenshell_wrapper.ray_intersection_results_append(self, x) + + def empty(self): + r"""empty(ray_intersection_results self) -> bool""" + return _ifcopenshell_wrapper.ray_intersection_results_empty(self) + + def size(self): + r"""size(ray_intersection_results self) -> std::vector< IfcGeom::ray_intersection_result >::size_type""" + return _ifcopenshell_wrapper.ray_intersection_results_size(self) + + def swap(self, v): + r"""swap(ray_intersection_results self, ray_intersection_results v)""" + return _ifcopenshell_wrapper.ray_intersection_results_swap(self, v) + + def begin(self): + r"""begin(ray_intersection_results self) -> std::vector< IfcGeom::ray_intersection_result >::iterator""" + return _ifcopenshell_wrapper.ray_intersection_results_begin(self) + + def end(self): + r"""end(ray_intersection_results self) -> std::vector< IfcGeom::ray_intersection_result >::iterator""" + return _ifcopenshell_wrapper.ray_intersection_results_end(self) + + def rbegin(self): + r"""rbegin(ray_intersection_results self) -> std::vector< IfcGeom::ray_intersection_result >::reverse_iterator""" + return _ifcopenshell_wrapper.ray_intersection_results_rbegin(self) + + def rend(self): + r"""rend(ray_intersection_results self) -> std::vector< IfcGeom::ray_intersection_result >::reverse_iterator""" + return _ifcopenshell_wrapper.ray_intersection_results_rend(self) + + def clear(self): + r"""clear(ray_intersection_results self)""" + return _ifcopenshell_wrapper.ray_intersection_results_clear(self) + + def get_allocator(self): + r"""get_allocator(ray_intersection_results self) -> std::vector< IfcGeom::ray_intersection_result >::allocator_type""" + return _ifcopenshell_wrapper.ray_intersection_results_get_allocator(self) + + def pop_back(self): + r"""pop_back(ray_intersection_results self)""" + return _ifcopenshell_wrapper.ray_intersection_results_pop_back(self) + + def erase(self, *args): + r""" + erase(ray_intersection_results self, std::vector< IfcGeom::ray_intersection_result >::iterator pos) -> std::vector< IfcGeom::ray_intersection_result >::iterator + erase(ray_intersection_results self, std::vector< IfcGeom::ray_intersection_result >::iterator first, std::vector< IfcGeom::ray_intersection_result >::iterator last) -> std::vector< IfcGeom::ray_intersection_result >::iterator + """ + return _ifcopenshell_wrapper.ray_intersection_results_erase(self, *args) + + def __init__(self, *args): + r""" + __init__(ray_intersection_results self) -> ray_intersection_results + __init__(ray_intersection_results self, ray_intersection_results other) -> ray_intersection_results + __init__(ray_intersection_results self, std::vector< IfcGeom::ray_intersection_result >::size_type size) -> ray_intersection_results + __init__(ray_intersection_results self, std::vector< IfcGeom::ray_intersection_result >::size_type size, ray_intersection_result value) -> ray_intersection_results + """ + _ifcopenshell_wrapper.ray_intersection_results_swiginit(self, _ifcopenshell_wrapper.new_ray_intersection_results(*args)) + + def push_back(self, x): + r"""push_back(ray_intersection_results self, ray_intersection_result x)""" + return _ifcopenshell_wrapper.ray_intersection_results_push_back(self, x) + + def front(self): + r"""front(ray_intersection_results self) -> ray_intersection_result""" + return _ifcopenshell_wrapper.ray_intersection_results_front(self) + + def back(self): + r"""back(ray_intersection_results self) -> ray_intersection_result""" + return _ifcopenshell_wrapper.ray_intersection_results_back(self) + + def assign(self, n, x): + r"""assign(ray_intersection_results self, std::vector< IfcGeom::ray_intersection_result >::size_type n, ray_intersection_result x)""" + return _ifcopenshell_wrapper.ray_intersection_results_assign(self, n, x) + + def resize(self, *args): + r""" + resize(ray_intersection_results self, std::vector< IfcGeom::ray_intersection_result >::size_type new_size) + resize(ray_intersection_results self, std::vector< IfcGeom::ray_intersection_result >::size_type new_size, ray_intersection_result x) + """ + return _ifcopenshell_wrapper.ray_intersection_results_resize(self, *args) + + def insert(self, *args): + r""" + insert(ray_intersection_results self, std::vector< IfcGeom::ray_intersection_result >::iterator pos, ray_intersection_result x) -> std::vector< IfcGeom::ray_intersection_result >::iterator + insert(ray_intersection_results self, std::vector< IfcGeom::ray_intersection_result >::iterator pos, std::vector< IfcGeom::ray_intersection_result >::size_type n, ray_intersection_result x) + """ + return _ifcopenshell_wrapper.ray_intersection_results_insert(self, *args) + + def reserve(self, n): + r"""reserve(ray_intersection_results self, std::vector< IfcGeom::ray_intersection_result >::size_type n)""" + return _ifcopenshell_wrapper.ray_intersection_results_reserve(self, n) + + def capacity(self): + r"""capacity(ray_intersection_results self) -> std::vector< IfcGeom::ray_intersection_result >::size_type""" + return _ifcopenshell_wrapper.ray_intersection_results_capacity(self) + __swig_destroy__ = _ifcopenshell_wrapper.delete_ray_intersection_results + +# Register ray_intersection_results in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.ray_intersection_results_swigregister(ray_intersection_results) + +class clashes(object): + r"""Proxy of C++ std::vector< IfcGeom::clash > class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def iterator(self): + r"""iterator(clashes self) -> SwigPyIterator""" + return _ifcopenshell_wrapper.clashes_iterator(self) + def __iter__(self): + return self.iterator() + + def __nonzero__(self): + r"""__nonzero__(clashes self) -> bool""" + return _ifcopenshell_wrapper.clashes___nonzero__(self) + + def __bool__(self): + r"""__bool__(clashes self) -> bool""" + return _ifcopenshell_wrapper.clashes___bool__(self) + + def __len__(self): + r"""__len__(clashes self) -> std::vector< IfcGeom::clash >::size_type""" + return _ifcopenshell_wrapper.clashes___len__(self) + + def __getslice__(self, i, j): + r"""__getslice__(clashes self, std::vector< IfcGeom::clash >::difference_type i, std::vector< IfcGeom::clash >::difference_type j) -> clashes""" + return _ifcopenshell_wrapper.clashes___getslice__(self, i, j) + + def __setslice__(self, *args): + r""" + __setslice__(clashes self, std::vector< IfcGeom::clash >::difference_type i, std::vector< IfcGeom::clash >::difference_type j) + __setslice__(clashes self, std::vector< IfcGeom::clash >::difference_type i, std::vector< IfcGeom::clash >::difference_type j, clashes v) + """ + return _ifcopenshell_wrapper.clashes___setslice__(self, *args) + + def __delslice__(self, i, j): + r"""__delslice__(clashes self, std::vector< IfcGeom::clash >::difference_type i, std::vector< IfcGeom::clash >::difference_type j)""" + return _ifcopenshell_wrapper.clashes___delslice__(self, i, j) + + def __delitem__(self, *args): + r""" + __delitem__(clashes self, std::vector< IfcGeom::clash >::difference_type i) + __delitem__(clashes self, PySliceObject * slice) + """ + return _ifcopenshell_wrapper.clashes___delitem__(self, *args) + + def __getitem__(self, *args): + r""" + __getitem__(clashes self, PySliceObject * slice) -> clashes + __getitem__(clashes self, std::vector< IfcGeom::clash >::difference_type i) -> clash + """ + return _ifcopenshell_wrapper.clashes___getitem__(self, *args) + + def __setitem__(self, *args): + r""" + __setitem__(clashes self, PySliceObject * slice, clashes v) + __setitem__(clashes self, PySliceObject * slice) + __setitem__(clashes self, std::vector< IfcGeom::clash >::difference_type i, clash x) + """ + return _ifcopenshell_wrapper.clashes___setitem__(self, *args) + + def pop(self): + r"""pop(clashes self) -> clash""" + return _ifcopenshell_wrapper.clashes_pop(self) + + def append(self, x): + r"""append(clashes self, clash x)""" + return _ifcopenshell_wrapper.clashes_append(self, x) + + def empty(self): + r"""empty(clashes self) -> bool""" + return _ifcopenshell_wrapper.clashes_empty(self) + + def size(self): + r"""size(clashes self) -> std::vector< IfcGeom::clash >::size_type""" + return _ifcopenshell_wrapper.clashes_size(self) + + def swap(self, v): + r"""swap(clashes self, clashes v)""" + return _ifcopenshell_wrapper.clashes_swap(self, v) + + def begin(self): + r"""begin(clashes self) -> std::vector< IfcGeom::clash >::iterator""" + return _ifcopenshell_wrapper.clashes_begin(self) + + def end(self): + r"""end(clashes self) -> std::vector< IfcGeom::clash >::iterator""" + return _ifcopenshell_wrapper.clashes_end(self) + + def rbegin(self): + r"""rbegin(clashes self) -> std::vector< IfcGeom::clash >::reverse_iterator""" + return _ifcopenshell_wrapper.clashes_rbegin(self) + + def rend(self): + r"""rend(clashes self) -> std::vector< IfcGeom::clash >::reverse_iterator""" + return _ifcopenshell_wrapper.clashes_rend(self) + + def clear(self): + r"""clear(clashes self)""" + return _ifcopenshell_wrapper.clashes_clear(self) + + def get_allocator(self): + r"""get_allocator(clashes self) -> std::vector< IfcGeom::clash >::allocator_type""" + return _ifcopenshell_wrapper.clashes_get_allocator(self) + + def pop_back(self): + r"""pop_back(clashes self)""" + return _ifcopenshell_wrapper.clashes_pop_back(self) + + def erase(self, *args): + r""" + erase(clashes self, std::vector< IfcGeom::clash >::iterator pos) -> std::vector< IfcGeom::clash >::iterator + erase(clashes self, std::vector< IfcGeom::clash >::iterator first, std::vector< IfcGeom::clash >::iterator last) -> std::vector< IfcGeom::clash >::iterator + """ + return _ifcopenshell_wrapper.clashes_erase(self, *args) + + def __init__(self, *args): + r""" + __init__(clashes self) -> clashes + __init__(clashes self, clashes other) -> clashes + __init__(clashes self, std::vector< IfcGeom::clash >::size_type size) -> clashes + __init__(clashes self, std::vector< IfcGeom::clash >::size_type size, clash value) -> clashes + """ + _ifcopenshell_wrapper.clashes_swiginit(self, _ifcopenshell_wrapper.new_clashes(*args)) + + def push_back(self, x): + r"""push_back(clashes self, clash x)""" + return _ifcopenshell_wrapper.clashes_push_back(self, x) + + def front(self): + r"""front(clashes self) -> clash""" + return _ifcopenshell_wrapper.clashes_front(self) + + def back(self): + r"""back(clashes self) -> clash""" + return _ifcopenshell_wrapper.clashes_back(self) + + def assign(self, n, x): + r"""assign(clashes self, std::vector< IfcGeom::clash >::size_type n, clash x)""" + return _ifcopenshell_wrapper.clashes_assign(self, n, x) + + def resize(self, *args): + r""" + resize(clashes self, std::vector< IfcGeom::clash >::size_type new_size) + resize(clashes self, std::vector< IfcGeom::clash >::size_type new_size, clash x) + """ + return _ifcopenshell_wrapper.clashes_resize(self, *args) + + def insert(self, *args): + r""" + insert(clashes self, std::vector< IfcGeom::clash >::iterator pos, clash x) -> std::vector< IfcGeom::clash >::iterator + insert(clashes self, std::vector< IfcGeom::clash >::iterator pos, std::vector< IfcGeom::clash >::size_type n, clash x) + """ + return _ifcopenshell_wrapper.clashes_insert(self, *args) + + def reserve(self, n): + r"""reserve(clashes self, std::vector< IfcGeom::clash >::size_type n)""" + return _ifcopenshell_wrapper.clashes_reserve(self, n) + + def capacity(self): + r"""capacity(clashes self) -> std::vector< IfcGeom::clash >::size_type""" + return _ifcopenshell_wrapper.clashes_capacity(self) + __swig_destroy__ = _ifcopenshell_wrapper.delete_clashes + +# Register clashes in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.clashes_swigregister(clashes) + +class ray_intersection_result(object): + r"""Proxy of C++ IfcGeom::ray_intersection_result class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + distance = property(_ifcopenshell_wrapper.ray_intersection_result_distance_get, _ifcopenshell_wrapper.ray_intersection_result_distance_set, doc=r"""distance : double""") + style_index = property(_ifcopenshell_wrapper.ray_intersection_result_style_index_get, _ifcopenshell_wrapper.ray_intersection_result_style_index_set, doc=r"""style_index : int""") + instance = property(_ifcopenshell_wrapper.ray_intersection_result_instance_get, _ifcopenshell_wrapper.ray_intersection_result_instance_set, doc=r"""instance : p.q(const).IfcUtil::IfcBaseEntity""") + position = property(_ifcopenshell_wrapper.ray_intersection_result_position_get, _ifcopenshell_wrapper.ray_intersection_result_position_set, doc=r"""position : std::array<(double,3)>""") + normal = property(_ifcopenshell_wrapper.ray_intersection_result_normal_get, _ifcopenshell_wrapper.ray_intersection_result_normal_set, doc=r"""normal : std::array<(double,3)>""") + ray_distance = property(_ifcopenshell_wrapper.ray_intersection_result_ray_distance_get, _ifcopenshell_wrapper.ray_intersection_result_ray_distance_set, doc=r"""ray_distance : double""") + dot_product = property(_ifcopenshell_wrapper.ray_intersection_result_dot_product_get, _ifcopenshell_wrapper.ray_intersection_result_dot_product_set, doc=r"""dot_product : double""") + + def __init__(self): + r"""__init__(ray_intersection_result self) -> ray_intersection_result""" + _ifcopenshell_wrapper.ray_intersection_result_swiginit(self, _ifcopenshell_wrapper.new_ray_intersection_result()) + __swig_destroy__ = _ifcopenshell_wrapper.delete_ray_intersection_result + +# Register ray_intersection_result in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.ray_intersection_result_swigregister(ray_intersection_result) + +class clash(object): + r"""Proxy of C++ IfcGeom::clash class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + clash_type = property(_ifcopenshell_wrapper.clash_clash_type_get, _ifcopenshell_wrapper.clash_clash_type_set, doc=r"""clash_type : int""") + a = property(_ifcopenshell_wrapper.clash_a_get, _ifcopenshell_wrapper.clash_a_set, doc=r"""a : p.q(const).IfcUtil::IfcBaseClass""") + b = property(_ifcopenshell_wrapper.clash_b_get, _ifcopenshell_wrapper.clash_b_set, doc=r"""b : p.q(const).IfcUtil::IfcBaseClass""") + distance = property(_ifcopenshell_wrapper.clash_distance_get, _ifcopenshell_wrapper.clash_distance_set, doc=r"""distance : double""") + p1 = property(_ifcopenshell_wrapper.clash_p1_get, _ifcopenshell_wrapper.clash_p1_set, doc=r"""p1 : std::array<(double,3)>""") + p2 = property(_ifcopenshell_wrapper.clash_p2_get, _ifcopenshell_wrapper.clash_p2_set, doc=r"""p2 : std::array<(double,3)>""") + + def __init__(self): + r"""__init__(clash self) -> clash""" + _ifcopenshell_wrapper.clash_swiginit(self, _ifcopenshell_wrapper.new_clash()) + __swig_destroy__ = _ifcopenshell_wrapper.delete_clash + +# Register clash in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.clash_swigregister(clash) + +class tree(object): + r"""Proxy of C++ IfcGeom::tree class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def __init__(self, *args): + r""" + __init__(tree self) -> tree + __init__(tree self, file f) -> tree + __init__(tree self, file f, Settings settings) -> tree + __init__(tree self, Iterator it) -> tree + """ + _ifcopenshell_wrapper.tree_swiginit(self, _ifcopenshell_wrapper.new_tree(*args)) + + def add_file(self, *args): + r""" + add_file(tree self, file f, Settings settings) + add_file(tree self, Iterator it) + """ + return _ifcopenshell_wrapper.tree_add_file(self, *args) + + def write_h5(self): + r"""write_h5(tree self)""" + return _ifcopenshell_wrapper.tree_write_h5(self) + + def uint8_to_b64(self, uuids_array): + r"""uint8_to_b64(tree self, std::vector< uint8_t,std::allocator< uint8_t > > const & uuids_array) -> std::string""" + return _ifcopenshell_wrapper.tree_uint8_to_b64(self, uuids_array) + + @staticmethod + def is_manifold(fs): + r"""is_manifold(std::vector< int,std::allocator< int > > const & fs) -> bool""" + return _ifcopenshell_wrapper.tree_is_manifold(fs) + + def add_element(self, *args): + r""" + add_element(tree self, TriangulationElement elem) + add_element(tree self, BRepElement elem) + """ + return _ifcopenshell_wrapper.tree_add_element(self, *args) + + def distances(self): + r"""distances(tree self) -> std::vector< double,std::allocator< double > > const &""" + return _ifcopenshell_wrapper.tree_distances(self) + + def protrusion_distances(self): + r"""protrusion_distances(tree self) -> std::vector< double,std::allocator< double > > const &""" + return _ifcopenshell_wrapper.tree_protrusion_distances(self) + + def select_ray(self, p0, d, length=1000.): + r"""select_ray(tree self, gp_Pnt const & p0, gp_Dir const & d, double length=1000.) -> ray_intersection_results""" + return _ifcopenshell_wrapper.tree_select_ray(self, p0, d, length) + + def enable_face_styles(self, *args): + r""" + enable_face_styles(tree self) -> bool + enable_face_styles(tree self, bool b) + """ + return _ifcopenshell_wrapper.tree_enable_face_styles(self, *args) + + def styles(self): + r"""styles(tree self) -> std::vector< ifcopenshell::geometry::taxonomy::style::ptr,std::allocator< ifcopenshell::geometry::taxonomy::style::ptr > > const &""" + return _ifcopenshell_wrapper.tree_styles(self) + + @staticmethod + def vector_to_list(ps): + r"""vector_to_list(std::vector< IfcUtil::IfcBaseEntity const *,std::allocator< IfcUtil::IfcBaseEntity const * > > const & ps) -> aggregate_of_instance::ptr""" + return _ifcopenshell_wrapper.tree_vector_to_list(ps) + + def select_box(self, *args): + r""" + select_box(tree self, entity_instance e, bool completely_within=False, double extend=-1.e-5) -> aggregate_of_instance::ptr + select_box(tree self, gp_Pnt const & p) -> aggregate_of_instance::ptr + select_box(tree self, Bnd_Box const & b, bool completely_within=False) -> aggregate_of_instance::ptr + """ + return _ifcopenshell_wrapper.tree_select_box(self, *args) + + def select(self, *args): + r""" + select(tree self, entity_instance e, bool completely_within=False, double extend=0.0) -> aggregate_of_instance::ptr + select(tree self, gp_Pnt const & p, double extend=0.0) -> aggregate_of_instance::ptr + select(tree self, std::string const & shape_serialization, bool completely_within=False, double extend=-1.e-5) -> aggregate_of_instance::ptr + select(tree self, BRepElement elem, bool completely_within=False, double extend=-1.e-5) -> aggregate_of_instance::ptr + """ + return _ifcopenshell_wrapper.tree_select(self, *args) + + def clash_intersection_many(self, set_a, set_b, tolerance, check_all): + r"""clash_intersection_many(tree self, std::vector< IfcUtil::IfcBaseClass *,std::allocator< IfcUtil::IfcBaseClass * > > const & set_a, std::vector< IfcUtil::IfcBaseClass *,std::allocator< IfcUtil::IfcBaseClass * > > const & set_b, double tolerance, bool check_all) -> clashes""" + return _ifcopenshell_wrapper.tree_clash_intersection_many(self, set_a, set_b, tolerance, check_all) + + def clash_collision_many(self, set_a, set_b, allow_touching): + r"""clash_collision_many(tree self, std::vector< IfcUtil::IfcBaseClass *,std::allocator< IfcUtil::IfcBaseClass * > > const & set_a, std::vector< IfcUtil::IfcBaseClass *,std::allocator< IfcUtil::IfcBaseClass * > > const & set_b, bool allow_touching) -> clashes""" + return _ifcopenshell_wrapper.tree_clash_collision_many(self, set_a, set_b, allow_touching) + + def clash_clearance_many(self, set_a, set_b, clearance, check_all): + r"""clash_clearance_many(tree self, std::vector< IfcUtil::IfcBaseClass *,std::allocator< IfcUtil::IfcBaseClass * > > const & set_a, std::vector< IfcUtil::IfcBaseClass *,std::allocator< IfcUtil::IfcBaseClass * > > const & set_b, double clearance, bool check_all) -> clashes""" + return _ifcopenshell_wrapper.tree_clash_clearance_many(self, set_a, set_b, clearance, check_all) + __swig_destroy__ = _ifcopenshell_wrapper.delete_tree + +# Register tree in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.tree_swigregister(tree) + +def tree_is_manifold(fs): + r"""tree_is_manifold(std::vector< int,std::allocator< int > > const & fs) -> bool""" + return _ifcopenshell_wrapper.tree_is_manifold(fs) + +def tree_vector_to_list(ps): + r"""tree_vector_to_list(std::vector< IfcUtil::IfcBaseEntity const *,std::allocator< IfcUtil::IfcBaseEntity const * > > const & ps) -> aggregate_of_instance::ptr""" + return _ifcopenshell_wrapper.tree_vector_to_list(ps) + + +def construct_iterator(geometry_library, settings, file, num_threads): + r"""construct_iterator(std::string const & geometry_library, Settings settings, file file, int num_threads) -> Iterator""" + return _ifcopenshell_wrapper.construct_iterator(geometry_library, settings, file, num_threads) + +def construct_iterator_with_include_exclude(geometry_library, settings, file, elems, include, num_threads): + r"""construct_iterator_with_include_exclude(std::string const & geometry_library, Settings settings, file file, std::vector< std::string,std::allocator< std::string > > elems, bool include, int num_threads) -> Iterator""" + return _ifcopenshell_wrapper.construct_iterator_with_include_exclude(geometry_library, settings, file, elems, include, num_threads) + +def construct_iterator_with_include_exclude_globalid(geometry_library, settings, file, elems, include, num_threads): + r"""construct_iterator_with_include_exclude_globalid(std::string const & geometry_library, Settings settings, file file, std::vector< std::string,std::allocator< std::string > > elems, bool include, int num_threads) -> Iterator""" + return _ifcopenshell_wrapper.construct_iterator_with_include_exclude_globalid(geometry_library, settings, file, elems, include, num_threads) + +def construct_iterator_with_include_exclude_id(geometry_library, settings, file, elems, include, num_threads): + r"""construct_iterator_with_include_exclude_id(std::string const & geometry_library, Settings settings, file file, std::vector< int,std::allocator< int > > elems, bool include, int num_threads) -> Iterator""" + return _ifcopenshell_wrapper.construct_iterator_with_include_exclude_id(geometry_library, settings, file, elems, include, num_threads) + +def map_shape(settings, instance): + r"""map_shape(Settings settings, entity_instance instance) -> ifcopenshell::geometry::taxonomy::item::ptr""" + return _ifcopenshell_wrapper.map_shape(settings, instance) + +def create_shape(*args): + r"""create_shape(Settings settings, entity_instance instance, entity_instance representation=None, char const *const geometry_library="opencascade") -> boost::variant< IfcGeom::Element *,IfcGeom::Representation::Representation *,IfcGeom::Transformation * >""" + return _ifcopenshell_wrapper.create_shape(*args) + +def serialise(schema_name, shape_str, advanced=True): + r"""serialise(std::string const & schema_name, std::string const & shape_str, bool advanced=True) -> entity_instance""" + return _ifcopenshell_wrapper.serialise(schema_name, shape_str, advanced) + +def tesselate(schema_name, shape_str, d): + r"""tesselate(std::string const & schema_name, std::string const & shape_str, double d) -> entity_instance""" + return _ifcopenshell_wrapper.tesselate(schema_name, shape_str, d) +class svg_line_segments(object): + r"""Proxy of C++ std::vector< std::array< svgfill::point_2,2 > > class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def iterator(self): + r"""iterator(svg_line_segments self) -> SwigPyIterator""" + return _ifcopenshell_wrapper.svg_line_segments_iterator(self) + def __iter__(self): + return self.iterator() + + def __nonzero__(self): + r"""__nonzero__(svg_line_segments self) -> bool""" + return _ifcopenshell_wrapper.svg_line_segments___nonzero__(self) + + def __bool__(self): + r"""__bool__(svg_line_segments self) -> bool""" + return _ifcopenshell_wrapper.svg_line_segments___bool__(self) + + def __len__(self): + r"""__len__(svg_line_segments self) -> std::vector< std::array< svgfill::point_2,2 > >::size_type""" + return _ifcopenshell_wrapper.svg_line_segments___len__(self) + + def __getslice__(self, i, j): + r"""__getslice__(svg_line_segments self, std::vector< std::array< svgfill::point_2,2 > >::difference_type i, std::vector< std::array< svgfill::point_2,2 > >::difference_type j) -> svg_line_segments""" + return _ifcopenshell_wrapper.svg_line_segments___getslice__(self, i, j) + + def __setslice__(self, *args): + r""" + __setslice__(svg_line_segments self, std::vector< std::array< svgfill::point_2,2 > >::difference_type i, std::vector< std::array< svgfill::point_2,2 > >::difference_type j) + __setslice__(svg_line_segments self, std::vector< std::array< svgfill::point_2,2 > >::difference_type i, std::vector< std::array< svgfill::point_2,2 > >::difference_type j, svg_line_segments v) + """ + return _ifcopenshell_wrapper.svg_line_segments___setslice__(self, *args) + + def __delslice__(self, i, j): + r"""__delslice__(svg_line_segments self, std::vector< std::array< svgfill::point_2,2 > >::difference_type i, std::vector< std::array< svgfill::point_2,2 > >::difference_type j)""" + return _ifcopenshell_wrapper.svg_line_segments___delslice__(self, i, j) + + def __delitem__(self, *args): + r""" + __delitem__(svg_line_segments self, std::vector< std::array< svgfill::point_2,2 > >::difference_type i) + __delitem__(svg_line_segments self, PySliceObject * slice) + """ + return _ifcopenshell_wrapper.svg_line_segments___delitem__(self, *args) + + def __getitem__(self, *args): + r""" + __getitem__(svg_line_segments self, PySliceObject * slice) -> svg_line_segments + __getitem__(svg_line_segments self, std::vector< std::array< svgfill::point_2,2 > >::difference_type i) -> line_segment + """ + return _ifcopenshell_wrapper.svg_line_segments___getitem__(self, *args) + + def __setitem__(self, *args): + r""" + __setitem__(svg_line_segments self, PySliceObject * slice, svg_line_segments v) + __setitem__(svg_line_segments self, PySliceObject * slice) + __setitem__(svg_line_segments self, std::vector< std::array< svgfill::point_2,2 > >::difference_type i, line_segment x) + """ + return _ifcopenshell_wrapper.svg_line_segments___setitem__(self, *args) + + def pop(self): + r"""pop(svg_line_segments self) -> line_segment""" + return _ifcopenshell_wrapper.svg_line_segments_pop(self) + + def append(self, x): + r"""append(svg_line_segments self, line_segment x)""" + return _ifcopenshell_wrapper.svg_line_segments_append(self, x) + + def empty(self): + r"""empty(svg_line_segments self) -> bool""" + return _ifcopenshell_wrapper.svg_line_segments_empty(self) + + def size(self): + r"""size(svg_line_segments self) -> std::vector< std::array< svgfill::point_2,2 > >::size_type""" + return _ifcopenshell_wrapper.svg_line_segments_size(self) + + def swap(self, v): + r"""swap(svg_line_segments self, svg_line_segments v)""" + return _ifcopenshell_wrapper.svg_line_segments_swap(self, v) + + def begin(self): + r"""begin(svg_line_segments self) -> std::vector< std::array< svgfill::point_2,2 > >::iterator""" + return _ifcopenshell_wrapper.svg_line_segments_begin(self) + + def end(self): + r"""end(svg_line_segments self) -> std::vector< std::array< svgfill::point_2,2 > >::iterator""" + return _ifcopenshell_wrapper.svg_line_segments_end(self) + + def rbegin(self): + r"""rbegin(svg_line_segments self) -> std::vector< std::array< svgfill::point_2,2 > >::reverse_iterator""" + return _ifcopenshell_wrapper.svg_line_segments_rbegin(self) + + def rend(self): + r"""rend(svg_line_segments self) -> std::vector< std::array< svgfill::point_2,2 > >::reverse_iterator""" + return _ifcopenshell_wrapper.svg_line_segments_rend(self) + + def clear(self): + r"""clear(svg_line_segments self)""" + return _ifcopenshell_wrapper.svg_line_segments_clear(self) + + def get_allocator(self): + r"""get_allocator(svg_line_segments self) -> std::vector< std::array< svgfill::point_2,2 > >::allocator_type""" + return _ifcopenshell_wrapper.svg_line_segments_get_allocator(self) + + def pop_back(self): + r"""pop_back(svg_line_segments self)""" + return _ifcopenshell_wrapper.svg_line_segments_pop_back(self) + + def erase(self, *args): + r""" + erase(svg_line_segments self, std::vector< std::array< svgfill::point_2,2 > >::iterator pos) -> std::vector< std::array< svgfill::point_2,2 > >::iterator + erase(svg_line_segments self, std::vector< std::array< svgfill::point_2,2 > >::iterator first, std::vector< std::array< svgfill::point_2,2 > >::iterator last) -> std::vector< std::array< svgfill::point_2,2 > >::iterator + """ + return _ifcopenshell_wrapper.svg_line_segments_erase(self, *args) + + def __init__(self, *args): + r""" + __init__(svg_line_segments self) -> svg_line_segments + __init__(svg_line_segments self, svg_line_segments other) -> svg_line_segments + __init__(svg_line_segments self, std::vector< std::array< svgfill::point_2,2 > >::size_type size) -> svg_line_segments + __init__(svg_line_segments self, std::vector< std::array< svgfill::point_2,2 > >::size_type size, line_segment value) -> svg_line_segments + """ + _ifcopenshell_wrapper.svg_line_segments_swiginit(self, _ifcopenshell_wrapper.new_svg_line_segments(*args)) + + def push_back(self, x): + r"""push_back(svg_line_segments self, line_segment x)""" + return _ifcopenshell_wrapper.svg_line_segments_push_back(self, x) + + def front(self): + r"""front(svg_line_segments self) -> line_segment""" + return _ifcopenshell_wrapper.svg_line_segments_front(self) + + def back(self): + r"""back(svg_line_segments self) -> line_segment""" + return _ifcopenshell_wrapper.svg_line_segments_back(self) + + def assign(self, n, x): + r"""assign(svg_line_segments self, std::vector< std::array< svgfill::point_2,2 > >::size_type n, line_segment x)""" + return _ifcopenshell_wrapper.svg_line_segments_assign(self, n, x) + + def resize(self, *args): + r""" + resize(svg_line_segments self, std::vector< std::array< svgfill::point_2,2 > >::size_type new_size) + resize(svg_line_segments self, std::vector< std::array< svgfill::point_2,2 > >::size_type new_size, line_segment x) + """ + return _ifcopenshell_wrapper.svg_line_segments_resize(self, *args) + + def insert(self, *args): + r""" + insert(svg_line_segments self, std::vector< std::array< svgfill::point_2,2 > >::iterator pos, line_segment x) -> std::vector< std::array< svgfill::point_2,2 > >::iterator + insert(svg_line_segments self, std::vector< std::array< svgfill::point_2,2 > >::iterator pos, std::vector< std::array< svgfill::point_2,2 > >::size_type n, line_segment x) + """ + return _ifcopenshell_wrapper.svg_line_segments_insert(self, *args) + + def reserve(self, n): + r"""reserve(svg_line_segments self, std::vector< std::array< svgfill::point_2,2 > >::size_type n)""" + return _ifcopenshell_wrapper.svg_line_segments_reserve(self, n) + + def capacity(self): + r"""capacity(svg_line_segments self) -> std::vector< std::array< svgfill::point_2,2 > >::size_type""" + return _ifcopenshell_wrapper.svg_line_segments_capacity(self) + __swig_destroy__ = _ifcopenshell_wrapper.delete_svg_line_segments + +# Register svg_line_segments in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.svg_line_segments_swigregister(svg_line_segments) + +class svg_groups_of_line_segments(object): + r"""Proxy of C++ std::vector< std::vector< std::array< svgfill::point_2,2 > > > class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def iterator(self): + r"""iterator(svg_groups_of_line_segments self) -> SwigPyIterator""" + return _ifcopenshell_wrapper.svg_groups_of_line_segments_iterator(self) + def __iter__(self): + return self.iterator() + + def __nonzero__(self): + r"""__nonzero__(svg_groups_of_line_segments self) -> bool""" + return _ifcopenshell_wrapper.svg_groups_of_line_segments___nonzero__(self) + + def __bool__(self): + r"""__bool__(svg_groups_of_line_segments self) -> bool""" + return _ifcopenshell_wrapper.svg_groups_of_line_segments___bool__(self) + + def __len__(self): + r"""__len__(svg_groups_of_line_segments self) -> std::vector< std::vector< std::array< svgfill::point_2,2 > > >::size_type""" + return _ifcopenshell_wrapper.svg_groups_of_line_segments___len__(self) + + def __getslice__(self, i, j): + r"""__getslice__(svg_groups_of_line_segments self, std::vector< std::vector< std::array< svgfill::point_2,2 > > >::difference_type i, std::vector< std::vector< std::array< svgfill::point_2,2 > > >::difference_type j) -> svg_groups_of_line_segments""" + return _ifcopenshell_wrapper.svg_groups_of_line_segments___getslice__(self, i, j) + + def __setslice__(self, *args): + r""" + __setslice__(svg_groups_of_line_segments self, std::vector< std::vector< std::array< svgfill::point_2,2 > > >::difference_type i, std::vector< std::vector< std::array< svgfill::point_2,2 > > >::difference_type j) + __setslice__(svg_groups_of_line_segments self, std::vector< std::vector< std::array< svgfill::point_2,2 > > >::difference_type i, std::vector< std::vector< std::array< svgfill::point_2,2 > > >::difference_type j, svg_groups_of_line_segments v) + """ + return _ifcopenshell_wrapper.svg_groups_of_line_segments___setslice__(self, *args) + + def __delslice__(self, i, j): + r"""__delslice__(svg_groups_of_line_segments self, std::vector< std::vector< std::array< svgfill::point_2,2 > > >::difference_type i, std::vector< std::vector< std::array< svgfill::point_2,2 > > >::difference_type j)""" + return _ifcopenshell_wrapper.svg_groups_of_line_segments___delslice__(self, i, j) + + def __delitem__(self, *args): + r""" + __delitem__(svg_groups_of_line_segments self, std::vector< std::vector< std::array< svgfill::point_2,2 > > >::difference_type i) + __delitem__(svg_groups_of_line_segments self, PySliceObject * slice) + """ + return _ifcopenshell_wrapper.svg_groups_of_line_segments___delitem__(self, *args) + + def __getitem__(self, *args): + r""" + __getitem__(svg_groups_of_line_segments self, PySliceObject * slice) -> svg_groups_of_line_segments + __getitem__(svg_groups_of_line_segments self, std::vector< std::vector< std::array< svgfill::point_2,2 > > >::difference_type i) -> svg_line_segments + """ + return _ifcopenshell_wrapper.svg_groups_of_line_segments___getitem__(self, *args) + + def __setitem__(self, *args): + r""" + __setitem__(svg_groups_of_line_segments self, PySliceObject * slice, svg_groups_of_line_segments v) + __setitem__(svg_groups_of_line_segments self, PySliceObject * slice) + __setitem__(svg_groups_of_line_segments self, std::vector< std::vector< std::array< svgfill::point_2,2 > > >::difference_type i, svg_line_segments x) + """ + return _ifcopenshell_wrapper.svg_groups_of_line_segments___setitem__(self, *args) + + def pop(self): + r"""pop(svg_groups_of_line_segments self) -> svg_line_segments""" + return _ifcopenshell_wrapper.svg_groups_of_line_segments_pop(self) + + def append(self, x): + r"""append(svg_groups_of_line_segments self, svg_line_segments x)""" + return _ifcopenshell_wrapper.svg_groups_of_line_segments_append(self, x) + + def empty(self): + r"""empty(svg_groups_of_line_segments self) -> bool""" + return _ifcopenshell_wrapper.svg_groups_of_line_segments_empty(self) + + def size(self): + r"""size(svg_groups_of_line_segments self) -> std::vector< std::vector< std::array< svgfill::point_2,2 > > >::size_type""" + return _ifcopenshell_wrapper.svg_groups_of_line_segments_size(self) + + def swap(self, v): + r"""swap(svg_groups_of_line_segments self, svg_groups_of_line_segments v)""" + return _ifcopenshell_wrapper.svg_groups_of_line_segments_swap(self, v) + + def begin(self): + r"""begin(svg_groups_of_line_segments self) -> std::vector< std::vector< std::array< svgfill::point_2,2 > > >::iterator""" + return _ifcopenshell_wrapper.svg_groups_of_line_segments_begin(self) + + def end(self): + r"""end(svg_groups_of_line_segments self) -> std::vector< std::vector< std::array< svgfill::point_2,2 > > >::iterator""" + return _ifcopenshell_wrapper.svg_groups_of_line_segments_end(self) + + def rbegin(self): + r"""rbegin(svg_groups_of_line_segments self) -> std::vector< std::vector< std::array< svgfill::point_2,2 > > >::reverse_iterator""" + return _ifcopenshell_wrapper.svg_groups_of_line_segments_rbegin(self) + + def rend(self): + r"""rend(svg_groups_of_line_segments self) -> std::vector< std::vector< std::array< svgfill::point_2,2 > > >::reverse_iterator""" + return _ifcopenshell_wrapper.svg_groups_of_line_segments_rend(self) + + def clear(self): + r"""clear(svg_groups_of_line_segments self)""" + return _ifcopenshell_wrapper.svg_groups_of_line_segments_clear(self) + + def get_allocator(self): + r"""get_allocator(svg_groups_of_line_segments self) -> std::vector< std::vector< std::array< svgfill::point_2,2 > > >::allocator_type""" + return _ifcopenshell_wrapper.svg_groups_of_line_segments_get_allocator(self) + + def pop_back(self): + r"""pop_back(svg_groups_of_line_segments self)""" + return _ifcopenshell_wrapper.svg_groups_of_line_segments_pop_back(self) + + def erase(self, *args): + r""" + erase(svg_groups_of_line_segments self, std::vector< std::vector< std::array< svgfill::point_2,2 > > >::iterator pos) -> std::vector< std::vector< std::array< svgfill::point_2,2 > > >::iterator + erase(svg_groups_of_line_segments self, std::vector< std::vector< std::array< svgfill::point_2,2 > > >::iterator first, std::vector< std::vector< std::array< svgfill::point_2,2 > > >::iterator last) -> std::vector< std::vector< std::array< svgfill::point_2,2 > > >::iterator + """ + return _ifcopenshell_wrapper.svg_groups_of_line_segments_erase(self, *args) + + def __init__(self, *args): + r""" + __init__(svg_groups_of_line_segments self) -> svg_groups_of_line_segments + __init__(svg_groups_of_line_segments self, svg_groups_of_line_segments other) -> svg_groups_of_line_segments + __init__(svg_groups_of_line_segments self, std::vector< std::vector< std::array< svgfill::point_2,2 > > >::size_type size) -> svg_groups_of_line_segments + __init__(svg_groups_of_line_segments self, std::vector< std::vector< std::array< svgfill::point_2,2 > > >::size_type size, svg_line_segments value) -> svg_groups_of_line_segments + """ + _ifcopenshell_wrapper.svg_groups_of_line_segments_swiginit(self, _ifcopenshell_wrapper.new_svg_groups_of_line_segments(*args)) + + def push_back(self, x): + r"""push_back(svg_groups_of_line_segments self, svg_line_segments x)""" + return _ifcopenshell_wrapper.svg_groups_of_line_segments_push_back(self, x) + + def front(self): + r"""front(svg_groups_of_line_segments self) -> svg_line_segments""" + return _ifcopenshell_wrapper.svg_groups_of_line_segments_front(self) + + def back(self): + r"""back(svg_groups_of_line_segments self) -> svg_line_segments""" + return _ifcopenshell_wrapper.svg_groups_of_line_segments_back(self) + + def assign(self, n, x): + r"""assign(svg_groups_of_line_segments self, std::vector< std::vector< std::array< svgfill::point_2,2 > > >::size_type n, svg_line_segments x)""" + return _ifcopenshell_wrapper.svg_groups_of_line_segments_assign(self, n, x) + + def resize(self, *args): + r""" + resize(svg_groups_of_line_segments self, std::vector< std::vector< std::array< svgfill::point_2,2 > > >::size_type new_size) + resize(svg_groups_of_line_segments self, std::vector< std::vector< std::array< svgfill::point_2,2 > > >::size_type new_size, svg_line_segments x) + """ + return _ifcopenshell_wrapper.svg_groups_of_line_segments_resize(self, *args) + + def insert(self, *args): + r""" + insert(svg_groups_of_line_segments self, std::vector< std::vector< std::array< svgfill::point_2,2 > > >::iterator pos, svg_line_segments x) -> std::vector< std::vector< std::array< svgfill::point_2,2 > > >::iterator + insert(svg_groups_of_line_segments self, std::vector< std::vector< std::array< svgfill::point_2,2 > > >::iterator pos, std::vector< std::vector< std::array< svgfill::point_2,2 > > >::size_type n, svg_line_segments x) + """ + return _ifcopenshell_wrapper.svg_groups_of_line_segments_insert(self, *args) + + def reserve(self, n): + r"""reserve(svg_groups_of_line_segments self, std::vector< std::vector< std::array< svgfill::point_2,2 > > >::size_type n)""" + return _ifcopenshell_wrapper.svg_groups_of_line_segments_reserve(self, n) + + def capacity(self): + r"""capacity(svg_groups_of_line_segments self) -> std::vector< std::vector< std::array< svgfill::point_2,2 > > >::size_type""" + return _ifcopenshell_wrapper.svg_groups_of_line_segments_capacity(self) + __swig_destroy__ = _ifcopenshell_wrapper.delete_svg_groups_of_line_segments + +# Register svg_groups_of_line_segments in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.svg_groups_of_line_segments_swigregister(svg_groups_of_line_segments) + +class svg_point(object): + r"""Proxy of C++ std::array< double,2 > class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def iterator(self): + r"""iterator(svg_point self) -> SwigPyIterator""" + return _ifcopenshell_wrapper.svg_point_iterator(self) + def __iter__(self): + return self.iterator() + + def __nonzero__(self): + r"""__nonzero__(svg_point self) -> bool""" + return _ifcopenshell_wrapper.svg_point___nonzero__(self) + + def __bool__(self): + r"""__bool__(svg_point self) -> bool""" + return _ifcopenshell_wrapper.svg_point___bool__(self) + + def __len__(self): + r"""__len__(svg_point self) -> std::array< double,2 >::size_type""" + return _ifcopenshell_wrapper.svg_point___len__(self) + + def __getslice__(self, i, j): + r"""__getslice__(svg_point self, std::array< double,2 >::difference_type i, std::array< double,2 >::difference_type j) -> svg_point""" + return _ifcopenshell_wrapper.svg_point___getslice__(self, i, j) + + def __setslice__(self, *args): + r""" + __setslice__(svg_point self, std::array< double,2 >::difference_type i, std::array< double,2 >::difference_type j) + __setslice__(svg_point self, std::array< double,2 >::difference_type i, std::array< double,2 >::difference_type j, svg_point v) + """ + return _ifcopenshell_wrapper.svg_point___setslice__(self, *args) + + def __delslice__(self, i, j): + r"""__delslice__(svg_point self, std::array< double,2 >::difference_type i, std::array< double,2 >::difference_type j)""" + return _ifcopenshell_wrapper.svg_point___delslice__(self, i, j) + + def __delitem__(self, *args): + r""" + __delitem__(svg_point self, std::array< double,2 >::difference_type i) + __delitem__(svg_point self, PySliceObject * slice) + """ + return _ifcopenshell_wrapper.svg_point___delitem__(self, *args) + + def __getitem__(self, *args): + r""" + __getitem__(svg_point self, PySliceObject * slice) -> svg_point + __getitem__(svg_point self, std::array< double,2 >::difference_type i) -> std::array< double,2 >::value_type const & + """ + return _ifcopenshell_wrapper.svg_point___getitem__(self, *args) + + def __setitem__(self, *args): + r""" + __setitem__(svg_point self, PySliceObject * slice, svg_point v) + __setitem__(svg_point self, PySliceObject * slice) + __setitem__(svg_point self, std::array< double,2 >::difference_type i, std::array< double,2 >::value_type const & x) + """ + return _ifcopenshell_wrapper.svg_point___setitem__(self, *args) + + def __init__(self, *args): + r""" + __init__(svg_point self) -> svg_point + __init__(svg_point self, svg_point other) -> svg_point + """ + _ifcopenshell_wrapper.svg_point_swiginit(self, _ifcopenshell_wrapper.new_svg_point(*args)) + + def empty(self): + r"""empty(svg_point self) -> bool""" + return _ifcopenshell_wrapper.svg_point_empty(self) + + def size(self): + r"""size(svg_point self) -> std::array< double,2 >::size_type""" + return _ifcopenshell_wrapper.svg_point_size(self) + + def swap(self, v): + r"""swap(svg_point self, svg_point v)""" + return _ifcopenshell_wrapper.svg_point_swap(self, v) + + def begin(self): + r"""begin(svg_point self) -> std::array< double,2 >::iterator""" + return _ifcopenshell_wrapper.svg_point_begin(self) + + def end(self): + r"""end(svg_point self) -> std::array< double,2 >::iterator""" + return _ifcopenshell_wrapper.svg_point_end(self) + + def rbegin(self): + r"""rbegin(svg_point self) -> std::array< double,2 >::reverse_iterator""" + return _ifcopenshell_wrapper.svg_point_rbegin(self) + + def rend(self): + r"""rend(svg_point self) -> std::array< double,2 >::reverse_iterator""" + return _ifcopenshell_wrapper.svg_point_rend(self) + + def front(self): + r"""front(svg_point self) -> std::array< double,2 >::value_type const &""" + return _ifcopenshell_wrapper.svg_point_front(self) + + def back(self): + r"""back(svg_point self) -> std::array< double,2 >::value_type const &""" + return _ifcopenshell_wrapper.svg_point_back(self) + + def fill(self, u): + r"""fill(svg_point self, std::array< double,2 >::value_type const & u)""" + return _ifcopenshell_wrapper.svg_point_fill(self, u) + __swig_destroy__ = _ifcopenshell_wrapper.delete_svg_point + +# Register svg_point in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.svg_point_swigregister(svg_point) + +class line_segment(object): + r"""Proxy of C++ std::array< svgfill::point_2,2 > class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def iterator(self): + r"""iterator(line_segment self) -> SwigPyIterator""" + return _ifcopenshell_wrapper.line_segment_iterator(self) + def __iter__(self): + return self.iterator() + + def __nonzero__(self): + r"""__nonzero__(line_segment self) -> bool""" + return _ifcopenshell_wrapper.line_segment___nonzero__(self) + + def __bool__(self): + r"""__bool__(line_segment self) -> bool""" + return _ifcopenshell_wrapper.line_segment___bool__(self) + + def __len__(self): + r"""__len__(line_segment self) -> std::array< svgfill::point_2,2 >::size_type""" + return _ifcopenshell_wrapper.line_segment___len__(self) + + def __getslice__(self, i, j): + r"""__getslice__(line_segment self, std::array< svgfill::point_2,2 >::difference_type i, std::array< svgfill::point_2,2 >::difference_type j) -> line_segment""" + return _ifcopenshell_wrapper.line_segment___getslice__(self, i, j) + + def __setslice__(self, *args): + r""" + __setslice__(line_segment self, std::array< svgfill::point_2,2 >::difference_type i, std::array< svgfill::point_2,2 >::difference_type j) + __setslice__(line_segment self, std::array< svgfill::point_2,2 >::difference_type i, std::array< svgfill::point_2,2 >::difference_type j, line_segment v) + """ + return _ifcopenshell_wrapper.line_segment___setslice__(self, *args) + + def __delslice__(self, i, j): + r"""__delslice__(line_segment self, std::array< svgfill::point_2,2 >::difference_type i, std::array< svgfill::point_2,2 >::difference_type j)""" + return _ifcopenshell_wrapper.line_segment___delslice__(self, i, j) + + def __delitem__(self, *args): + r""" + __delitem__(line_segment self, std::array< svgfill::point_2,2 >::difference_type i) + __delitem__(line_segment self, PySliceObject * slice) + """ + return _ifcopenshell_wrapper.line_segment___delitem__(self, *args) + + def __getitem__(self, *args): + r""" + __getitem__(line_segment self, PySliceObject * slice) -> line_segment + __getitem__(line_segment self, std::array< svgfill::point_2,2 >::difference_type i) -> std::array< svgfill::point_2,2 >::value_type const & + """ + return _ifcopenshell_wrapper.line_segment___getitem__(self, *args) + + def __setitem__(self, *args): + r""" + __setitem__(line_segment self, PySliceObject * slice, line_segment v) + __setitem__(line_segment self, PySliceObject * slice) + __setitem__(line_segment self, std::array< svgfill::point_2,2 >::difference_type i, std::array< svgfill::point_2,2 >::value_type const & x) + """ + return _ifcopenshell_wrapper.line_segment___setitem__(self, *args) + + def __init__(self, *args): + r""" + __init__(line_segment self) -> line_segment + __init__(line_segment self, line_segment other) -> line_segment + """ + _ifcopenshell_wrapper.line_segment_swiginit(self, _ifcopenshell_wrapper.new_line_segment(*args)) + + def empty(self): + r"""empty(line_segment self) -> bool""" + return _ifcopenshell_wrapper.line_segment_empty(self) + + def size(self): + r"""size(line_segment self) -> std::array< svgfill::point_2,2 >::size_type""" + return _ifcopenshell_wrapper.line_segment_size(self) + + def swap(self, v): + r"""swap(line_segment self, line_segment v)""" + return _ifcopenshell_wrapper.line_segment_swap(self, v) + + def begin(self): + r"""begin(line_segment self) -> std::array< svgfill::point_2,2 >::iterator""" + return _ifcopenshell_wrapper.line_segment_begin(self) + + def end(self): + r"""end(line_segment self) -> std::array< svgfill::point_2,2 >::iterator""" + return _ifcopenshell_wrapper.line_segment_end(self) + + def rbegin(self): + r"""rbegin(line_segment self) -> std::array< svgfill::point_2,2 >::reverse_iterator""" + return _ifcopenshell_wrapper.line_segment_rbegin(self) + + def rend(self): + r"""rend(line_segment self) -> std::array< svgfill::point_2,2 >::reverse_iterator""" + return _ifcopenshell_wrapper.line_segment_rend(self) + + def front(self): + r"""front(line_segment self) -> std::array< svgfill::point_2,2 >::value_type const &""" + return _ifcopenshell_wrapper.line_segment_front(self) + + def back(self): + r"""back(line_segment self) -> std::array< svgfill::point_2,2 >::value_type const &""" + return _ifcopenshell_wrapper.line_segment_back(self) + + def fill(self, u): + r"""fill(line_segment self, std::array< svgfill::point_2,2 >::value_type const & u)""" + return _ifcopenshell_wrapper.line_segment_fill(self, u) + __swig_destroy__ = _ifcopenshell_wrapper.delete_line_segment + +# Register line_segment in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.line_segment_swigregister(line_segment) + +class svg_polygons(object): + r"""Proxy of C++ std::vector< svgfill::polygon_2 > class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def iterator(self): + r"""iterator(svg_polygons self) -> SwigPyIterator""" + return _ifcopenshell_wrapper.svg_polygons_iterator(self) + def __iter__(self): + return self.iterator() + + def __nonzero__(self): + r"""__nonzero__(svg_polygons self) -> bool""" + return _ifcopenshell_wrapper.svg_polygons___nonzero__(self) + + def __bool__(self): + r"""__bool__(svg_polygons self) -> bool""" + return _ifcopenshell_wrapper.svg_polygons___bool__(self) + + def __len__(self): + r"""__len__(svg_polygons self) -> std::vector< svgfill::polygon_2 >::size_type""" + return _ifcopenshell_wrapper.svg_polygons___len__(self) + + def __getslice__(self, i, j): + r"""__getslice__(svg_polygons self, std::vector< svgfill::polygon_2 >::difference_type i, std::vector< svgfill::polygon_2 >::difference_type j) -> svg_polygons""" + return _ifcopenshell_wrapper.svg_polygons___getslice__(self, i, j) + + def __setslice__(self, *args): + r""" + __setslice__(svg_polygons self, std::vector< svgfill::polygon_2 >::difference_type i, std::vector< svgfill::polygon_2 >::difference_type j) + __setslice__(svg_polygons self, std::vector< svgfill::polygon_2 >::difference_type i, std::vector< svgfill::polygon_2 >::difference_type j, svg_polygons v) + """ + return _ifcopenshell_wrapper.svg_polygons___setslice__(self, *args) + + def __delslice__(self, i, j): + r"""__delslice__(svg_polygons self, std::vector< svgfill::polygon_2 >::difference_type i, std::vector< svgfill::polygon_2 >::difference_type j)""" + return _ifcopenshell_wrapper.svg_polygons___delslice__(self, i, j) + + def __delitem__(self, *args): + r""" + __delitem__(svg_polygons self, std::vector< svgfill::polygon_2 >::difference_type i) + __delitem__(svg_polygons self, PySliceObject * slice) + """ + return _ifcopenshell_wrapper.svg_polygons___delitem__(self, *args) + + def __getitem__(self, *args): + r""" + __getitem__(svg_polygons self, PySliceObject * slice) -> svg_polygons + __getitem__(svg_polygons self, std::vector< svgfill::polygon_2 >::difference_type i) -> polygon_2 + """ + return _ifcopenshell_wrapper.svg_polygons___getitem__(self, *args) + + def __setitem__(self, *args): + r""" + __setitem__(svg_polygons self, PySliceObject * slice, svg_polygons v) + __setitem__(svg_polygons self, PySliceObject * slice) + __setitem__(svg_polygons self, std::vector< svgfill::polygon_2 >::difference_type i, polygon_2 x) + """ + return _ifcopenshell_wrapper.svg_polygons___setitem__(self, *args) + + def pop(self): + r"""pop(svg_polygons self) -> polygon_2""" + return _ifcopenshell_wrapper.svg_polygons_pop(self) + + def append(self, x): + r"""append(svg_polygons self, polygon_2 x)""" + return _ifcopenshell_wrapper.svg_polygons_append(self, x) + + def empty(self): + r"""empty(svg_polygons self) -> bool""" + return _ifcopenshell_wrapper.svg_polygons_empty(self) + + def size(self): + r"""size(svg_polygons self) -> std::vector< svgfill::polygon_2 >::size_type""" + return _ifcopenshell_wrapper.svg_polygons_size(self) + + def swap(self, v): + r"""swap(svg_polygons self, svg_polygons v)""" + return _ifcopenshell_wrapper.svg_polygons_swap(self, v) + + def begin(self): + r"""begin(svg_polygons self) -> std::vector< svgfill::polygon_2 >::iterator""" + return _ifcopenshell_wrapper.svg_polygons_begin(self) + + def end(self): + r"""end(svg_polygons self) -> std::vector< svgfill::polygon_2 >::iterator""" + return _ifcopenshell_wrapper.svg_polygons_end(self) + + def rbegin(self): + r"""rbegin(svg_polygons self) -> std::vector< svgfill::polygon_2 >::reverse_iterator""" + return _ifcopenshell_wrapper.svg_polygons_rbegin(self) + + def rend(self): + r"""rend(svg_polygons self) -> std::vector< svgfill::polygon_2 >::reverse_iterator""" + return _ifcopenshell_wrapper.svg_polygons_rend(self) + + def clear(self): + r"""clear(svg_polygons self)""" + return _ifcopenshell_wrapper.svg_polygons_clear(self) + + def get_allocator(self): + r"""get_allocator(svg_polygons self) -> std::vector< svgfill::polygon_2 >::allocator_type""" + return _ifcopenshell_wrapper.svg_polygons_get_allocator(self) + + def pop_back(self): + r"""pop_back(svg_polygons self)""" + return _ifcopenshell_wrapper.svg_polygons_pop_back(self) + + def erase(self, *args): + r""" + erase(svg_polygons self, std::vector< svgfill::polygon_2 >::iterator pos) -> std::vector< svgfill::polygon_2 >::iterator + erase(svg_polygons self, std::vector< svgfill::polygon_2 >::iterator first, std::vector< svgfill::polygon_2 >::iterator last) -> std::vector< svgfill::polygon_2 >::iterator + """ + return _ifcopenshell_wrapper.svg_polygons_erase(self, *args) + + def __init__(self, *args): + r""" + __init__(svg_polygons self) -> svg_polygons + __init__(svg_polygons self, svg_polygons other) -> svg_polygons + __init__(svg_polygons self, std::vector< svgfill::polygon_2 >::size_type size) -> svg_polygons + __init__(svg_polygons self, std::vector< svgfill::polygon_2 >::size_type size, polygon_2 value) -> svg_polygons + """ + _ifcopenshell_wrapper.svg_polygons_swiginit(self, _ifcopenshell_wrapper.new_svg_polygons(*args)) + + def push_back(self, x): + r"""push_back(svg_polygons self, polygon_2 x)""" + return _ifcopenshell_wrapper.svg_polygons_push_back(self, x) + + def front(self): + r"""front(svg_polygons self) -> polygon_2""" + return _ifcopenshell_wrapper.svg_polygons_front(self) + + def back(self): + r"""back(svg_polygons self) -> polygon_2""" + return _ifcopenshell_wrapper.svg_polygons_back(self) + + def assign(self, n, x): + r"""assign(svg_polygons self, std::vector< svgfill::polygon_2 >::size_type n, polygon_2 x)""" + return _ifcopenshell_wrapper.svg_polygons_assign(self, n, x) + + def resize(self, *args): + r""" + resize(svg_polygons self, std::vector< svgfill::polygon_2 >::size_type new_size) + resize(svg_polygons self, std::vector< svgfill::polygon_2 >::size_type new_size, polygon_2 x) + """ + return _ifcopenshell_wrapper.svg_polygons_resize(self, *args) + + def insert(self, *args): + r""" + insert(svg_polygons self, std::vector< svgfill::polygon_2 >::iterator pos, polygon_2 x) -> std::vector< svgfill::polygon_2 >::iterator + insert(svg_polygons self, std::vector< svgfill::polygon_2 >::iterator pos, std::vector< svgfill::polygon_2 >::size_type n, polygon_2 x) + """ + return _ifcopenshell_wrapper.svg_polygons_insert(self, *args) + + def reserve(self, n): + r"""reserve(svg_polygons self, std::vector< svgfill::polygon_2 >::size_type n)""" + return _ifcopenshell_wrapper.svg_polygons_reserve(self, n) + + def capacity(self): + r"""capacity(svg_polygons self) -> std::vector< svgfill::polygon_2 >::size_type""" + return _ifcopenshell_wrapper.svg_polygons_capacity(self) + __swig_destroy__ = _ifcopenshell_wrapper.delete_svg_polygons + +# Register svg_polygons in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.svg_polygons_swigregister(svg_polygons) + +class svg_groups_of_polygons(object): + r"""Proxy of C++ std::vector< std::vector< svgfill::polygon_2 > > class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def iterator(self): + r"""iterator(svg_groups_of_polygons self) -> SwigPyIterator""" + return _ifcopenshell_wrapper.svg_groups_of_polygons_iterator(self) + def __iter__(self): + return self.iterator() + + def __nonzero__(self): + r"""__nonzero__(svg_groups_of_polygons self) -> bool""" + return _ifcopenshell_wrapper.svg_groups_of_polygons___nonzero__(self) + + def __bool__(self): + r"""__bool__(svg_groups_of_polygons self) -> bool""" + return _ifcopenshell_wrapper.svg_groups_of_polygons___bool__(self) + + def __len__(self): + r"""__len__(svg_groups_of_polygons self) -> std::vector< std::vector< svgfill::polygon_2 > >::size_type""" + return _ifcopenshell_wrapper.svg_groups_of_polygons___len__(self) + + def __getslice__(self, i, j): + r"""__getslice__(svg_groups_of_polygons self, std::vector< std::vector< svgfill::polygon_2 > >::difference_type i, std::vector< std::vector< svgfill::polygon_2 > >::difference_type j) -> svg_groups_of_polygons""" + return _ifcopenshell_wrapper.svg_groups_of_polygons___getslice__(self, i, j) + + def __setslice__(self, *args): + r""" + __setslice__(svg_groups_of_polygons self, std::vector< std::vector< svgfill::polygon_2 > >::difference_type i, std::vector< std::vector< svgfill::polygon_2 > >::difference_type j) + __setslice__(svg_groups_of_polygons self, std::vector< std::vector< svgfill::polygon_2 > >::difference_type i, std::vector< std::vector< svgfill::polygon_2 > >::difference_type j, svg_groups_of_polygons v) + """ + return _ifcopenshell_wrapper.svg_groups_of_polygons___setslice__(self, *args) + + def __delslice__(self, i, j): + r"""__delslice__(svg_groups_of_polygons self, std::vector< std::vector< svgfill::polygon_2 > >::difference_type i, std::vector< std::vector< svgfill::polygon_2 > >::difference_type j)""" + return _ifcopenshell_wrapper.svg_groups_of_polygons___delslice__(self, i, j) + + def __delitem__(self, *args): + r""" + __delitem__(svg_groups_of_polygons self, std::vector< std::vector< svgfill::polygon_2 > >::difference_type i) + __delitem__(svg_groups_of_polygons self, PySliceObject * slice) + """ + return _ifcopenshell_wrapper.svg_groups_of_polygons___delitem__(self, *args) + + def __getitem__(self, *args): + r""" + __getitem__(svg_groups_of_polygons self, PySliceObject * slice) -> svg_groups_of_polygons + __getitem__(svg_groups_of_polygons self, std::vector< std::vector< svgfill::polygon_2 > >::difference_type i) -> svg_polygons + """ + return _ifcopenshell_wrapper.svg_groups_of_polygons___getitem__(self, *args) + + def __setitem__(self, *args): + r""" + __setitem__(svg_groups_of_polygons self, PySliceObject * slice, svg_groups_of_polygons v) + __setitem__(svg_groups_of_polygons self, PySliceObject * slice) + __setitem__(svg_groups_of_polygons self, std::vector< std::vector< svgfill::polygon_2 > >::difference_type i, svg_polygons x) + """ + return _ifcopenshell_wrapper.svg_groups_of_polygons___setitem__(self, *args) + + def pop(self): + r"""pop(svg_groups_of_polygons self) -> svg_polygons""" + return _ifcopenshell_wrapper.svg_groups_of_polygons_pop(self) + + def append(self, x): + r"""append(svg_groups_of_polygons self, svg_polygons x)""" + return _ifcopenshell_wrapper.svg_groups_of_polygons_append(self, x) + + def empty(self): + r"""empty(svg_groups_of_polygons self) -> bool""" + return _ifcopenshell_wrapper.svg_groups_of_polygons_empty(self) + + def size(self): + r"""size(svg_groups_of_polygons self) -> std::vector< std::vector< svgfill::polygon_2 > >::size_type""" + return _ifcopenshell_wrapper.svg_groups_of_polygons_size(self) + + def swap(self, v): + r"""swap(svg_groups_of_polygons self, svg_groups_of_polygons v)""" + return _ifcopenshell_wrapper.svg_groups_of_polygons_swap(self, v) + + def begin(self): + r"""begin(svg_groups_of_polygons self) -> std::vector< std::vector< svgfill::polygon_2 > >::iterator""" + return _ifcopenshell_wrapper.svg_groups_of_polygons_begin(self) + + def end(self): + r"""end(svg_groups_of_polygons self) -> std::vector< std::vector< svgfill::polygon_2 > >::iterator""" + return _ifcopenshell_wrapper.svg_groups_of_polygons_end(self) + + def rbegin(self): + r"""rbegin(svg_groups_of_polygons self) -> std::vector< std::vector< svgfill::polygon_2 > >::reverse_iterator""" + return _ifcopenshell_wrapper.svg_groups_of_polygons_rbegin(self) + + def rend(self): + r"""rend(svg_groups_of_polygons self) -> std::vector< std::vector< svgfill::polygon_2 > >::reverse_iterator""" + return _ifcopenshell_wrapper.svg_groups_of_polygons_rend(self) + + def clear(self): + r"""clear(svg_groups_of_polygons self)""" + return _ifcopenshell_wrapper.svg_groups_of_polygons_clear(self) + + def get_allocator(self): + r"""get_allocator(svg_groups_of_polygons self) -> std::vector< std::vector< svgfill::polygon_2 > >::allocator_type""" + return _ifcopenshell_wrapper.svg_groups_of_polygons_get_allocator(self) + + def pop_back(self): + r"""pop_back(svg_groups_of_polygons self)""" + return _ifcopenshell_wrapper.svg_groups_of_polygons_pop_back(self) + + def erase(self, *args): + r""" + erase(svg_groups_of_polygons self, std::vector< std::vector< svgfill::polygon_2 > >::iterator pos) -> std::vector< std::vector< svgfill::polygon_2 > >::iterator + erase(svg_groups_of_polygons self, std::vector< std::vector< svgfill::polygon_2 > >::iterator first, std::vector< std::vector< svgfill::polygon_2 > >::iterator last) -> std::vector< std::vector< svgfill::polygon_2 > >::iterator + """ + return _ifcopenshell_wrapper.svg_groups_of_polygons_erase(self, *args) + + def __init__(self, *args): + r""" + __init__(svg_groups_of_polygons self) -> svg_groups_of_polygons + __init__(svg_groups_of_polygons self, svg_groups_of_polygons other) -> svg_groups_of_polygons + __init__(svg_groups_of_polygons self, std::vector< std::vector< svgfill::polygon_2 > >::size_type size) -> svg_groups_of_polygons + __init__(svg_groups_of_polygons self, std::vector< std::vector< svgfill::polygon_2 > >::size_type size, svg_polygons value) -> svg_groups_of_polygons + """ + _ifcopenshell_wrapper.svg_groups_of_polygons_swiginit(self, _ifcopenshell_wrapper.new_svg_groups_of_polygons(*args)) + + def push_back(self, x): + r"""push_back(svg_groups_of_polygons self, svg_polygons x)""" + return _ifcopenshell_wrapper.svg_groups_of_polygons_push_back(self, x) + + def front(self): + r"""front(svg_groups_of_polygons self) -> svg_polygons""" + return _ifcopenshell_wrapper.svg_groups_of_polygons_front(self) + + def back(self): + r"""back(svg_groups_of_polygons self) -> svg_polygons""" + return _ifcopenshell_wrapper.svg_groups_of_polygons_back(self) + + def assign(self, n, x): + r"""assign(svg_groups_of_polygons self, std::vector< std::vector< svgfill::polygon_2 > >::size_type n, svg_polygons x)""" + return _ifcopenshell_wrapper.svg_groups_of_polygons_assign(self, n, x) + + def resize(self, *args): + r""" + resize(svg_groups_of_polygons self, std::vector< std::vector< svgfill::polygon_2 > >::size_type new_size) + resize(svg_groups_of_polygons self, std::vector< std::vector< svgfill::polygon_2 > >::size_type new_size, svg_polygons x) + """ + return _ifcopenshell_wrapper.svg_groups_of_polygons_resize(self, *args) + + def insert(self, *args): + r""" + insert(svg_groups_of_polygons self, std::vector< std::vector< svgfill::polygon_2 > >::iterator pos, svg_polygons x) -> std::vector< std::vector< svgfill::polygon_2 > >::iterator + insert(svg_groups_of_polygons self, std::vector< std::vector< svgfill::polygon_2 > >::iterator pos, std::vector< std::vector< svgfill::polygon_2 > >::size_type n, svg_polygons x) + """ + return _ifcopenshell_wrapper.svg_groups_of_polygons_insert(self, *args) + + def reserve(self, n): + r"""reserve(svg_groups_of_polygons self, std::vector< std::vector< svgfill::polygon_2 > >::size_type n)""" + return _ifcopenshell_wrapper.svg_groups_of_polygons_reserve(self, n) + + def capacity(self): + r"""capacity(svg_groups_of_polygons self) -> std::vector< std::vector< svgfill::polygon_2 > >::size_type""" + return _ifcopenshell_wrapper.svg_groups_of_polygons_capacity(self) + __swig_destroy__ = _ifcopenshell_wrapper.delete_svg_groups_of_polygons + +# Register svg_groups_of_polygons in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.svg_groups_of_polygons_swigregister(svg_groups_of_polygons) + +class svg_loop(object): + r"""Proxy of C++ std::vector< std::array< double,2 > > class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def iterator(self): + r"""iterator(svg_loop self) -> SwigPyIterator""" + return _ifcopenshell_wrapper.svg_loop_iterator(self) + def __iter__(self): + return self.iterator() + + def __nonzero__(self): + r"""__nonzero__(svg_loop self) -> bool""" + return _ifcopenshell_wrapper.svg_loop___nonzero__(self) + + def __bool__(self): + r"""__bool__(svg_loop self) -> bool""" + return _ifcopenshell_wrapper.svg_loop___bool__(self) + + def __len__(self): + r"""__len__(svg_loop self) -> std::vector< std::array< double,2 > >::size_type""" + return _ifcopenshell_wrapper.svg_loop___len__(self) + + def __getslice__(self, i, j): + r"""__getslice__(svg_loop self, std::vector< std::array< double,2 > >::difference_type i, std::vector< std::array< double,2 > >::difference_type j) -> svg_loop""" + return _ifcopenshell_wrapper.svg_loop___getslice__(self, i, j) + + def __setslice__(self, *args): + r""" + __setslice__(svg_loop self, std::vector< std::array< double,2 > >::difference_type i, std::vector< std::array< double,2 > >::difference_type j) + __setslice__(svg_loop self, std::vector< std::array< double,2 > >::difference_type i, std::vector< std::array< double,2 > >::difference_type j, svg_loop v) + """ + return _ifcopenshell_wrapper.svg_loop___setslice__(self, *args) + + def __delslice__(self, i, j): + r"""__delslice__(svg_loop self, std::vector< std::array< double,2 > >::difference_type i, std::vector< std::array< double,2 > >::difference_type j)""" + return _ifcopenshell_wrapper.svg_loop___delslice__(self, i, j) + + def __delitem__(self, *args): + r""" + __delitem__(svg_loop self, std::vector< std::array< double,2 > >::difference_type i) + __delitem__(svg_loop self, PySliceObject * slice) + """ + return _ifcopenshell_wrapper.svg_loop___delitem__(self, *args) + + def __getitem__(self, *args): + r""" + __getitem__(svg_loop self, PySliceObject * slice) -> svg_loop + __getitem__(svg_loop self, std::vector< std::array< double,2 > >::difference_type i) -> svg_point + """ + return _ifcopenshell_wrapper.svg_loop___getitem__(self, *args) + + def __setitem__(self, *args): + r""" + __setitem__(svg_loop self, PySliceObject * slice, svg_loop v) + __setitem__(svg_loop self, PySliceObject * slice) + __setitem__(svg_loop self, std::vector< std::array< double,2 > >::difference_type i, svg_point x) + """ + return _ifcopenshell_wrapper.svg_loop___setitem__(self, *args) + + def pop(self): + r"""pop(svg_loop self) -> svg_point""" + return _ifcopenshell_wrapper.svg_loop_pop(self) + + def append(self, x): + r"""append(svg_loop self, svg_point x)""" + return _ifcopenshell_wrapper.svg_loop_append(self, x) + + def empty(self): + r"""empty(svg_loop self) -> bool""" + return _ifcopenshell_wrapper.svg_loop_empty(self) + + def size(self): + r"""size(svg_loop self) -> std::vector< std::array< double,2 > >::size_type""" + return _ifcopenshell_wrapper.svg_loop_size(self) + + def swap(self, v): + r"""swap(svg_loop self, svg_loop v)""" + return _ifcopenshell_wrapper.svg_loop_swap(self, v) + + def begin(self): + r"""begin(svg_loop self) -> std::vector< std::array< double,2 > >::iterator""" + return _ifcopenshell_wrapper.svg_loop_begin(self) + + def end(self): + r"""end(svg_loop self) -> std::vector< std::array< double,2 > >::iterator""" + return _ifcopenshell_wrapper.svg_loop_end(self) + + def rbegin(self): + r"""rbegin(svg_loop self) -> std::vector< std::array< double,2 > >::reverse_iterator""" + return _ifcopenshell_wrapper.svg_loop_rbegin(self) + + def rend(self): + r"""rend(svg_loop self) -> std::vector< std::array< double,2 > >::reverse_iterator""" + return _ifcopenshell_wrapper.svg_loop_rend(self) + + def clear(self): + r"""clear(svg_loop self)""" + return _ifcopenshell_wrapper.svg_loop_clear(self) + + def get_allocator(self): + r"""get_allocator(svg_loop self) -> std::vector< std::array< double,2 > >::allocator_type""" + return _ifcopenshell_wrapper.svg_loop_get_allocator(self) + + def pop_back(self): + r"""pop_back(svg_loop self)""" + return _ifcopenshell_wrapper.svg_loop_pop_back(self) + + def erase(self, *args): + r""" + erase(svg_loop self, std::vector< std::array< double,2 > >::iterator pos) -> std::vector< std::array< double,2 > >::iterator + erase(svg_loop self, std::vector< std::array< double,2 > >::iterator first, std::vector< std::array< double,2 > >::iterator last) -> std::vector< std::array< double,2 > >::iterator + """ + return _ifcopenshell_wrapper.svg_loop_erase(self, *args) + + def __init__(self, *args): + r""" + __init__(svg_loop self) -> svg_loop + __init__(svg_loop self, svg_loop other) -> svg_loop + __init__(svg_loop self, std::vector< std::array< double,2 > >::size_type size) -> svg_loop + __init__(svg_loop self, std::vector< std::array< double,2 > >::size_type size, svg_point value) -> svg_loop + """ + _ifcopenshell_wrapper.svg_loop_swiginit(self, _ifcopenshell_wrapper.new_svg_loop(*args)) + + def push_back(self, x): + r"""push_back(svg_loop self, svg_point x)""" + return _ifcopenshell_wrapper.svg_loop_push_back(self, x) + + def front(self): + r"""front(svg_loop self) -> svg_point""" + return _ifcopenshell_wrapper.svg_loop_front(self) + + def back(self): + r"""back(svg_loop self) -> svg_point""" + return _ifcopenshell_wrapper.svg_loop_back(self) + + def assign(self, n, x): + r"""assign(svg_loop self, std::vector< std::array< double,2 > >::size_type n, svg_point x)""" + return _ifcopenshell_wrapper.svg_loop_assign(self, n, x) + + def resize(self, *args): + r""" + resize(svg_loop self, std::vector< std::array< double,2 > >::size_type new_size) + resize(svg_loop self, std::vector< std::array< double,2 > >::size_type new_size, svg_point x) + """ + return _ifcopenshell_wrapper.svg_loop_resize(self, *args) + + def insert(self, *args): + r""" + insert(svg_loop self, std::vector< std::array< double,2 > >::iterator pos, svg_point x) -> std::vector< std::array< double,2 > >::iterator + insert(svg_loop self, std::vector< std::array< double,2 > >::iterator pos, std::vector< std::array< double,2 > >::size_type n, svg_point x) + """ + return _ifcopenshell_wrapper.svg_loop_insert(self, *args) + + def reserve(self, n): + r"""reserve(svg_loop self, std::vector< std::array< double,2 > >::size_type n)""" + return _ifcopenshell_wrapper.svg_loop_reserve(self, n) + + def capacity(self): + r"""capacity(svg_loop self) -> std::vector< std::array< double,2 > >::size_type""" + return _ifcopenshell_wrapper.svg_loop_capacity(self) + __swig_destroy__ = _ifcopenshell_wrapper.delete_svg_loop + +# Register svg_loop in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.svg_loop_swigregister(svg_loop) + +class svg_loops(object): + r"""Proxy of C++ std::vector< std::vector< std::array< double,2 > > > class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def iterator(self): + r"""iterator(svg_loops self) -> SwigPyIterator""" + return _ifcopenshell_wrapper.svg_loops_iterator(self) + def __iter__(self): + return self.iterator() + + def __nonzero__(self): + r"""__nonzero__(svg_loops self) -> bool""" + return _ifcopenshell_wrapper.svg_loops___nonzero__(self) + + def __bool__(self): + r"""__bool__(svg_loops self) -> bool""" + return _ifcopenshell_wrapper.svg_loops___bool__(self) + + def __len__(self): + r"""__len__(svg_loops self) -> std::vector< std::vector< std::array< double,2 > > >::size_type""" + return _ifcopenshell_wrapper.svg_loops___len__(self) + + def __getslice__(self, i, j): + r"""__getslice__(svg_loops self, std::vector< std::vector< std::array< double,2 > > >::difference_type i, std::vector< std::vector< std::array< double,2 > > >::difference_type j) -> svg_loops""" + return _ifcopenshell_wrapper.svg_loops___getslice__(self, i, j) + + def __setslice__(self, *args): + r""" + __setslice__(svg_loops self, std::vector< std::vector< std::array< double,2 > > >::difference_type i, std::vector< std::vector< std::array< double,2 > > >::difference_type j) + __setslice__(svg_loops self, std::vector< std::vector< std::array< double,2 > > >::difference_type i, std::vector< std::vector< std::array< double,2 > > >::difference_type j, svg_loops v) + """ + return _ifcopenshell_wrapper.svg_loops___setslice__(self, *args) + + def __delslice__(self, i, j): + r"""__delslice__(svg_loops self, std::vector< std::vector< std::array< double,2 > > >::difference_type i, std::vector< std::vector< std::array< double,2 > > >::difference_type j)""" + return _ifcopenshell_wrapper.svg_loops___delslice__(self, i, j) + + def __delitem__(self, *args): + r""" + __delitem__(svg_loops self, std::vector< std::vector< std::array< double,2 > > >::difference_type i) + __delitem__(svg_loops self, PySliceObject * slice) + """ + return _ifcopenshell_wrapper.svg_loops___delitem__(self, *args) + + def __getitem__(self, *args): + r""" + __getitem__(svg_loops self, PySliceObject * slice) -> svg_loops + __getitem__(svg_loops self, std::vector< std::vector< std::array< double,2 > > >::difference_type i) -> svg_loop + """ + return _ifcopenshell_wrapper.svg_loops___getitem__(self, *args) + + def __setitem__(self, *args): + r""" + __setitem__(svg_loops self, PySliceObject * slice, svg_loops v) + __setitem__(svg_loops self, PySliceObject * slice) + __setitem__(svg_loops self, std::vector< std::vector< std::array< double,2 > > >::difference_type i, svg_loop x) + """ + return _ifcopenshell_wrapper.svg_loops___setitem__(self, *args) + + def pop(self): + r"""pop(svg_loops self) -> svg_loop""" + return _ifcopenshell_wrapper.svg_loops_pop(self) + + def append(self, x): + r"""append(svg_loops self, svg_loop x)""" + return _ifcopenshell_wrapper.svg_loops_append(self, x) + + def empty(self): + r"""empty(svg_loops self) -> bool""" + return _ifcopenshell_wrapper.svg_loops_empty(self) + + def size(self): + r"""size(svg_loops self) -> std::vector< std::vector< std::array< double,2 > > >::size_type""" + return _ifcopenshell_wrapper.svg_loops_size(self) + + def swap(self, v): + r"""swap(svg_loops self, svg_loops v)""" + return _ifcopenshell_wrapper.svg_loops_swap(self, v) + + def begin(self): + r"""begin(svg_loops self) -> std::vector< std::vector< std::array< double,2 > > >::iterator""" + return _ifcopenshell_wrapper.svg_loops_begin(self) + + def end(self): + r"""end(svg_loops self) -> std::vector< std::vector< std::array< double,2 > > >::iterator""" + return _ifcopenshell_wrapper.svg_loops_end(self) + + def rbegin(self): + r"""rbegin(svg_loops self) -> std::vector< std::vector< std::array< double,2 > > >::reverse_iterator""" + return _ifcopenshell_wrapper.svg_loops_rbegin(self) + + def rend(self): + r"""rend(svg_loops self) -> std::vector< std::vector< std::array< double,2 > > >::reverse_iterator""" + return _ifcopenshell_wrapper.svg_loops_rend(self) + + def clear(self): + r"""clear(svg_loops self)""" + return _ifcopenshell_wrapper.svg_loops_clear(self) + + def get_allocator(self): + r"""get_allocator(svg_loops self) -> std::vector< std::vector< std::array< double,2 > > >::allocator_type""" + return _ifcopenshell_wrapper.svg_loops_get_allocator(self) + + def pop_back(self): + r"""pop_back(svg_loops self)""" + return _ifcopenshell_wrapper.svg_loops_pop_back(self) + + def erase(self, *args): + r""" + erase(svg_loops self, std::vector< std::vector< std::array< double,2 > > >::iterator pos) -> std::vector< std::vector< std::array< double,2 > > >::iterator + erase(svg_loops self, std::vector< std::vector< std::array< double,2 > > >::iterator first, std::vector< std::vector< std::array< double,2 > > >::iterator last) -> std::vector< std::vector< std::array< double,2 > > >::iterator + """ + return _ifcopenshell_wrapper.svg_loops_erase(self, *args) + + def __init__(self, *args): + r""" + __init__(svg_loops self) -> svg_loops + __init__(svg_loops self, svg_loops other) -> svg_loops + __init__(svg_loops self, std::vector< std::vector< std::array< double,2 > > >::size_type size) -> svg_loops + __init__(svg_loops self, std::vector< std::vector< std::array< double,2 > > >::size_type size, svg_loop value) -> svg_loops + """ + _ifcopenshell_wrapper.svg_loops_swiginit(self, _ifcopenshell_wrapper.new_svg_loops(*args)) + + def push_back(self, x): + r"""push_back(svg_loops self, svg_loop x)""" + return _ifcopenshell_wrapper.svg_loops_push_back(self, x) + + def front(self): + r"""front(svg_loops self) -> svg_loop""" + return _ifcopenshell_wrapper.svg_loops_front(self) + + def back(self): + r"""back(svg_loops self) -> svg_loop""" + return _ifcopenshell_wrapper.svg_loops_back(self) + + def assign(self, n, x): + r"""assign(svg_loops self, std::vector< std::vector< std::array< double,2 > > >::size_type n, svg_loop x)""" + return _ifcopenshell_wrapper.svg_loops_assign(self, n, x) + + def resize(self, *args): + r""" + resize(svg_loops self, std::vector< std::vector< std::array< double,2 > > >::size_type new_size) + resize(svg_loops self, std::vector< std::vector< std::array< double,2 > > >::size_type new_size, svg_loop x) + """ + return _ifcopenshell_wrapper.svg_loops_resize(self, *args) + + def insert(self, *args): + r""" + insert(svg_loops self, std::vector< std::vector< std::array< double,2 > > >::iterator pos, svg_loop x) -> std::vector< std::vector< std::array< double,2 > > >::iterator + insert(svg_loops self, std::vector< std::vector< std::array< double,2 > > >::iterator pos, std::vector< std::vector< std::array< double,2 > > >::size_type n, svg_loop x) + """ + return _ifcopenshell_wrapper.svg_loops_insert(self, *args) + + def reserve(self, n): + r"""reserve(svg_loops self, std::vector< std::vector< std::array< double,2 > > >::size_type n)""" + return _ifcopenshell_wrapper.svg_loops_reserve(self, n) + + def capacity(self): + r"""capacity(svg_loops self) -> std::vector< std::vector< std::array< double,2 > > >::size_type""" + return _ifcopenshell_wrapper.svg_loops_capacity(self) + __swig_destroy__ = _ifcopenshell_wrapper.delete_svg_loops + +# Register svg_loops in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.svg_loops_swigregister(svg_loops) + +class OpaqueCoordinate_3(object): + r"""Proxy of C++ IfcGeom::OpaqueCoordinate< 3 > class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def __init__(self, *args): + r""" + __init__(OpaqueCoordinate_3 self) -> OpaqueCoordinate_3 + __init__(OpaqueCoordinate_3 self, OpaqueCoordinate_3 other) -> OpaqueCoordinate_3 + """ + _ifcopenshell_wrapper.OpaqueCoordinate_3_swiginit(self, _ifcopenshell_wrapper.new_OpaqueCoordinate_3(*args)) + __swig_destroy__ = _ifcopenshell_wrapper.delete_OpaqueCoordinate_3 + + def get(self, i): + r"""get(OpaqueCoordinate_3 self, size_t i) -> OpaqueNumber""" + return _ifcopenshell_wrapper.OpaqueCoordinate_3_get(self, i) + + def set(self, i, n): + r"""set(OpaqueCoordinate_3 self, size_t i, OpaqueNumber n)""" + return _ifcopenshell_wrapper.OpaqueCoordinate_3_set(self, i, n) + +# Register OpaqueCoordinate_3 in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.OpaqueCoordinate_3_swigregister(OpaqueCoordinate_3) + +class OpaqueCoordinate_4(object): + r"""Proxy of C++ IfcGeom::OpaqueCoordinate< 4 > class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def __init__(self, *args): + r""" + __init__(OpaqueCoordinate_4 self) -> OpaqueCoordinate_4 + __init__(OpaqueCoordinate_4 self, OpaqueCoordinate_4 other) -> OpaqueCoordinate_4 + """ + _ifcopenshell_wrapper.OpaqueCoordinate_4_swiginit(self, _ifcopenshell_wrapper.new_OpaqueCoordinate_4(*args)) + __swig_destroy__ = _ifcopenshell_wrapper.delete_OpaqueCoordinate_4 + + def get(self, i): + r"""get(OpaqueCoordinate_4 self, size_t i) -> OpaqueNumber""" + return _ifcopenshell_wrapper.OpaqueCoordinate_4_get(self, i) + + def set(self, i, n): + r"""set(OpaqueCoordinate_4 self, size_t i, OpaqueNumber n)""" + return _ifcopenshell_wrapper.OpaqueCoordinate_4_set(self, i, n) + +# Register OpaqueCoordinate_4 in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.OpaqueCoordinate_4_swigregister(OpaqueCoordinate_4) + + +def create_epeck(*args): + r""" + create_epeck(int i) -> OpaqueNumber + create_epeck(double d) -> OpaqueNumber + create_epeck(std::string const & s) -> OpaqueNumber + """ + return _ifcopenshell_wrapper.create_epeck(*args) + +def nary_union(sequence): + r"""nary_union(PyObject * sequence) -> ConversionResultShape""" + return _ifcopenshell_wrapper.nary_union(sequence) +class polygon_2(object): + r"""Proxy of C++ svgfill::polygon_2 class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + boundary = property(_ifcopenshell_wrapper.polygon_2_boundary_get, _ifcopenshell_wrapper.polygon_2_boundary_set, doc=r"""boundary : svgfill::loop_2""") + inner_boundaries = property(_ifcopenshell_wrapper.polygon_2_inner_boundaries_get, _ifcopenshell_wrapper.polygon_2_inner_boundaries_set, doc=r"""inner_boundaries : std::vector<(svgfill::loop_2,std::allocator<(svgfill::loop_2)>)>""") + point_inside = property(_ifcopenshell_wrapper.polygon_2_point_inside_get, _ifcopenshell_wrapper.polygon_2_point_inside_set, doc=r"""point_inside : svgfill::point_2""") + + def __init__(self): + r"""__init__(polygon_2 self) -> polygon_2""" + _ifcopenshell_wrapper.polygon_2_swiginit(self, _ifcopenshell_wrapper.new_polygon_2()) + __swig_destroy__ = _ifcopenshell_wrapper.delete_polygon_2 + +# Register polygon_2 in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.polygon_2_swigregister(polygon_2) + +CARTESIAN_DOUBLE = _ifcopenshell_wrapper.CARTESIAN_DOUBLE + +CARTESIAN_QUOTIENT = _ifcopenshell_wrapper.CARTESIAN_QUOTIENT + +FILTERED_CARTESIAN_QUOTIENT = _ifcopenshell_wrapper.FILTERED_CARTESIAN_QUOTIENT + +EXACT_PREDICATES = _ifcopenshell_wrapper.EXACT_PREDICATES + +EXACT_CONSTRUCTIONS = _ifcopenshell_wrapper.EXACT_CONSTRUCTIONS + +class abstract_arrangement(object): + r"""Proxy of C++ svgfill::abstract_arrangement class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + + def __init__(self, *args, **kwargs): + raise AttributeError("No constructor defined - class is abstract") + __repr__ = _swig_repr + __swig_destroy__ = _ifcopenshell_wrapper.delete_abstract_arrangement + + def __call__(self, eps, segments, progress): + r"""__call__(abstract_arrangement self, double eps, svg_line_segments segments, std::function< void (float) > & progress) -> bool""" + return _ifcopenshell_wrapper.abstract_arrangement___call__(self, eps, segments, progress) + + def write(self, polygons, progress): + r"""write(abstract_arrangement self, svg_polygons polygons, std::function< void (float) > & progress) -> bool""" + return _ifcopenshell_wrapper.abstract_arrangement_write(self, polygons, progress) + + def merge(self, edge_indices): + r"""merge(abstract_arrangement self, std::vector< int,std::allocator< int > > const & edge_indices)""" + return _ifcopenshell_wrapper.abstract_arrangement_merge(self, edge_indices) + + def get_face_pairs(self): + r"""get_face_pairs(abstract_arrangement self) -> std::vector< int,std::allocator< int > >""" + return _ifcopenshell_wrapper.abstract_arrangement_get_face_pairs(self) + + def num_edges(self): + r"""num_edges(abstract_arrangement self) -> size_t""" + return _ifcopenshell_wrapper.abstract_arrangement_num_edges(self) + + def num_faces(self): + r"""num_faces(abstract_arrangement self) -> size_t""" + return _ifcopenshell_wrapper.abstract_arrangement_num_faces(self) + +# Register abstract_arrangement in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.abstract_arrangement_swigregister(abstract_arrangement) + +class context(object): + r"""Proxy of C++ svgfill::context class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def __init__(self, *args): + r""" + __init__(context self, svgfill::solver s, double eps) -> context + __init__(context self, svgfill::solver s, double eps, std::function< void (float) > & progress) -> context + """ + _ifcopenshell_wrapper.context_swiginit(self, _ifcopenshell_wrapper.new_context(*args)) + + def add(self, segments): + r"""add(context self, svg_line_segments segments)""" + return _ifcopenshell_wrapper.context_add(self, segments) + + def build(self): + r"""build(context self) -> bool""" + return _ifcopenshell_wrapper.context_build(self) + + def get_face_pairs(self): + r"""get_face_pairs(context self) -> std::vector< int,std::allocator< int > >""" + return _ifcopenshell_wrapper.context_get_face_pairs(self) + + def merge(self, edge_indices): + r"""merge(context self, std::vector< int,std::allocator< int > > const & edge_indices)""" + return _ifcopenshell_wrapper.context_merge(self, edge_indices) + + def write(self, arg2): + r"""write(context self, svg_groups_of_polygons arg2)""" + return _ifcopenshell_wrapper.context_write(self, arg2) + + def num_edges(self): + r"""num_edges(context self) -> size_t""" + return _ifcopenshell_wrapper.context_num_edges(self) + + def num_faces(self): + r"""num_faces(context self) -> size_t""" + return _ifcopenshell_wrapper.context_num_faces(self) + __swig_destroy__ = _ifcopenshell_wrapper.delete_context + +# Register context in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.context_swigregister(context) + + +def polygons_to_svg(*args): + r""" + polygons_to_svg(svg_groups_of_polygons polygons, bool random_color=False) -> std::string + polygons_to_svg(svg_polygons polygons, bool random_color=False) -> std::string + """ + return _ifcopenshell_wrapper.polygons_to_svg(*args) + +def svg_to_line_segments(data, class_name): + r"""svg_to_line_segments(std::string const & data, boost::optional< std::string > const & class_name) -> svg_groups_of_line_segments""" + return _ifcopenshell_wrapper.svg_to_line_segments(data, class_name) + +def line_segments_to_polygons(s, eps, segments): + r"""line_segments_to_polygons(svgfill::solver s, double eps, svg_groups_of_line_segments segments) -> svg_groups_of_polygons""" + return _ifcopenshell_wrapper.line_segments_to_polygons(s, eps, segments) + +def svg_to_polygons(data, class_name): + r"""svg_to_polygons(std::string const & data, boost::optional< std::string > const & class_name) -> svg_polygons""" + return _ifcopenshell_wrapper.svg_to_polygons(data, class_name) + +def arrange_polygons(polygons): + r"""arrange_polygons(svg_polygons polygons) -> svg_polygons""" + return _ifcopenshell_wrapper.arrange_polygons(polygons) +class IfcEntityInstanceData(object): + r"""Proxy of C++ IfcEntityInstanceData class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + + def __init__(self, *args, **kwargs): + raise AttributeError("No constructor defined") + __repr__ = _swig_repr + __swig_destroy__ = _ifcopenshell_wrapper.delete_IfcEntityInstanceData + +# Register IfcEntityInstanceData in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.IfcEntityInstanceData_swigregister(IfcEntityInstanceData) + +class attribute_value_derived(object): + r"""Proxy of C++ attribute_value_derived class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def __bool__(self): return False + def __repr__(self): return '*' + + + def __init__(self): + r"""__init__(attribute_value_derived self) -> attribute_value_derived""" + _ifcopenshell_wrapper.attribute_value_derived_swiginit(self, _ifcopenshell_wrapper.new_attribute_value_derived()) + __swig_destroy__ = _ifcopenshell_wrapper.delete_attribute_value_derived + +# Register attribute_value_derived in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.attribute_value_derived_swigregister(attribute_value_derived) + + +def set_feature(x, v): + r"""set_feature(std::string const & x, PyObject * v)""" + return _ifcopenshell_wrapper.set_feature(x, v) + +def get_feature(x): + r"""get_feature(std::string const & x) -> PyObject *""" + return _ifcopenshell_wrapper.get_feature(x) +class RocksDBPrefixIterator(object): + r"""Proxy of C++ RocksDBPrefixIterator class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def __init__(self, storage, prefix): + r"""__init__(RocksDBPrefixIterator self, IfcParse::impl::rocks_db_file_storage const * storage, std::string const & prefix) -> RocksDBPrefixIterator""" + _ifcopenshell_wrapper.RocksDBPrefixIterator_swiginit(self, _ifcopenshell_wrapper.new_RocksDBPrefixIterator(storage, prefix)) + + def valid(self): + r"""valid(RocksDBPrefixIterator self) -> bool""" + return _ifcopenshell_wrapper.RocksDBPrefixIterator_valid(self) + + def next(self): + r"""next(RocksDBPrefixIterator self)""" + return _ifcopenshell_wrapper.RocksDBPrefixIterator_next(self) + + def key(self): + r"""key(RocksDBPrefixIterator self) -> PyObject *""" + return _ifcopenshell_wrapper.RocksDBPrefixIterator_key(self) + + def value(self): + r"""value(RocksDBPrefixIterator self) -> PyObject *""" + return _ifcopenshell_wrapper.RocksDBPrefixIterator_value(self) + __swig_destroy__ = _ifcopenshell_wrapper.delete_RocksDBPrefixIterator + +# Register RocksDBPrefixIterator in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.RocksDBPrefixIterator_swigregister(RocksDBPrefixIterator) +cvar = _ifcopenshell_wrapper.cvar + +class IfcSpfHeader(object): + r"""Proxy of C++ IfcParse::IfcSpfHeader class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def __init__(self, *args): + r""" + __init__(IfcSpfHeader self, file file=None) -> IfcSpfHeader + __init__(IfcSpfHeader self, IfcParse::IfcSpfLexer * lexer) -> IfcSpfHeader + """ + _ifcopenshell_wrapper.IfcSpfHeader_swiginit(self, _ifcopenshell_wrapper.new_IfcSpfHeader(*args)) + __swig_destroy__ = _ifcopenshell_wrapper.delete_IfcSpfHeader + + def file(self, *args): + r""" + file(IfcSpfHeader self) -> file + file(IfcSpfHeader self, file file) + """ + return _ifcopenshell_wrapper.IfcSpfHeader_file(self, *args) + + def read(self): + r"""read(IfcSpfHeader self)""" + return _ifcopenshell_wrapper.IfcSpfHeader_read(self) + + def tryRead(self): + r"""tryRead(IfcSpfHeader self) -> bool""" + return _ifcopenshell_wrapper.IfcSpfHeader_tryRead(self) + + def write(self, out): + r"""write(IfcSpfHeader self, std::ostream & out)""" + return _ifcopenshell_wrapper.IfcSpfHeader_write(self, out) + + def file_description_py(self): + r"""file_description_py(IfcSpfHeader self) -> entity_instance""" + return _ifcopenshell_wrapper.IfcSpfHeader_file_description_py(self) + + def file_name_py(self): + r"""file_name_py(IfcSpfHeader self) -> entity_instance""" + return _ifcopenshell_wrapper.IfcSpfHeader_file_name_py(self) + + def file_schema_py(self): + r"""file_schema_py(IfcSpfHeader self) -> entity_instance""" + return _ifcopenshell_wrapper.IfcSpfHeader_file_schema_py(self) + +# Register IfcSpfHeader in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.IfcSpfHeader_swigregister(IfcSpfHeader) + +FT_IFCSPF = _ifcopenshell_wrapper.FT_IFCSPF + +FT_IFCXML = _ifcopenshell_wrapper.FT_IFCXML + +FT_IFCZIP = _ifcopenshell_wrapper.FT_IFCZIP + +FT_ROCKSDB = _ifcopenshell_wrapper.FT_ROCKSDB + +FT_UNKNOWN = _ifcopenshell_wrapper.FT_UNKNOWN + +FT_AUTODETECT = _ifcopenshell_wrapper.FT_AUTODETECT + + +def guess_file_type(fn): + r"""guess_file_type(std::string const & fn) -> IfcParse::filetype""" + return _ifcopenshell_wrapper.guess_file_type(fn) +class InstanceStreamer(object): + r"""Proxy of C++ IfcParse::InstanceStreamer class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + coerce_attribute_count = property(_ifcopenshell_wrapper.InstanceStreamer_coerce_attribute_count_get, _ifcopenshell_wrapper.InstanceStreamer_coerce_attribute_count_set, doc=r"""coerce_attribute_count : bool""") + + def __nonzero__(self): + return _ifcopenshell_wrapper.InstanceStreamer___nonzero__(self) + __bool__ = __nonzero__ + + + + def status(self): + r"""status(InstanceStreamer self) -> file_open_status""" + return _ifcopenshell_wrapper.InstanceStreamer_status(self) + + def references(self, *args): + r""" + references(InstanceStreamer self) -> IfcParse::unresolved_references const + references(InstanceStreamer self) -> IfcParse::unresolved_references & + """ + return _ifcopenshell_wrapper.InstanceStreamer_references(self, *args) + + def bypassed_instances(self): + r"""bypassed_instances(InstanceStreamer self) -> std::vector< unsigned int,std::allocator< unsigned int > > const &""" + return _ifcopenshell_wrapper.InstanceStreamer_bypassed_instances(self) + + def inverses(self, *args): + r""" + inverses(InstanceStreamer self) -> IfcParse::impl::in_memory_file_storage::entities_by_ref_t const + inverses(InstanceStreamer self) -> IfcParse::impl::in_memory_file_storage::entities_by_ref_t & + """ + return _ifcopenshell_wrapper.InstanceStreamer_inverses(self, *args) + + def hasSemicolon(self): + r"""hasSemicolon(InstanceStreamer self) -> bool""" + return _ifcopenshell_wrapper.InstanceStreamer_hasSemicolon(self) + + def semicolonCount(self): + r"""semicolonCount(InstanceStreamer self) -> size_t""" + return _ifcopenshell_wrapper.InstanceStreamer_semicolonCount(self) + + def pushPage(self, page): + r"""pushPage(InstanceStreamer self, std::string const & page)""" + return _ifcopenshell_wrapper.InstanceStreamer_pushPage(self, page) + + def __init__(self, *args): + r""" + __init__(InstanceStreamer self) -> InstanceStreamer + __init__(InstanceStreamer self, std::string const & fn, bool mmap=False) -> InstanceStreamer + __init__(InstanceStreamer self, void * data, int length) -> InstanceStreamer + """ + _ifcopenshell_wrapper.InstanceStreamer_swiginit(self, _ifcopenshell_wrapper.new_InstanceStreamer(*args)) + + def bypassTypes(self, type_names): + r"""bypassTypes(InstanceStreamer self, std::set< std::string > const & type_names)""" + return _ifcopenshell_wrapper.InstanceStreamer_bypassTypes(self, type_names) + __swig_destroy__ = _ifcopenshell_wrapper.delete_InstanceStreamer + + def readInstancePy(self, type_as_declaration_instance=False): + r"""readInstancePy(InstanceStreamer self, bool type_as_declaration_instance=False) -> PyObject""" + return _ifcopenshell_wrapper.InstanceStreamer_readInstancePy(self, type_as_declaration_instance) + +# Register InstanceStreamer in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.InstanceStreamer_swigregister(InstanceStreamer) + +class uninitialized_tag(object): + r"""Proxy of C++ IfcParse::uninitialized_tag class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def __init__(self): + r"""__init__(uninitialized_tag self) -> uninitialized_tag""" + _ifcopenshell_wrapper.uninitialized_tag_swiginit(self, _ifcopenshell_wrapper.new_uninitialized_tag()) + __swig_destroy__ = _ifcopenshell_wrapper.delete_uninitialized_tag + +# Register uninitialized_tag in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.uninitialized_tag_swigregister(uninitialized_tag) + +class file(object): + r"""Proxy of C++ IfcParse::IfcFile class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + check_existance_before_adding = property(_ifcopenshell_wrapper.file_check_existance_before_adding_get, _ifcopenshell_wrapper.file_check_existance_before_adding_set, doc=r"""check_existance_before_adding : bool""") + calculate_unit_factors = property(_ifcopenshell_wrapper.file_calculate_unit_factors_get, _ifcopenshell_wrapper.file_calculate_unit_factors_set, doc=r"""calculate_unit_factors : bool""") + instantiate_typed_instances = property(_ifcopenshell_wrapper.file_instantiate_typed_instances_get, _ifcopenshell_wrapper.file_instantiate_typed_instances_set, doc=r"""instantiate_typed_instances : bool""") + + def __init__(self, *args): + r""" + __init__(file self, std::string const & path, IfcParse::filetype ty=FT_AUTODETECT, bool readonly=False) -> file + __init__(file self, std::istream & stream, int length) -> file + __init__(file self, void * data, int length) -> file + __init__(file self, IfcParse::FileReader * stream) -> file + __init__(file self, schema_definition schema=IfcParse::schema_by_name("IFC4"), IfcParse::filetype ty=FT_AUTODETECT, std::string const & path="") -> file + __init__(file self, uninitialized_tag arg2) -> file + """ + _ifcopenshell_wrapper.file_swiginit(self, _ifcopenshell_wrapper.new_file(*args)) + + def initialize(self, *args): + r"""initialize(file self, std::string const & path, IfcParse::filetype ty=FT_AUTODETECT, bool readonly=False) -> bool""" + return _ifcopenshell_wrapper.file_initialize(self, *args) + + def bypass_type(self, type_name): + r"""bypass_type(file self, std::string const & type_name)""" + return _ifcopenshell_wrapper.file_bypass_type(self, type_name) + __swig_destroy__ = _ifcopenshell_wrapper.delete_file + + def good(self): + r"""good(file self) -> file_open_status""" + return _ifcopenshell_wrapper.file_good(self) + + def by_type(self, *args): + r""" + by_type(file self, declaration arg2) -> aggregate_of_instance::ptr + by_type(file self, std::string const & type) -> aggregate_of_instance::ptr + """ + return _ifcopenshell_wrapper.file_by_type(self, *args) + + def by_type_excl_subtypes(self, *args): + r""" + by_type_excl_subtypes(file self, declaration arg2) -> aggregate_of_instance::ptr + by_type_excl_subtypes(file self, std::string const & type) -> aggregate_of_instance::ptr + """ + return _ifcopenshell_wrapper.file_by_type_excl_subtypes(self, *args) + + def by_id(self, id): + r"""by_id(file self, int id) -> entity_instance""" + return _ifcopenshell_wrapper.file_by_id(self, id) + + def by_guid(self, guid): + r"""by_guid(file self, std::string const & guid) -> entity_instance""" + return _ifcopenshell_wrapper.file_by_guid(self, guid) + + @staticmethod + def traverse(instance, max_level=-1): + r"""traverse(entity_instance instance, int max_level=-1) -> aggregate_of_instance::ptr""" + return _ifcopenshell_wrapper.file_traverse(instance, max_level) + + @staticmethod + def traverse_breadth_first(instance, max_level=-1): + r"""traverse_breadth_first(entity_instance instance, int max_level=-1) -> aggregate_of_instance::ptr""" + return _ifcopenshell_wrapper.file_traverse_breadth_first(instance, max_level) + + def get_inverses_by_declaration(self, instance_id, type, attribute_index): + r"""get_inverses_by_declaration(file self, int instance_id, declaration type, int attribute_index) -> aggregate_of_instance::ptr""" + return _ifcopenshell_wrapper.file_get_inverses_by_declaration(self, instance_id, type, attribute_index) + + def get_total_inverses_by_id(self, instance_id): + r"""get_total_inverses_by_id(file self, int instance_id) -> size_t""" + return _ifcopenshell_wrapper.file_get_total_inverses_by_id(self, instance_id) + + def FreshId(self): + r"""FreshId(file self) -> unsigned int""" + return _ifcopenshell_wrapper.file_FreshId(self) + + def getMaxId(self): + r"""getMaxId(file self) -> unsigned int""" + return _ifcopenshell_wrapper.file_getMaxId(self) + + def ifcroot_type(self): + r"""ifcroot_type(file self) -> declaration""" + return _ifcopenshell_wrapper.file_ifcroot_type(self) + + def recalculate_id_counter(self): + r"""recalculate_id_counter(file self)""" + return _ifcopenshell_wrapper.file_recalculate_id_counter(self) + + def add(self, entity, id=-1): + r"""add(file self, entity_instance entity, int id=-1) -> entity_instance""" + return _ifcopenshell_wrapper.file_add(self, entity, id) + + def addEntities(self, entities): + r"""addEntities(file self, aggregate_of_instance::ptr entities)""" + return _ifcopenshell_wrapper.file_addEntities(self, entities) + + def remove(self, entity): + r"""remove(file self, entity_instance entity)""" + return _ifcopenshell_wrapper.file_remove(self, entity) + + def header(self, *args): + r""" + header(file self) -> IfcSpfHeader + header(file self) -> IfcSpfHeader + """ + return _ifcopenshell_wrapper.file_header(self, *args) + + @staticmethod + def createTimestamp(): + r"""createTimestamp() -> std::string""" + return _ifcopenshell_wrapper.file_createTimestamp() + + def getUnit(self, unit_type): + r"""getUnit(file self, std::string const & unit_type) -> std::pair< IfcUtil::IfcBaseClass *,double >""" + return _ifcopenshell_wrapper.file_getUnit(self, unit_type) + + def build_inverses(self): + r"""build_inverses(file self)""" + return _ifcopenshell_wrapper.file_build_inverses(self) + + def add_type_ref(self, new_entity): + r"""add_type_ref(file self, entity_instance new_entity)""" + return _ifcopenshell_wrapper.file_add_type_ref(self, new_entity) + + def remove_type_ref(self, new_entity): + r"""remove_type_ref(file self, entity_instance new_entity)""" + return _ifcopenshell_wrapper.file_remove_type_ref(self, new_entity) + + def process_deletion_inverse(self, inst): + r"""process_deletion_inverse(file self, entity_instance inst)""" + return _ifcopenshell_wrapper.file_process_deletion_inverse(self, inst) + + def build_inverses_(self, arg2): + r"""build_inverses_(file self, entity_instance arg2)""" + return _ifcopenshell_wrapper.file_build_inverses_(self, arg2) + + def create(self, decl): + r"""create(file self, declaration decl) -> entity_instance""" + return _ifcopenshell_wrapper.file_create(self, decl) + + def batch(self): + r"""batch(file self)""" + return _ifcopenshell_wrapper.file_batch(self) + + def unbatch(self): + r"""unbatch(file self)""" + return _ifcopenshell_wrapper.file_unbatch(self) + + def reset_identity_cache(self): + r"""reset_identity_cache(file self)""" + return _ifcopenshell_wrapper.file_reset_identity_cache(self) + + def file_pointer(self): + r"""file_pointer(file self) -> size_t""" + return _ifcopenshell_wrapper.file_file_pointer(self) + + def get_inverse(self, e): + r"""get_inverse(file self, entity_instance e) -> aggregate_of_instance::ptr""" + return _ifcopenshell_wrapper.file_get_inverse(self, e) + + def get_inverse_indices(self, *args): + r""" + get_inverse_indices(file self, int instance_id) -> std::vector< int,std::allocator< int > > + get_inverse_indices(file self, entity_instance e) -> std::vector< int,std::allocator< int > > + """ + return _ifcopenshell_wrapper.file_get_inverse_indices(self, *args) + + def get_total_inverses(self, e): + r"""get_total_inverses(file self, entity_instance e) -> int""" + return _ifcopenshell_wrapper.file_get_total_inverses(self, e) + + def write(self, fn): + r"""write(file self, std::string const & fn)""" + return _ifcopenshell_wrapper.file_write(self, fn) + + def to_string(self): + r"""to_string(file self) -> std::string""" + return _ifcopenshell_wrapper.file_to_string(self) + + def entity_names(self): + r"""entity_names(file self) -> std::vector< unsigned int,std::allocator< unsigned int > >""" + return _ifcopenshell_wrapper.file_entity_names(self) + + def types(self): + r"""types(file self) -> std::vector< std::string,std::allocator< std::string > >""" + return _ifcopenshell_wrapper.file_types(self) + + def schema_name(self): + r"""schema_name(file self) -> std::string""" + return _ifcopenshell_wrapper.file_schema_name(self) + + def storage_mode(self): + r"""storage_mode(file self) -> int""" + return _ifcopenshell_wrapper.file_storage_mode(self) + + def key_value_store_iter(self, prefix): + r"""key_value_store_iter(file self, std::string const & prefix) -> RocksDBPrefixIterator""" + return _ifcopenshell_wrapper.file_key_value_store_iter(self, prefix) + + def key_value_store_query(self, key): + r"""key_value_store_query(file self, std::string const & key) -> PyObject *""" + return _ifcopenshell_wrapper.file_key_value_store_query(self, key) + + schema = property(schema_name) + + +# Register file in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.file_swigregister(file) + +def file_traverse(instance, max_level=-1): + r"""file_traverse(entity_instance instance, int max_level=-1) -> aggregate_of_instance::ptr""" + return _ifcopenshell_wrapper.file_traverse(instance, max_level) + +def file_traverse_breadth_first(instance, max_level=-1): + r"""file_traverse_breadth_first(entity_instance instance, int max_level=-1) -> aggregate_of_instance::ptr""" + return _ifcopenshell_wrapper.file_traverse_breadth_first(instance, max_level) + +def file_createTimestamp(): + r"""file_createTimestamp() -> std::string""" + return _ifcopenshell_wrapper.file_createTimestamp() + + +def parse_ifcxml(filename): + r"""parse_ifcxml(std::string const & filename) -> file""" + return _ifcopenshell_wrapper.parse_ifcxml(filename) +class file_open_status(object): + r"""Proxy of C++ IfcParse::file_open_status class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + SUCCESS = _ifcopenshell_wrapper.file_open_status_SUCCESS + + READ_ERROR = _ifcopenshell_wrapper.file_open_status_READ_ERROR + + NO_HEADER = _ifcopenshell_wrapper.file_open_status_NO_HEADER + + UNSUPPORTED_SCHEMA = _ifcopenshell_wrapper.file_open_status_UNSUPPORTED_SCHEMA + + INVALID_SYNTAX = _ifcopenshell_wrapper.file_open_status_INVALID_SYNTAX + + UNKNOWN = _ifcopenshell_wrapper.file_open_status_UNKNOWN + + + def __init__(self, *args): + r"""__init__(file_open_status self, IfcParse::file_open_status::file_open_enum error=UNKNOWN) -> file_open_status""" + _ifcopenshell_wrapper.file_open_status_swiginit(self, _ifcopenshell_wrapper.new_file_open_status(*args)) + + def value(self): + r"""value(file_open_status self) -> IfcParse::file_open_status::file_open_enum""" + return _ifcopenshell_wrapper.file_open_status_value(self) + + def __nonzero__(self): + return _ifcopenshell_wrapper.file_open_status___nonzero__(self) + __bool__ = __nonzero__ + + + __swig_destroy__ = _ifcopenshell_wrapper.delete_file_open_status + +# Register file_open_status in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.file_open_status_swigregister(file_open_status) + +class entity_instance(object): + r"""Proxy of C++ IfcUtil::IfcBaseClass class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + + def __init__(self, *args, **kwargs): + raise AttributeError("No constructor defined - class is abstract") + id_ = property(_ifcopenshell_wrapper.entity_instance_id__get, _ifcopenshell_wrapper.entity_instance_id__set, doc=r"""id_ : uint32_t""") + file_ = property(_ifcopenshell_wrapper.entity_instance_file__get, _ifcopenshell_wrapper.entity_instance_file__set, doc=r"""file_ : p.IfcParse::IfcFile""") + + def data(self, *args): + r""" + data(entity_instance self) -> IfcEntityInstanceData + data(entity_instance self) -> IfcEntityInstanceData + """ + return _ifcopenshell_wrapper.entity_instance_data(self, *args) + + def declaration(self): + r"""declaration(entity_instance self) -> declaration""" + return _ifcopenshell_wrapper.entity_instance_declaration(self) + + def set_attribute_value(self, *args): + r""" + set_attribute_value(entity_instance self, size_t i, entity_instance p) + set_attribute_value(entity_instance self, std::string const & name, entity_instance p) + """ + return _ifcopenshell_wrapper.entity_instance_set_attribute_value(self, *args) + + def unset_attribute_value(self, i): + r"""unset_attribute_value(entity_instance self, size_t i)""" + return _ifcopenshell_wrapper.entity_instance_unset_attribute_value(self, i) + + def get_attribute_value(self, index): + r"""get_attribute_value(entity_instance self, size_t index) -> AttributeValue""" + return _ifcopenshell_wrapper.entity_instance_get_attribute_value(self, index) + + def identity(self): + r"""identity(entity_instance self) -> uint32_t""" + return _ifcopenshell_wrapper.entity_instance_identity(self) + + def toString(self, arg2, upper=False): + r"""toString(entity_instance self, std::ostream & arg2, bool upper=False)""" + return _ifcopenshell_wrapper.entity_instance_toString(self, arg2, upper) + + # Will be assigned when `ifcopenshell.entity_instance` is created. + file = None + + + def get_attribute_category(self, name): + r"""get_attribute_category(entity_instance self, std::string const & name) -> int""" + return _ifcopenshell_wrapper.entity_instance_get_attribute_category(self, name) + + def id(self): + r"""id(entity_instance self) -> int""" + return _ifcopenshell_wrapper.entity_instance_id(self) + + def __len__(self): + r"""__len__(entity_instance self) -> int""" + return _ifcopenshell_wrapper.entity_instance___len__(self) + + def get_attribute_names(self): + r"""get_attribute_names(entity_instance self) -> std::vector< std::string,std::allocator< std::string > >""" + return _ifcopenshell_wrapper.entity_instance_get_attribute_names(self) + + def get_inverse_attribute_names(self): + r"""get_inverse_attribute_names(entity_instance self) -> std::vector< std::string,std::allocator< std::string > >""" + return _ifcopenshell_wrapper.entity_instance_get_inverse_attribute_names(self) + + def is_a(self, *args): + r""" + is_a(entity_instance self, std::string const & s) -> bool + is_a(entity_instance self, bool with_schema=False) -> std::string + """ + return _ifcopenshell_wrapper.entity_instance_is_a(self, *args) + + def get_argument(self, *args): + r""" + get_argument(entity_instance self, unsigned int i) -> AttributeValue + get_argument(entity_instance self, std::string const & a) -> AttributeValue + """ + return _ifcopenshell_wrapper.entity_instance_get_argument(self, *args) + + def __eq__(self, other): + r"""__eq__(entity_instance self, entity_instance other) -> bool""" + return _ifcopenshell_wrapper.entity_instance___eq__(self, other) + + def __repr__(self): + r"""__repr__(entity_instance self) -> std::string""" + return _ifcopenshell_wrapper.entity_instance___repr__(self) + + def to_string(self, valid_spf=True): + r"""to_string(entity_instance self, bool valid_spf=True) -> std::string""" + return _ifcopenshell_wrapper.entity_instance_to_string(self, valid_spf) + + def file_pointer(self): + r"""file_pointer(entity_instance self) -> size_t""" + return _ifcopenshell_wrapper.entity_instance_file_pointer(self) + + def get_argument_index(self, a): + r"""get_argument_index(entity_instance self, std::string const & a) -> unsigned int""" + return _ifcopenshell_wrapper.entity_instance_get_argument_index(self, a) + + def get_inverse(self, a): + r"""get_inverse(entity_instance self, std::string const & a) -> aggregate_of_instance::ptr""" + return _ifcopenshell_wrapper.entity_instance_get_inverse(self, a) + + def get_argument_type(self, i): + r"""get_argument_type(entity_instance self, unsigned int i) -> char const *const""" + return _ifcopenshell_wrapper.entity_instance_get_argument_type(self, i) + + def get_argument_name(self, i): + r"""get_argument_name(entity_instance self, unsigned int i) -> std::string const &""" + return _ifcopenshell_wrapper.entity_instance_get_argument_name(self, i) + + def setArgumentAsNull(self, i): + r"""setArgumentAsNull(entity_instance self, unsigned int i)""" + return _ifcopenshell_wrapper.entity_instance_setArgumentAsNull(self, i) + + def setArgumentAsInt(self, i, v): + r"""setArgumentAsInt(entity_instance self, unsigned int i, int v)""" + return _ifcopenshell_wrapper.entity_instance_setArgumentAsInt(self, i, v) + + def setArgumentAsBool(self, i, v): + r"""setArgumentAsBool(entity_instance self, unsigned int i, bool v)""" + return _ifcopenshell_wrapper.entity_instance_setArgumentAsBool(self, i, v) + + def setArgumentAsLogical(self, i, v): + r"""setArgumentAsLogical(entity_instance self, unsigned int i, boost::logic::tribool v)""" + return _ifcopenshell_wrapper.entity_instance_setArgumentAsLogical(self, i, v) + + def setArgumentAsDouble(self, i, v): + r"""setArgumentAsDouble(entity_instance self, unsigned int i, double v)""" + return _ifcopenshell_wrapper.entity_instance_setArgumentAsDouble(self, i, v) + + def setArgumentAsString(self, i, a): + r"""setArgumentAsString(entity_instance self, unsigned int i, std::string const & a)""" + return _ifcopenshell_wrapper.entity_instance_setArgumentAsString(self, i, a) + + def setArgumentAsAggregateOfInt(self, i, v): + r"""setArgumentAsAggregateOfInt(entity_instance self, unsigned int i, std::vector< int,std::allocator< int > > const & v)""" + return _ifcopenshell_wrapper.entity_instance_setArgumentAsAggregateOfInt(self, i, v) + + def setArgumentAsAggregateOfDouble(self, i, v): + r"""setArgumentAsAggregateOfDouble(entity_instance self, unsigned int i, std::vector< double,std::allocator< double > > const & v)""" + return _ifcopenshell_wrapper.entity_instance_setArgumentAsAggregateOfDouble(self, i, v) + + def setArgumentAsAggregateOfString(self, i, v): + r"""setArgumentAsAggregateOfString(entity_instance self, unsigned int i, std::vector< std::string,std::allocator< std::string > > const & v)""" + return _ifcopenshell_wrapper.entity_instance_setArgumentAsAggregateOfString(self, i, v) + + def setArgumentAsEntityInstance(self, i, v): + r"""setArgumentAsEntityInstance(entity_instance self, unsigned int i, entity_instance v)""" + return _ifcopenshell_wrapper.entity_instance_setArgumentAsEntityInstance(self, i, v) + + def setArgumentAsAggregateOfEntityInstance(self, i, v): + r"""setArgumentAsAggregateOfEntityInstance(entity_instance self, unsigned int i, aggregate_of_instance::ptr v)""" + return _ifcopenshell_wrapper.entity_instance_setArgumentAsAggregateOfEntityInstance(self, i, v) + + def setArgumentAsAggregateOfAggregateOfInt(self, i, v): + r"""setArgumentAsAggregateOfAggregateOfInt(entity_instance self, unsigned int i, std::vector< std::vector< int,std::allocator< int > >,std::allocator< std::vector< int,std::allocator< int > > > > const & v)""" + return _ifcopenshell_wrapper.entity_instance_setArgumentAsAggregateOfAggregateOfInt(self, i, v) + + def setArgumentAsAggregateOfAggregateOfDouble(self, i, v): + r"""setArgumentAsAggregateOfAggregateOfDouble(entity_instance self, unsigned int i, std::vector< std::vector< double,std::allocator< double > >,std::allocator< std::vector< double,std::allocator< double > > > > const & v)""" + return _ifcopenshell_wrapper.entity_instance_setArgumentAsAggregateOfAggregateOfDouble(self, i, v) + + def setArgumentAsAggregateOfAggregateOfEntityInstance(self, i, v): + r"""setArgumentAsAggregateOfAggregateOfEntityInstance(entity_instance self, unsigned int i, aggregate_of_aggregate_of_instance::ptr v)""" + return _ifcopenshell_wrapper.entity_instance_setArgumentAsAggregateOfAggregateOfEntityInstance(self, i, v) + __swig_destroy__ = _ifcopenshell_wrapper.delete_entity_instance + +# Register entity_instance in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.entity_instance_swigregister(entity_instance) + +class IfcBaseEntity(entity_instance): + r"""Proxy of C++ IfcUtil::IfcBaseEntity class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + + def __init__(self, *args, **kwargs): + raise AttributeError("No constructor defined - class is abstract") + __repr__ = _swig_repr + + def declaration(self): + r"""declaration(IfcBaseEntity self) -> declaration""" + return _ifcopenshell_wrapper.IfcBaseEntity_declaration(self) + + def get(self, name): + r"""get(IfcBaseEntity self, std::string const & name) -> AttributeValue""" + return _ifcopenshell_wrapper.IfcBaseEntity_get(self, name) + + def get_inverse(self, name): + r"""get_inverse(IfcBaseEntity self, std::string const & name) -> boost::shared_ptr< aggregate_of_instance >""" + return _ifcopenshell_wrapper.IfcBaseEntity_get_inverse(self, name) + + def set_id(self, i): + r"""set_id(IfcBaseEntity self, boost::optional< unsigned int > const & i) -> unsigned int""" + return _ifcopenshell_wrapper.IfcBaseEntity_set_id(self, i) + + def populate_derived(self): + r"""populate_derived(IfcBaseEntity self)""" + return _ifcopenshell_wrapper.IfcBaseEntity_populate_derived(self) + __swig_destroy__ = _ifcopenshell_wrapper.delete_IfcBaseEntity + +# Register IfcBaseEntity in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.IfcBaseEntity_swigregister(IfcBaseEntity) + +class IfcLateBoundEntity(IfcBaseEntity): + r"""Proxy of C++ IfcUtil::IfcLateBoundEntity class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def __init__(self, decl, data): + r"""__init__(IfcLateBoundEntity self, declaration decl, IfcEntityInstanceData data) -> IfcLateBoundEntity""" + _ifcopenshell_wrapper.IfcLateBoundEntity_swiginit(self, _ifcopenshell_wrapper.new_IfcLateBoundEntity(decl, data)) + + def declaration(self): + r"""declaration(IfcLateBoundEntity self) -> declaration""" + return _ifcopenshell_wrapper.IfcLateBoundEntity_declaration(self) + __swig_destroy__ = _ifcopenshell_wrapper.delete_IfcLateBoundEntity + +# Register IfcLateBoundEntity in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.IfcLateBoundEntity_swigregister(IfcLateBoundEntity) + +class IfcBaseType(entity_instance): + r"""Proxy of C++ IfcUtil::IfcBaseType class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + + def __init__(self, *args, **kwargs): + raise AttributeError("No constructor defined - class is abstract") + __repr__ = _swig_repr + + def declaration(self): + r"""declaration(IfcBaseType self) -> declaration""" + return _ifcopenshell_wrapper.IfcBaseType_declaration(self) + __swig_destroy__ = _ifcopenshell_wrapper.delete_IfcBaseType + +# Register IfcBaseType in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.IfcBaseType_swigregister(IfcBaseType) + +class parameter_type(object): + r"""Proxy of C++ IfcParse::parameter_type class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + __swig_destroy__ = _ifcopenshell_wrapper.delete_parameter_type + + def as_named_type(self): + r"""as_named_type(parameter_type self) -> named_type""" + return _ifcopenshell_wrapper.parameter_type_as_named_type(self) + + def as_simple_type(self): + r"""as_simple_type(parameter_type self) -> simple_type""" + return _ifcopenshell_wrapper.parameter_type_as_simple_type(self) + + def as_aggregation_type(self): + r"""as_aggregation_type(parameter_type self) -> aggregation_type""" + return _ifcopenshell_wrapper.parameter_type_as_aggregation_type(self) + + def _is(self, *args): + r""" + _is(parameter_type self, std::string const & arg2) -> bool + _is(parameter_type self, declaration arg2) -> bool + """ + return _ifcopenshell_wrapper.parameter_type__is(self, *args) + + def __init__(self): + r"""__init__(parameter_type self) -> parameter_type""" + _ifcopenshell_wrapper.parameter_type_swiginit(self, _ifcopenshell_wrapper.new_parameter_type()) + +# Register parameter_type in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.parameter_type_swigregister(parameter_type) + +class named_type(parameter_type): + r"""Proxy of C++ IfcParse::named_type class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def __init__(self, declared_type): + r"""__init__(named_type self, declaration declared_type) -> named_type""" + _ifcopenshell_wrapper.named_type_swiginit(self, _ifcopenshell_wrapper.new_named_type(declared_type)) + + def declared_type(self): + r"""declared_type(named_type self) -> declaration""" + return _ifcopenshell_wrapper.named_type_declared_type(self) + + def as_named_type(self): + r"""as_named_type(named_type self) -> named_type""" + return _ifcopenshell_wrapper.named_type_as_named_type(self) + + def _is(self, *args): + r""" + _is(named_type self, std::string const & name) -> bool + _is(named_type self, declaration decl) -> bool + """ + return _ifcopenshell_wrapper.named_type__is(self, *args) + + def __repr__(self): + return repr(self.declared_type()) + + __swig_destroy__ = _ifcopenshell_wrapper.delete_named_type + +# Register named_type in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.named_type_swigregister(named_type) + +class simple_type(parameter_type): + r"""Proxy of C++ IfcParse::simple_type class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + binary_type = _ifcopenshell_wrapper.simple_type_binary_type + + boolean_type = _ifcopenshell_wrapper.simple_type_boolean_type + + integer_type = _ifcopenshell_wrapper.simple_type_integer_type + + logical_type = _ifcopenshell_wrapper.simple_type_logical_type + + number_type = _ifcopenshell_wrapper.simple_type_number_type + + real_type = _ifcopenshell_wrapper.simple_type_real_type + + string_type = _ifcopenshell_wrapper.simple_type_string_type + + datatype_COUNT = _ifcopenshell_wrapper.simple_type_datatype_COUNT + + + def __init__(self, declared_type): + r"""__init__(simple_type self, IfcParse::simple_type::data_type declared_type) -> simple_type""" + _ifcopenshell_wrapper.simple_type_swiginit(self, _ifcopenshell_wrapper.new_simple_type(declared_type)) + + def declared_type(self): + r"""declared_type(simple_type self) -> IfcParse::simple_type::data_type""" + return _ifcopenshell_wrapper.simple_type_declared_type(self) + + def as_simple_type(self): + r"""as_simple_type(simple_type self) -> simple_type""" + return _ifcopenshell_wrapper.simple_type_as_simple_type(self) + + def __repr__(self): + return "<%s>" % self.declared_type() + + __swig_destroy__ = _ifcopenshell_wrapper.delete_simple_type + +# Register simple_type in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.simple_type_swigregister(simple_type) + +class aggregation_type(parameter_type): + r"""Proxy of C++ IfcParse::aggregation_type class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + array_type = _ifcopenshell_wrapper.aggregation_type_array_type + + bag_type = _ifcopenshell_wrapper.aggregation_type_bag_type + + list_type = _ifcopenshell_wrapper.aggregation_type_list_type + + set_type = _ifcopenshell_wrapper.aggregation_type_set_type + + + def __init__(self, type_of_aggregation, bound1, bound2, type_of_element): + r"""__init__(aggregation_type self, IfcParse::aggregation_type::aggregate_type type_of_aggregation, int bound1, int bound2, parameter_type type_of_element) -> aggregation_type""" + _ifcopenshell_wrapper.aggregation_type_swiginit(self, _ifcopenshell_wrapper.new_aggregation_type(type_of_aggregation, bound1, bound2, type_of_element)) + __swig_destroy__ = _ifcopenshell_wrapper.delete_aggregation_type + + def type_of_aggregation(self): + r"""type_of_aggregation(aggregation_type self) -> IfcParse::aggregation_type::aggregate_type""" + return _ifcopenshell_wrapper.aggregation_type_type_of_aggregation(self) + + def bound1(self): + r"""bound1(aggregation_type self) -> int""" + return _ifcopenshell_wrapper.aggregation_type_bound1(self) + + def bound2(self): + r"""bound2(aggregation_type self) -> int""" + return _ifcopenshell_wrapper.aggregation_type_bound2(self) + + def type_of_element(self): + r"""type_of_element(aggregation_type self) -> parameter_type""" + return _ifcopenshell_wrapper.aggregation_type_type_of_element(self) + + def as_aggregation_type(self): + r"""as_aggregation_type(aggregation_type self) -> aggregation_type""" + return _ifcopenshell_wrapper.aggregation_type_as_aggregation_type(self) + + def type_of_aggregation_string(self): + r"""type_of_aggregation_string(aggregation_type self) -> std::string""" + return _ifcopenshell_wrapper.aggregation_type_type_of_aggregation_string(self) + + def __repr__(self): + format_bound = lambda i: "?" if i == -1 else str(i) + return "<%s [%s:%s] of %r>" % ( + self.type_of_aggregation_string(), + format_bound(self.bound1()), + format_bound(self.bound2()), + self.type_of_element() + ) + + +# Register aggregation_type in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.aggregation_type_swigregister(aggregation_type) + +class declaration(object): + r"""Proxy of C++ IfcParse::declaration class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def __init__(self, name, index_in_schema): + r"""__init__(declaration self, std::string const & name, int index_in_schema) -> declaration""" + _ifcopenshell_wrapper.declaration_swiginit(self, _ifcopenshell_wrapper.new_declaration(name, index_in_schema)) + __swig_destroy__ = _ifcopenshell_wrapper.delete_declaration + + def name(self): + r"""name(declaration self) -> std::string const &""" + return _ifcopenshell_wrapper.declaration_name(self) + + def name_uc(self): + r"""name_uc(declaration self) -> std::string const &""" + return _ifcopenshell_wrapper.declaration_name_uc(self) + + def as_type_declaration(self): + r"""as_type_declaration(declaration self) -> type_declaration""" + return _ifcopenshell_wrapper.declaration_as_type_declaration(self) + + def as_select_type(self): + r"""as_select_type(declaration self) -> select_type""" + return _ifcopenshell_wrapper.declaration_as_select_type(self) + + def as_enumeration_type(self): + r"""as_enumeration_type(declaration self) -> enumeration_type""" + return _ifcopenshell_wrapper.declaration_as_enumeration_type(self) + + def as_entity(self): + r"""as_entity(declaration self) -> entity""" + return _ifcopenshell_wrapper.declaration_as_entity(self) + + def _is(self, *args): + r""" + _is(declaration self, std::string const & name) -> bool + _is(declaration self, declaration decl) -> bool + """ + return _ifcopenshell_wrapper.declaration__is(self, *args) + + def index_in_schema(self): + r"""index_in_schema(declaration self) -> int""" + return _ifcopenshell_wrapper.declaration_index_in_schema(self) + + def type(self): + r"""type(declaration self) -> int""" + return _ifcopenshell_wrapper.declaration_type(self) + + def schema(self): + r"""schema(declaration self) -> schema_definition""" + return _ifcopenshell_wrapper.declaration_schema(self) + +# Register declaration in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.declaration_swigregister(declaration) + +class type_declaration(declaration): + r"""Proxy of C++ IfcParse::type_declaration class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def __init__(self, name, index_in_schema, declared_type): + r"""__init__(type_declaration self, std::string const & name, int index_in_schema, parameter_type declared_type) -> type_declaration""" + _ifcopenshell_wrapper.type_declaration_swiginit(self, _ifcopenshell_wrapper.new_type_declaration(name, index_in_schema, declared_type)) + __swig_destroy__ = _ifcopenshell_wrapper.delete_type_declaration + + def declared_type(self): + r"""declared_type(type_declaration self) -> parameter_type""" + return _ifcopenshell_wrapper.type_declaration_declared_type(self) + + def as_type_declaration(self): + r"""as_type_declaration(type_declaration self) -> type_declaration""" + return _ifcopenshell_wrapper.type_declaration_as_type_declaration(self) + + def __repr__(self): + return "" % (self.name(), self.declared_type()) + + + def argument_types(self): + r"""argument_types(type_declaration self) -> std::vector< std::string,std::allocator< std::string > >""" + return _ifcopenshell_wrapper.type_declaration_argument_types(self) + +# Register type_declaration in _ifcopenshell_wrapper: +_ifcopenshell_wrapper.type_declaration_swigregister(type_declaration) + +class select_type(declaration): + r"""Proxy of C++ IfcParse::select_type class.""" + + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def __init__(self, name, index_in_schema, select_list): + r"""__init__(select_type self, std::string const & name, int index_in_schema, std::vector< IfcParse::declaration const *,std::allocator< IfcParse::declaration const * > > const & select_list) -> select_type""" + _ifcopenshell_wrapper.select_type_swiginit(self, _ifcopenshell_wrapper.new_select_type(name, index_in_schema, select_list)) + + def select_list(self): + r"""select_list(select_type self) -> std::vector< IfcParse::declaration const *,std::allocator< IfcParse::declaration const * > > const &""" + return _ifcopenshell_wrapper.select_type_select_list(self) + + def as_select_type(self): + r"""as_select_type(select_type self) -> select_type""" + return _ifcopenshell_wrapper.select_type_as_select_type(self) + + def __repr__(self): + return "