diff --git a/src/poetry/core/_vendor/_pyrsistent_version.py b/src/poetry/core/_vendor/_pyrsistent_version.py index 9513287c9..5877c8d04 100644 --- a/src/poetry/core/_vendor/_pyrsistent_version.py +++ b/src/poetry/core/_vendor/_pyrsistent_version.py @@ -1 +1 @@ -__version__ = '0.16.1' +__version__ = '0.18.1' diff --git a/src/poetry/core/_vendor/jsonschema/LICENSE b/src/poetry/core/_vendor/jsonschema/LICENSE deleted file mode 100644 index c28adbadd..000000000 --- a/src/poetry/core/_vendor/jsonschema/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2012 Julian Berman - -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/src/poetry/core/_vendor/jsonschema/_format.py b/src/poetry/core/_vendor/jsonschema/_format.py index bd8377f35..da4bb799e 100644 --- a/src/poetry/core/_vendor/jsonschema/_format.py +++ b/src/poetry/core/_vendor/jsonschema/_format.py @@ -9,6 +9,12 @@ from jsonschema.exceptions import FormatError +_FormatCheckCallable = typing.Callable[[object], bool] +_F = typing.TypeVar("_F", bound=_FormatCheckCallable) +_RaisesType = typing.Union[ + typing.Type[Exception], typing.Tuple[typing.Type[Exception], ...], +] + class FormatChecker(object): """ @@ -35,13 +41,10 @@ class FormatChecker(object): checkers: dict[ str, - tuple[ - typing.Callable[[typing.Any], bool], - Exception | tuple[Exception, ...], - ], + tuple[_FormatCheckCallable, _RaisesType], ] = {} - def __init__(self, formats=None): + def __init__(self, formats: typing.Iterable[str] | None = None): if formats is None: self.checkers = self.checkers.copy() else: @@ -50,7 +53,9 @@ def __init__(self, formats=None): def __repr__(self): return "".format(sorted(self.checkers)) - def checks(self, format, raises=()): + def checks( + self, format: str, raises: _RaisesType = (), + ) -> typing.Callable[[_F], _F]: """ Register a decorated function as validating a new format. @@ -70,14 +75,23 @@ def checks(self, format, raises=()): resulting validation error. """ - def _checks(func): + def _checks(func: _F) -> _F: self.checkers[format] = (func, raises) return func + return _checks - cls_checks = classmethod(checks) + @classmethod + def cls_checks( + cls, format: str, raises: _RaisesType = (), + ) -> typing.Callable[[_F], _F]: + def _checks(func: _F) -> _F: + cls.checkers[format] = (func, raises) + return func + + return _checks - def check(self, instance, format): + def check(self, instance: object, format: str) -> None: """ Check whether the instance conforms to the given format. @@ -109,7 +123,7 @@ def check(self, instance, format): if not result: raise FormatError(f"{instance!r} is not a {format!r}", cause=cause) - def conforms(self, instance, format): + def conforms(self, instance: object, format: str) -> bool: """ Check whether the instance conforms to the given format. @@ -143,7 +157,7 @@ def conforms(self, instance, format): draft201909_format_checker = FormatChecker() draft202012_format_checker = FormatChecker() -_draft_checkers = dict( +_draft_checkers: dict[str, FormatChecker] = dict( draft3=draft3_format_checker, draft4=draft4_format_checker, draft6=draft6_format_checker, @@ -162,7 +176,7 @@ def _checks_drafts( draft201909=None, draft202012=None, raises=(), -): +) -> typing.Callable[[_F], _F]: draft3 = draft3 or name draft4 = draft4 or name draft6 = draft6 or name @@ -170,7 +184,7 @@ def _checks_drafts( draft201909 = draft201909 or name draft202012 = draft202012 or name - def wrap(func): + def wrap(func: _F) -> _F: if draft3: func = _draft_checkers["draft3"].checks(draft3, raises)(func) if draft4: @@ -195,12 +209,13 @@ def wrap(func): raises, )(func) return func + return wrap @_checks_drafts(name="idn-email") @_checks_drafts(name="email") -def is_email(instance): +def is_email(instance: object) -> bool: if not isinstance(instance, str): return True return "@" in instance @@ -215,14 +230,14 @@ def is_email(instance): draft202012="ipv4", raises=ipaddress.AddressValueError, ) -def is_ipv4(instance): +def is_ipv4(instance: object) -> bool: if not isinstance(instance, str): return True - return ipaddress.IPv4Address(instance) + return bool(ipaddress.IPv4Address(instance)) @_checks_drafts(name="ipv6", raises=ipaddress.AddressValueError) -def is_ipv6(instance): +def is_ipv6(instance: object) -> bool: if not isinstance(instance, str): return True address = ipaddress.IPv6Address(instance) @@ -240,7 +255,7 @@ def is_ipv6(instance): draft201909="hostname", draft202012="hostname", ) - def is_host_name(instance): + def is_host_name(instance: object) -> bool: if not isinstance(instance, str): return True return FQDN(instance).is_valid @@ -256,7 +271,7 @@ def is_host_name(instance): draft202012="idn-hostname", raises=(idna.IDNAError, UnicodeError), ) - def is_idn_host_name(instance): + def is_idn_host_name(instance: object) -> bool: if not isinstance(instance, str): return True idna.encode(instance) @@ -270,7 +285,7 @@ def is_idn_host_name(instance): from rfc3986_validator import validate_rfc3986 @_checks_drafts(name="uri") - def is_uri(instance): + def is_uri(instance: object) -> bool: if not isinstance(instance, str): return True return validate_rfc3986(instance, rule="URI") @@ -282,19 +297,20 @@ def is_uri(instance): draft202012="uri-reference", raises=ValueError, ) - def is_uri_reference(instance): + def is_uri_reference(instance: object) -> bool: if not isinstance(instance, str): return True return validate_rfc3986(instance, rule="URI_reference") else: + @_checks_drafts( draft7="iri", draft201909="iri", draft202012="iri", raises=ValueError, ) - def is_iri(instance): + def is_iri(instance: object) -> bool: if not isinstance(instance, str): return True return rfc3987.parse(instance, rule="IRI") @@ -305,13 +321,13 @@ def is_iri(instance): draft202012="iri-reference", raises=ValueError, ) - def is_iri_reference(instance): + def is_iri_reference(instance: object) -> bool: if not isinstance(instance, str): return True return rfc3987.parse(instance, rule="IRI_reference") @_checks_drafts(name="uri", raises=ValueError) - def is_uri(instance): + def is_uri(instance: object) -> bool: if not isinstance(instance, str): return True return rfc3987.parse(instance, rule="URI") @@ -323,16 +339,17 @@ def is_uri(instance): draft202012="uri-reference", raises=ValueError, ) - def is_uri_reference(instance): + def is_uri_reference(instance: object) -> bool: if not isinstance(instance, str): return True return rfc3987.parse(instance, rule="URI_reference") + with suppress(ImportError): from rfc3339_validator import validate_rfc3339 @_checks_drafts(name="date-time") - def is_datetime(instance): + def is_datetime(instance: object) -> bool: if not isinstance(instance, str): return True return validate_rfc3339(instance.upper()) @@ -342,17 +359,17 @@ def is_datetime(instance): draft201909="time", draft202012="time", ) - def is_time(instance): + def is_time(instance: object) -> bool: if not isinstance(instance, str): return True return is_datetime("1970-01-01T" + instance) @_checks_drafts(name="regex", raises=re.error) -def is_regex(instance): +def is_regex(instance: object) -> bool: if not isinstance(instance, str): return True - return re.compile(instance) + return bool(re.compile(instance)) @_checks_drafts( @@ -362,28 +379,28 @@ def is_regex(instance): draft202012="date", raises=ValueError, ) -def is_date(instance): +def is_date(instance: object) -> bool: if not isinstance(instance, str): return True - return instance.isascii() and datetime.date.fromisoformat(instance) + return bool(instance.isascii() and datetime.date.fromisoformat(instance)) @_checks_drafts(draft3="time", raises=ValueError) -def is_draft3_time(instance): +def is_draft3_time(instance: object) -> bool: if not isinstance(instance, str): return True - return datetime.datetime.strptime(instance, "%H:%M:%S") + return bool(datetime.datetime.strptime(instance, "%H:%M:%S")) with suppress(ImportError): from webcolors import CSS21_NAMES_TO_HEX import webcolors - def is_css_color_code(instance): + def is_css_color_code(instance: object) -> bool: return webcolors.normalize_hex(instance) @_checks_drafts(draft3="color", raises=(ValueError, TypeError)) - def is_css21_color(instance): + def is_css21_color(instance: object) -> bool: if ( not isinstance(instance, str) or instance.lower() in CSS21_NAMES_TO_HEX @@ -402,10 +419,10 @@ def is_css21_color(instance): draft202012="json-pointer", raises=jsonpointer.JsonPointerException, ) - def is_json_pointer(instance): + def is_json_pointer(instance: object) -> bool: if not isinstance(instance, str): return True - return jsonpointer.JsonPointer(instance) + return bool(jsonpointer.JsonPointer(instance)) # TODO: I don't want to maintain this, so it # needs to go either into jsonpointer (pending @@ -417,7 +434,7 @@ def is_json_pointer(instance): draft202012="relative-json-pointer", raises=jsonpointer.JsonPointerException, ) - def is_relative_json_pointer(instance): + def is_relative_json_pointer(instance: object) -> bool: # Definition taken from: # https://tools.ietf.org/html/draft-handrews-relative-json-pointer-01#section-3 if not isinstance(instance, str): @@ -437,7 +454,7 @@ def is_relative_json_pointer(instance): rest = instance[i:] break - return (rest == "#") or jsonpointer.JsonPointer(rest) + return (rest == "#") or bool(jsonpointer.JsonPointer(rest)) with suppress(ImportError): @@ -449,7 +466,7 @@ def is_relative_json_pointer(instance): draft201909="uri-template", draft202012="uri-template", ) - def is_uri_template(instance): + def is_uri_template(instance: object) -> bool: if not isinstance(instance, str): return True return uri_template.validate(instance) @@ -463,10 +480,10 @@ def is_uri_template(instance): draft202012="duration", raises=isoduration.DurationParsingException, ) - def is_duration(instance): + def is_duration(instance: object) -> bool: if not isinstance(instance, str): return True - return isoduration.parse_duration(instance) + return bool(isoduration.parse_duration(instance)) @_checks_drafts( @@ -474,7 +491,7 @@ def is_duration(instance): draft202012="uuid", raises=ValueError, ) -def is_uuid(instance): +def is_uuid(instance: object) -> bool: if not isinstance(instance, str): return True UUID(instance) diff --git a/src/poetry/core/_vendor/jsonschema/_legacy_validators.py b/src/poetry/core/_vendor/jsonschema/_legacy_validators.py index c8eff2cc5..5be628fe7 100644 --- a/src/poetry/core/_vendor/jsonschema/_legacy_validators.py +++ b/src/poetry/core/_vendor/jsonschema/_legacy_validators.py @@ -221,4 +221,8 @@ def recursiveRef(validator, recursiveRef, instance, schema): fragment = recursiveRef.lstrip("#") subschema = validator.resolver.resolve_fragment(target, fragment) - yield from validator.descend(instance, subschema) + # FIXME: This is gutted (and not calling .descend) because it can trigger + # recursion errors, so there's a bug here. Re-enable the tests to + # see it. + subschema + return [] diff --git a/src/poetry/core/_vendor/jsonschema/_reflect.py b/src/poetry/core/_vendor/jsonschema/_reflect.py index 39ee7a6c8..01f2dc320 100644 --- a/src/poetry/core/_vendor/jsonschema/_reflect.py +++ b/src/poetry/core/_vendor/jsonschema/_reflect.py @@ -60,7 +60,7 @@ def _importAndCheckStack(importName): Import the given name as a module, then walk the stack to determine whether the failure was the module not existing, or some code in the module (for example a dependent import) failing. This can be helpful to determine - whether any actual application code was run. For example, to distiguish + whether any actual application code was run. For example, to distinguish administrative error (entering the wrong module name), from programmer error (writing buggy code in a module that fails to import). diff --git a/src/poetry/core/_vendor/jsonschema/_validators.py b/src/poetry/core/_vendor/jsonschema/_validators.py index 9a07f5ec3..874e8796f 100644 --- a/src/poetry/core/_vendor/jsonschema/_validators.py +++ b/src/poetry/core/_vendor/jsonschema/_validators.py @@ -418,6 +418,8 @@ def if_(validator, if_schema, instance, schema): def unevaluatedItems(validator, unevaluatedItems, instance, schema): + if not validator.is_type(instance, "array"): + return evaluated_item_indexes = find_evaluated_item_indexes_by_schema( validator, instance, schema, ) @@ -431,6 +433,8 @@ def unevaluatedItems(validator, unevaluatedItems, instance, schema): def unevaluatedProperties(validator, unevaluatedProperties, instance, schema): + if not validator.is_type(instance, "object"): + return evaluated_property_keys = find_evaluated_property_keys_by_schema( validator, instance, schema, ) diff --git a/src/poetry/core/_vendor/pyparsing/__init__.py b/src/poetry/core/_vendor/pyparsing/__init__.py index 45f334d04..7802ff158 100644 --- a/src/poetry/core/_vendor/pyparsing/__init__.py +++ b/src/poetry/core/_vendor/pyparsing/__init__.py @@ -128,8 +128,8 @@ def __repr__(self): ) -__version_info__ = version_info(3, 0, 8, "final", 0) -__version_time__ = "09 Apr 2022 23:29 UTC" +__version_info__ = version_info(3, 0, 9, "final", 0) +__version_time__ = "05 May 2022 07:02 UTC" __version__ = __version_info__.__version__ __versionTime__ = __version_time__ __author__ = "Paul McGuire " diff --git a/src/poetry/core/_vendor/pyparsing/actions.py b/src/poetry/core/_vendor/pyparsing/actions.py index 2bcc5502b..f72c66e74 100644 --- a/src/poetry/core/_vendor/pyparsing/actions.py +++ b/src/poetry/core/_vendor/pyparsing/actions.py @@ -55,7 +55,7 @@ def replace_with(repl_str): na = one_of("N/A NA").set_parse_action(replace_with(math.nan)) term = na | num - OneOrMore(term).parse_string("324 234 N/A 234") # -> [324, 234, nan, 234] + term[1, ...].parse_string("324 234 N/A 234") # -> [324, 234, nan, 234] """ return lambda s, l, t: [repl_str] diff --git a/src/poetry/core/_vendor/pyparsing/core.py b/src/poetry/core/_vendor/pyparsing/core.py index 454bd57d0..9acba3f3e 100644 --- a/src/poetry/core/_vendor/pyparsing/core.py +++ b/src/poetry/core/_vendor/pyparsing/core.py @@ -2,9 +2,8 @@ # core.py # import os +import typing from typing import ( - Optional as OptionalType, - Iterable as IterableType, NamedTuple, Union, Callable, @@ -14,7 +13,6 @@ List, TextIO, Set, - Dict as DictType, Sequence, ) from abc import ABC, abstractmethod @@ -192,7 +190,7 @@ def enable_all_warnings() -> None: def _should_enable_warnings( - cmd_line_warn_options: IterableType[str], warn_env_var: OptionalType[str] + cmd_line_warn_options: typing.Iterable[str], warn_env_var: typing.Optional[str] ) -> bool: enable = bool(warn_env_var) for warn_opt in cmd_line_warn_options: @@ -404,7 +402,7 @@ class ParserElement(ABC): DEFAULT_WHITE_CHARS: str = " \n\t\r" verbose_stacktrace: bool = False - _literalStringClass: OptionalType[type] = None + _literalStringClass: typing.Optional[type] = None @staticmethod def set_default_whitespace_chars(chars: str) -> None: @@ -414,11 +412,11 @@ def set_default_whitespace_chars(chars: str) -> None: Example:: # default whitespace chars are space, and newline - OneOrMore(Word(alphas)).parse_string("abc def\nghi jkl") # -> ['abc', 'def', 'ghi', 'jkl'] + Word(alphas)[1, ...].parse_string("abc def\nghi jkl") # -> ['abc', 'def', 'ghi', 'jkl'] # change to just treat newline as significant ParserElement.set_default_whitespace_chars(" \t") - OneOrMore(Word(alphas)).parse_string("abc def\nghi jkl") # -> ['abc', 'def'] + Word(alphas)[1, ...].parse_string("abc def\nghi jkl") # -> ['abc', 'def'] """ ParserElement.DEFAULT_WHITE_CHARS = chars @@ -450,13 +448,13 @@ def inline_literals_using(cls: type) -> None: ParserElement._literalStringClass = cls class DebugActions(NamedTuple): - debug_try: OptionalType[DebugStartAction] - debug_match: OptionalType[DebugSuccessAction] - debug_fail: OptionalType[DebugExceptionAction] + debug_try: typing.Optional[DebugStartAction] + debug_match: typing.Optional[DebugSuccessAction] + debug_fail: typing.Optional[DebugExceptionAction] def __init__(self, savelist: bool = False): self.parseAction: List[ParseAction] = list() - self.failAction: OptionalType[ParseFailAction] = None + self.failAction: typing.Optional[ParseFailAction] = None self.customName = None self._defaultName = None self.resultsName = None @@ -510,7 +508,7 @@ def copy(self) -> "ParserElement": integerK = integer.copy().add_parse_action(lambda toks: toks[0] * 1024) + Suppress("K") integerM = integer.copy().add_parse_action(lambda toks: toks[0] * 1024 * 1024) + Suppress("M") - print(OneOrMore(integerK | integerM | integer).parse_string("5K 100 640K 256M")) + print((integerK | integerM | integer)[1, ...].parse_string("5K 100 640K 256M")) prints:: @@ -895,7 +893,7 @@ def can_parse_next(self, instring: str, loc: int) -> bool: # cache for left-recursion in Forward references recursion_lock = RLock() - recursion_memos: DictType[ + recursion_memos: typing.Dict[ Tuple[int, "Forward", bool], Tuple[int, Union[ParseResults, Exception]] ] = {} @@ -985,7 +983,7 @@ def disable_memoization() -> None: @staticmethod def enable_left_recursion( - cache_size_limit: OptionalType[int] = None, *, force=False + cache_size_limit: typing.Optional[int] = None, *, force=False ) -> None: """ Enables "bounded recursion" parsing, which allows for both direct and indirect @@ -1738,7 +1736,7 @@ def ignore(self, other: "ParserElement") -> "ParserElement": Example:: - patt = OneOrMore(Word(alphas)) + patt = Word(alphas)[1, ...] patt.parse_string('ablaj /* comment */ lskjd') # -> ['ablaj'] @@ -1798,7 +1796,7 @@ def set_debug(self, flag: bool = True) -> "ParserElement": # turn on debugging for wd wd.set_debug() - OneOrMore(term).parse_string("abc 123 xyz 890") + term[1, ...].parse_string("abc 123 xyz 890") prints:: @@ -1953,12 +1951,12 @@ def run_tests( self, tests: Union[str, List[str]], parse_all: bool = True, - comment: OptionalType[Union["ParserElement", str]] = "#", + comment: typing.Optional[Union["ParserElement", str]] = "#", full_dump: bool = True, print_results: bool = True, failure_tests: bool = False, post_parse: Callable[[str, ParseResults], str] = None, - file: OptionalType[TextIO] = None, + file: typing.Optional[TextIO] = None, with_line_numbers: bool = False, *, parseAll: bool = True, @@ -2385,11 +2383,11 @@ class Keyword(Token): def __init__( self, match_string: str = "", - ident_chars: OptionalType[str] = None, + ident_chars: typing.Optional[str] = None, caseless: bool = False, *, matchString: str = "", - identChars: OptionalType[str] = None, + identChars: typing.Optional[str] = None, ): super().__init__() identChars = identChars or ident_chars @@ -2479,7 +2477,7 @@ class CaselessLiteral(Literal): Example:: - OneOrMore(CaselessLiteral("CMD")).parse_string("cmd CMD Cmd10") + CaselessLiteral("CMD")[1, ...].parse_string("cmd CMD Cmd10") # -> ['CMD', 'CMD', 'CMD'] (Contrast with example for :class:`CaselessKeyword`.) @@ -2504,7 +2502,7 @@ class CaselessKeyword(Keyword): Example:: - OneOrMore(CaselessKeyword("CMD")).parse_string("cmd CMD Cmd10") + CaselessKeyword("CMD")[1, ...].parse_string("cmd CMD Cmd10") # -> ['CMD', 'CMD'] (Contrast with example for :class:`CaselessLiteral`.) @@ -2513,10 +2511,10 @@ class CaselessKeyword(Keyword): def __init__( self, match_string: str = "", - ident_chars: OptionalType[str] = None, + ident_chars: typing.Optional[str] = None, *, matchString: str = "", - identChars: OptionalType[str] = None, + identChars: typing.Optional[str] = None, ): identChars = identChars or ident_chars match_string = matchString or match_string @@ -2680,17 +2678,17 @@ class Word(Token): def __init__( self, init_chars: str = "", - body_chars: OptionalType[str] = None, + body_chars: typing.Optional[str] = None, min: int = 1, max: int = 0, exact: int = 0, as_keyword: bool = False, - exclude_chars: OptionalType[str] = None, + exclude_chars: typing.Optional[str] = None, *, - initChars: OptionalType[str] = None, - bodyChars: OptionalType[str] = None, + initChars: typing.Optional[str] = None, + bodyChars: typing.Optional[str] = None, asKeyword: bool = False, - excludeChars: OptionalType[str] = None, + excludeChars: typing.Optional[str] = None, ): initChars = initChars or init_chars bodyChars = bodyChars or body_chars @@ -2872,10 +2870,10 @@ def __init__( self, charset: str, as_keyword: bool = False, - exclude_chars: OptionalType[str] = None, + exclude_chars: typing.Optional[str] = None, *, asKeyword: bool = False, - excludeChars: OptionalType[str] = None, + excludeChars: typing.Optional[str] = None, ): asKeyword = asKeyword or as_keyword excludeChars = excludeChars or exclude_chars @@ -3088,18 +3086,18 @@ class QuotedString(Token): def __init__( self, quote_char: str = "", - esc_char: OptionalType[str] = None, - esc_quote: OptionalType[str] = None, + esc_char: typing.Optional[str] = None, + esc_quote: typing.Optional[str] = None, multiline: bool = False, unquote_results: bool = True, - end_quote_char: OptionalType[str] = None, + end_quote_char: typing.Optional[str] = None, convert_whitespace_escapes: bool = True, *, quoteChar: str = "", - escChar: OptionalType[str] = None, - escQuote: OptionalType[str] = None, + escChar: typing.Optional[str] = None, + escQuote: typing.Optional[str] = None, unquoteResults: bool = True, - endQuoteChar: OptionalType[str] = None, + endQuoteChar: typing.Optional[str] = None, convertWhitespaceEscapes: bool = True, ): super().__init__() @@ -3600,7 +3598,7 @@ class ParseExpression(ParserElement): post-processing parsed tokens. """ - def __init__(self, exprs: IterableType[ParserElement], savelist: bool = False): + def __init__(self, exprs: typing.Iterable[ParserElement], savelist: bool = False): super().__init__(savelist) self.exprs: List[ParserElement] if isinstance(exprs, _generatorType): @@ -3767,7 +3765,7 @@ class And(ParseExpression): Example:: integer = Word(nums) - name_expr = OneOrMore(Word(alphas)) + name_expr = Word(alphas)[1, ...] expr = And([integer("id"), name_expr("name"), integer("age")]) # more easily written as: @@ -3782,7 +3780,9 @@ def __init__(self, *args, **kwargs): def _generateDefaultName(self): return "-" - def __init__(self, exprs_arg: IterableType[ParserElement], savelist: bool = True): + def __init__( + self, exprs_arg: typing.Iterable[ParserElement], savelist: bool = True + ): exprs: List[ParserElement] = list(exprs_arg) if exprs and Ellipsis in exprs: tmp = [] @@ -3926,7 +3926,7 @@ class Or(ParseExpression): [['123'], ['3.1416'], ['789']] """ - def __init__(self, exprs: IterableType[ParserElement], savelist: bool = False): + def __init__(self, exprs: typing.Iterable[ParserElement], savelist: bool = False): super().__init__(exprs, savelist) if self.exprs: self.mayReturnEmpty = any(e.mayReturnEmpty for e in self.exprs) @@ -4081,7 +4081,7 @@ class MatchFirst(ParseExpression): print(number.search_string("123 3.1416 789")) # Better -> [['123'], ['3.1416'], ['789']] """ - def __init__(self, exprs: IterableType[ParserElement], savelist: bool = False): + def __init__(self, exprs: typing.Iterable[ParserElement], savelist: bool = False): super().__init__(exprs, savelist) if self.exprs: self.mayReturnEmpty = any(e.mayReturnEmpty for e in self.exprs) @@ -4232,7 +4232,7 @@ class Each(ParseExpression): - size: 20 """ - def __init__(self, exprs: IterableType[ParserElement], savelist: bool = True): + def __init__(self, exprs: typing.Iterable[ParserElement], savelist: bool = True): super().__init__(exprs, savelist) if self.exprs: self.mayReturnEmpty = all(e.mayReturnEmpty for e in self.exprs) @@ -4568,7 +4568,7 @@ class FollowedBy(ParseElementEnhance): label = data_word + FollowedBy(':') attr_expr = Group(label + Suppress(':') + OneOrMore(data_word, stop_on=label).set_parse_action(' '.join)) - OneOrMore(attr_expr).parse_string("shape: SQUARE color: BLACK posn: upper left").pprint() + attr_expr[1, ...].parse_string("shape: SQUARE color: BLACK posn: upper left").pprint() prints:: @@ -4619,7 +4619,7 @@ class PrecededBy(ParseElementEnhance): """ def __init__( - self, expr: Union[ParserElement, str], retreat: OptionalType[int] = None + self, expr: Union[ParserElement, str], retreat: typing.Optional[int] = None ): super().__init__(expr) self.expr = self.expr().leave_whitespace() @@ -4730,7 +4730,7 @@ class NotAny(ParseElementEnhance): # very crude boolean expression - to support parenthesis groups and # operation hierarchy, use infix_notation - boolean_expr = boolean_term + ZeroOrMore((AND | OR) + boolean_term) + boolean_expr = boolean_term + ((AND | OR) + boolean_term)[...] # integers that are followed by "." are actually floats integer = Word(nums) + ~Char(".") @@ -4758,9 +4758,9 @@ class _MultipleMatch(ParseElementEnhance): def __init__( self, expr: ParserElement, - stop_on: OptionalType[Union[ParserElement, str]] = None, + stop_on: typing.Optional[Union[ParserElement, str]] = None, *, - stopOn: OptionalType[Union[ParserElement, str]] = None, + stopOn: typing.Optional[Union[ParserElement, str]] = None, ): super().__init__(expr) stopOn = stopOn or stop_on @@ -4849,7 +4849,7 @@ class OneOrMore(_MultipleMatch): attr_expr = Group(label + Suppress(':') + OneOrMore(data_word).set_parse_action(' '.join)) text = "shape: SQUARE posn: upper left color: BLACK" - OneOrMore(attr_expr).parse_string(text).pprint() # Fail! read 'color' as data instead of next label -> [['shape', 'SQUARE color']] + attr_expr[1, ...].parse_string(text).pprint() # Fail! read 'color' as data instead of next label -> [['shape', 'SQUARE color']] # use stop_on attribute for OneOrMore to avoid reading label string as part of the data attr_expr = Group(label + Suppress(':') + OneOrMore(data_word, stop_on=label).set_parse_action(' '.join)) @@ -4879,9 +4879,9 @@ class ZeroOrMore(_MultipleMatch): def __init__( self, expr: ParserElement, - stop_on: OptionalType[Union[ParserElement, str]] = None, + stop_on: typing.Optional[Union[ParserElement, str]] = None, *, - stopOn: OptionalType[Union[ParserElement, str]] = None, + stopOn: typing.Optional[Union[ParserElement, str]] = None, ): super().__init__(expr, stopOn=stopOn or stop_on) self.mayReturnEmpty = True @@ -5046,7 +5046,7 @@ def __init__( other: Union[ParserElement, str], include: bool = False, ignore: bool = None, - fail_on: OptionalType[Union[ParserElement, str]] = None, + fail_on: typing.Optional[Union[ParserElement, str]] = None, *, failOn: Union[ParserElement, str] = None, ): @@ -5143,7 +5143,7 @@ class Forward(ParseElementEnhance): parser created using ``Forward``. """ - def __init__(self, other: OptionalType[Union[ParserElement, str]] = None): + def __init__(self, other: typing.Optional[Union[ParserElement, str]] = None): self.caller_frame = traceback.extract_stack(limit=2)[0] super().__init__(other, savelist=False) self.lshift_line = None @@ -5395,7 +5395,7 @@ def __init__( join_string: str = "", adjacent: bool = True, *, - joinString: OptionalType[str] = None, + joinString: typing.Optional[str] = None, ): super().__init__(expr) joinString = joinString if joinString is not None else join_string @@ -5482,10 +5482,10 @@ class Dict(TokenConverter): attr_expr = (label + Suppress(':') + OneOrMore(data_word, stop_on=label).set_parse_action(' '.join)) # print attributes as plain groups - print(OneOrMore(attr_expr).parse_string(text).dump()) + print(attr_expr[1, ...].parse_string(text).dump()) - # instead of OneOrMore(expr), parse using Dict(OneOrMore(Group(expr))) - Dict will auto-assign names - result = Dict(OneOrMore(Group(attr_expr))).parse_string(text) + # instead of OneOrMore(expr), parse using Dict(Group(expr)[1, ...]) - Dict will auto-assign names + result = Dict(Group(attr_expr)[1, ...]).parse_string(text) print(result.dump()) # access named fields as dict entries, or output as dict @@ -5558,12 +5558,12 @@ class Suppress(TokenConverter): source = "a, b, c,d" wd = Word(alphas) - wd_list1 = wd + ZeroOrMore(',' + wd) + wd_list1 = wd + (',' + wd)[...] print(wd_list1.parse_string(source)) # often, delimiters that are useful during parsing are just in the # way afterward - use Suppress to keep them out of the parsed output - wd_list2 = wd + ZeroOrMore(Suppress(',') + wd) + wd_list2 = wd + (Suppress(',') + wd)[...] print(wd_list2.parse_string(source)) # Skipped text (using '...') can be suppressed as well @@ -5622,7 +5622,7 @@ def trace_parse_action(f: ParseAction) -> ParseAction: def remove_duplicate_chars(tokens): return ''.join(sorted(set(''.join(tokens)))) - wds = OneOrMore(wd).set_parse_action(remove_duplicate_chars) + wds = wd[1, ...].set_parse_action(remove_duplicate_chars) print(wds.parse_string("slkdjs sld sldd sdlf sdljf")) prints:: @@ -5728,18 +5728,18 @@ def token_map(func, *args) -> ParseAction: Example (compare the last to example in :class:`ParserElement.transform_string`:: - hex_ints = OneOrMore(Word(hexnums)).set_parse_action(token_map(int, 16)) + hex_ints = Word(hexnums)[1, ...].set_parse_action(token_map(int, 16)) hex_ints.run_tests(''' 00 11 22 aa FF 0a 0d 1a ''') upperword = Word(alphas).set_parse_action(token_map(str.upper)) - OneOrMore(upperword).run_tests(''' + upperword[1, ...].run_tests(''' my kingdom for a horse ''') wd = Word(alphas).set_parse_action(token_map(str.title)) - OneOrMore(wd).set_parse_action(' '.join).run_tests(''' + wd[1, ...].set_parse_action(' '.join).run_tests(''' now is the winter of our discontent made glorious summer by this sun of york ''') @@ -5795,7 +5795,9 @@ def autoname_elements() -> None: # build list of built-in expressions, for future reference if a global default value # gets updated -_builtin_exprs = [v for v in vars().values() if isinstance(v, ParserElement)] +_builtin_exprs: List[ParserElement] = [ + v for v in vars().values() if isinstance(v, ParserElement) +] # backward compatibility names tokenMap = token_map diff --git a/src/poetry/core/_vendor/pyparsing/diagram/__init__.py b/src/poetry/core/_vendor/pyparsing/diagram/__init__.py index 2d0c587cb..898644755 100644 --- a/src/poetry/core/_vendor/pyparsing/diagram/__init__.py +++ b/src/poetry/core/_vendor/pyparsing/diagram/__init__.py @@ -1,9 +1,8 @@ import railroad import pyparsing -from pkg_resources import resource_filename +import typing from typing import ( List, - Optional, NamedTuple, Generic, TypeVar, @@ -17,13 +16,41 @@ import inspect -with open(resource_filename(__name__, "template.jinja2"), encoding="utf-8") as fp: - template = Template(fp.read()) +jinja2_template_source = """\ + + + + {% if not head %} + + {% else %} + {{ head | safe }} + {% endif %} + + +{{ body | safe }} +{% for diagram in diagrams %} +
+

{{ diagram.title }}

+
{{ diagram.text }}
+
+ {{ diagram.svg }} +
+
+{% endfor %} + + +""" + +template = Template(jinja2_template_source) # Note: ideally this would be a dataclass, but we're supporting Python 3.5+ so we can't do this yet NamedDiagram = NamedTuple( "NamedDiagram", - [("name", str), ("diagram", Optional[railroad.DiagramItem]), ("index", int)], + [("name", str), ("diagram", typing.Optional[railroad.DiagramItem]), ("index", int)], ) """ A simple structure for associating a name with a railroad diagram @@ -107,6 +134,8 @@ def railroad_to_html(diagrams: List[NamedDiagram], **kwargs) -> str: """ data = [] for diagram in diagrams: + if diagram.diagram is None: + continue io = StringIO() diagram.diagram.writeSvg(io.write) title = diagram.name @@ -135,7 +164,7 @@ def resolve_partial(partial: "EditablePartial[T]") -> T: def to_railroad( element: pyparsing.ParserElement, - diagram_kwargs: Optional[dict] = None, + diagram_kwargs: typing.Optional[dict] = None, vertical: int = 3, show_results_names: bool = False, show_groups: bool = False, @@ -216,12 +245,12 @@ def __init__( parent: EditablePartial, number: int, name: str = None, - parent_index: Optional[int] = None, + parent_index: typing.Optional[int] = None, ): #: The pyparsing element that this represents self.element: pyparsing.ParserElement = element #: The name of the element - self.name: str = name + self.name: typing.Optional[str] = name #: The output Railroad element in an unconverted state self.converted: EditablePartial = converted #: The parent Railroad element, which we store so that we can extract this if it's duplicated @@ -229,7 +258,7 @@ def __init__( #: The order in which we found this element, used for sorting diagrams if this is extracted into a diagram self.number: int = number #: The index of this inside its parent - self.parent_index: Optional[int] = parent_index + self.parent_index: typing.Optional[int] = parent_index #: If true, we should extract this out into a subdiagram self.extract: bool = False #: If true, all of this element's children have been filled out @@ -270,7 +299,7 @@ class ConverterState: Stores some state that persists between recursions into the element tree """ - def __init__(self, diagram_kwargs: Optional[dict] = None): + def __init__(self, diagram_kwargs: typing.Optional[dict] = None): #: A dictionary mapping ParserElements to state relating to them self._element_diagram_states: Dict[int, ElementState] = {} #: A dictionary mapping ParserElement IDs to subdiagrams generated from them @@ -361,14 +390,14 @@ def _apply_diagram_item_enhancements(fn): def _inner( element: pyparsing.ParserElement, - parent: Optional[EditablePartial], + parent: typing.Optional[EditablePartial], lookup: ConverterState = None, vertical: int = None, index: int = 0, name_hint: str = None, show_results_names: bool = False, show_groups: bool = False, - ) -> Optional[EditablePartial]: + ) -> typing.Optional[EditablePartial]: ret = fn( element, @@ -412,14 +441,14 @@ def _visible_exprs(exprs: Iterable[pyparsing.ParserElement]): @_apply_diagram_item_enhancements def _to_diagram_element( element: pyparsing.ParserElement, - parent: Optional[EditablePartial], + parent: typing.Optional[EditablePartial], lookup: ConverterState = None, vertical: int = None, index: int = 0, name_hint: str = None, show_results_names: bool = False, show_groups: bool = False, -) -> Optional[EditablePartial]: +) -> typing.Optional[EditablePartial]: """ Recursively converts a PyParsing Element to a railroad Element :param lookup: The shared converter state that keeps track of useful things @@ -526,7 +555,9 @@ def _to_diagram_element( else: ret = EditablePartial.from_call(railroad.Group, label="", item="") elif isinstance(element, pyparsing.TokenConverter): - ret = EditablePartial.from_call(AnnotatedItem, label=type(element).__name__.lower(), item="") + ret = EditablePartial.from_call( + AnnotatedItem, label=type(element).__name__.lower(), item="" + ) elif isinstance(element, pyparsing.Opt): ret = EditablePartial.from_call(railroad.Optional, item="") elif isinstance(element, pyparsing.OneOrMore): diff --git a/src/poetry/core/_vendor/pyparsing/diagram/template.jinja2 b/src/poetry/core/_vendor/pyparsing/diagram/template.jinja2 deleted file mode 100644 index d2219fb01..000000000 --- a/src/poetry/core/_vendor/pyparsing/diagram/template.jinja2 +++ /dev/null @@ -1,26 +0,0 @@ - - - - {% if not head %} - - {% else %} - {{ hear | safe }} - {% endif %} - - -{{ body | safe }} -{% for diagram in diagrams %} -
-

{{ diagram.title }}

-
{{ diagram.text }}
-
- {{ diagram.svg }} -
-
-{% endfor %} - - diff --git a/src/poetry/core/_vendor/pyparsing/exceptions.py b/src/poetry/core/_vendor/pyparsing/exceptions.py index e06513eb0..a38447bb0 100644 --- a/src/poetry/core/_vendor/pyparsing/exceptions.py +++ b/src/poetry/core/_vendor/pyparsing/exceptions.py @@ -2,7 +2,7 @@ import re import sys -from typing import Optional +import typing from .util import col, line, lineno, _collapse_string_to_ranges from .unicode import pyparsing_unicode as ppu @@ -25,7 +25,7 @@ def __init__( self, pstr: str, loc: int = 0, - msg: Optional[str] = None, + msg: typing.Optional[str] = None, elem=None, ): self.loc = loc diff --git a/src/poetry/core/_vendor/pyparsing/helpers.py b/src/poetry/core/_vendor/pyparsing/helpers.py index be8a36578..9588b3b78 100644 --- a/src/poetry/core/_vendor/pyparsing/helpers.py +++ b/src/poetry/core/_vendor/pyparsing/helpers.py @@ -1,6 +1,7 @@ # helpers.py import html.entities import re +import typing from . import __diag__ from .core import * @@ -14,8 +15,8 @@ def delimited_list( expr: Union[str, ParserElement], delim: Union[str, ParserElement] = ",", combine: bool = False, - min: OptionalType[int] = None, - max: OptionalType[int] = None, + min: typing.Optional[int] = None, + max: typing.Optional[int] = None, *, allow_trailing_delim: bool = False, ) -> ParserElement: @@ -69,9 +70,9 @@ def delimited_list( def counted_array( expr: ParserElement, - int_expr: OptionalType[ParserElement] = None, + int_expr: typing.Optional[ParserElement] = None, *, - intExpr: OptionalType[ParserElement] = None, + intExpr: typing.Optional[ParserElement] = None, ) -> ParserElement: """Helper to define a counted list of expressions. @@ -197,7 +198,7 @@ def must_match_these_tokens(s, l, t): def one_of( - strs: Union[IterableType[str], str], + strs: Union[typing.Iterable[str], str], caseless: bool = False, use_regex: bool = True, as_keyword: bool = False, @@ -337,7 +338,7 @@ def dict_of(key: ParserElement, value: ParserElement) -> ParserElement: text = "shape: SQUARE posn: upper left color: light blue texture: burlap" attr_expr = (label + Suppress(':') + OneOrMore(data_word, stop_on=label).set_parse_action(' '.join)) - print(OneOrMore(attr_expr).parse_string(text).dump()) + print(attr_expr[1, ...].parse_string(text).dump()) attr_label = label attr_value = Suppress(':') + OneOrMore(data_word, stop_on=label).set_parse_action(' '.join) @@ -461,7 +462,7 @@ def locatedExpr(expr: ParserElement) -> ParserElement: def nested_expr( opener: Union[str, ParserElement] = "(", closer: Union[str, ParserElement] = ")", - content: OptionalType[ParserElement] = None, + content: typing.Optional[ParserElement] = None, ignore_expr: ParserElement = quoted_string(), *, ignoreExpr: ParserElement = quoted_string(), @@ -682,6 +683,8 @@ def make_xml_tags( return _makeTags(tag_str, True) +any_open_tag: ParserElement +any_close_tag: ParserElement any_open_tag, any_close_tag = make_html_tags( Word(alphas, alphanums + "_:").set_name("any tag") ) @@ -710,7 +713,7 @@ class OpAssoc(Enum): InfixNotationOperatorArgType, int, OpAssoc, - OptionalType[ParseAction], + typing.Optional[ParseAction], ], Tuple[ InfixNotationOperatorArgType, @@ -840,7 +843,7 @@ def parseImpl(self, instring, loc, doActions=True): if rightLeftAssoc not in (OpAssoc.LEFT, OpAssoc.RIGHT): raise ValueError("operator must indicate right or left associativity") - thisExpr = Forward().set_name(term_name) + thisExpr: Forward = Forward().set_name(term_name) if rightLeftAssoc is OpAssoc.LEFT: if arity == 1: matchExpr = _FB(lastExpr + opExpr) + Group(lastExpr + opExpr[1, ...]) @@ -945,7 +948,7 @@ def eggs(z): assignment = Group(identifier + "=" + rvalue) stmt << (funcDef | assignment | identifier) - module_body = OneOrMore(stmt) + module_body = stmt[1, ...] parseTree = module_body.parseString(data) parseTree.pprint() @@ -1055,7 +1058,9 @@ def checkUnindent(s, l, t): # build list of built-in expressions, for future reference if a global default value # gets updated -_builtin_exprs = [v for v in vars().values() if isinstance(v, ParserElement)] +_builtin_exprs: List[ParserElement] = [ + v for v in vars().values() if isinstance(v, ParserElement) +] # pre-PEP8 compatible names diff --git a/src/poetry/core/_vendor/pyparsing/results.py b/src/poetry/core/_vendor/pyparsing/results.py index bb444df4e..00c9421d3 100644 --- a/src/poetry/core/_vendor/pyparsing/results.py +++ b/src/poetry/core/_vendor/pyparsing/results.py @@ -287,7 +287,7 @@ def remove_first(tokens): print(numlist.parse_string("0 123 321")) # -> ['123', '321'] label = Word(alphas) - patt = label("LABEL") + OneOrMore(Word(nums)) + patt = label("LABEL") + Word(nums)[1, ...] print(patt.parse_string("AAB 123 321").dump()) # Use pop() in a parse action to remove named result (note that corresponding value is not @@ -394,7 +394,7 @@ def extend(self, itemseq): Example:: - patt = OneOrMore(Word(alphas)) + patt = Word(alphas)[1, ...] # use a parse action to append the reverse of the matched strings, to make a palindrome def make_palindrome(tokens): @@ -487,7 +487,7 @@ def as_list(self) -> list: Example:: - patt = OneOrMore(Word(alphas)) + patt = Word(alphas)[1, ...] result = patt.parse_string("sldkj lsdkj sldkj") # even though the result prints in string-like form, it is actually a pyparsing ParseResults print(type(result), result) # -> ['sldkj', 'lsdkj', 'sldkj'] @@ -554,7 +554,7 @@ def get_name(self): user_data = (Group(house_number_expr)("house_number") | Group(ssn_expr)("ssn") | Group(integer)("age")) - user_info = OneOrMore(user_data) + user_info = user_data[1, ...] result = user_info.parse_string("22 111-22-3333 #221B") for item in result: diff --git a/src/poetry/core/_vendor/pyparsing/testing.py b/src/poetry/core/_vendor/pyparsing/testing.py index 991972f3f..84a0ef170 100644 --- a/src/poetry/core/_vendor/pyparsing/testing.py +++ b/src/poetry/core/_vendor/pyparsing/testing.py @@ -1,7 +1,7 @@ # testing.py from contextlib import contextmanager -from typing import Optional +import typing from .core import ( ParserElement, @@ -237,12 +237,12 @@ def assertRaisesParseException(self, exc_type=ParseException, msg=None): @staticmethod def with_line_numbers( s: str, - start_line: Optional[int] = None, - end_line: Optional[int] = None, + start_line: typing.Optional[int] = None, + end_line: typing.Optional[int] = None, expand_tabs: bool = True, eol_mark: str = "|", - mark_spaces: Optional[str] = None, - mark_control: Optional[str] = None, + mark_spaces: typing.Optional[str] = None, + mark_control: typing.Optional[str] = None, ) -> str: """ Helpful method for debugging a parser - prints a string with line and column numbers. diff --git a/src/poetry/core/_vendor/pyparsing/unicode.py b/src/poetry/core/_vendor/pyparsing/unicode.py index 92261487c..065262039 100644 --- a/src/poetry/core/_vendor/pyparsing/unicode.py +++ b/src/poetry/core/_vendor/pyparsing/unicode.py @@ -120,7 +120,18 @@ class pyparsing_unicode(unicode_set): A namespace class for defining common language unicode_sets. """ - _ranges: UnicodeRangeList = [(32, sys.maxunicode)] + # fmt: off + + # define ranges in language character sets + _ranges: UnicodeRangeList = [ + (0x0020, sys.maxunicode), + ] + + class BasicMultilingualPlane(unicode_set): + "Unicode set for the Basic Multilingual Plane" + _ranges: UnicodeRangeList = [ + (0x0020, 0xFFFF), + ] class Latin1(unicode_set): "Unicode set for Latin-1 Unicode Character Range" @@ -278,11 +289,13 @@ class Hangul(unicode_set): class CJK(Chinese, Japanese, Hangul): "Unicode set for combined Chinese, Japanese, and Korean (CJK) Unicode Character Range" - pass class Thai(unicode_set): "Unicode set for Thai Unicode Character Range" - _ranges: UnicodeRangeList = [(0x0E01, 0x0E3A), (0x0E3F, 0x0E5B)] + _ranges: UnicodeRangeList = [ + (0x0E01, 0x0E3A), + (0x0E3F, 0x0E5B) + ] class Arabic(unicode_set): "Unicode set for Arabic Unicode Character Range" @@ -308,7 +321,12 @@ class Hebrew(unicode_set): class Devanagari(unicode_set): "Unicode set for Devanagari Unicode Character Range" - _ranges: UnicodeRangeList = [(0x0900, 0x097F), (0xA8E0, 0xA8FF)] + _ranges: UnicodeRangeList = [ + (0x0900, 0x097F), + (0xA8E0, 0xA8FF) + ] + + # fmt: on pyparsing_unicode.Japanese._ranges = ( @@ -317,7 +335,9 @@ class Devanagari(unicode_set): + pyparsing_unicode.Japanese.Katakana._ranges ) -# define ranges in language character sets +pyparsing_unicode.BMP = pyparsing_unicode.BasicMultilingualPlane + +# add language identifiers using language Unicode pyparsing_unicode.العربية = pyparsing_unicode.Arabic pyparsing_unicode.中文 = pyparsing_unicode.Chinese pyparsing_unicode.кириллица = pyparsing_unicode.Cyrillic diff --git a/src/poetry/core/_vendor/pyrsistent/_checked_types.py b/src/poetry/core/_vendor/pyrsistent/_checked_types.py index 293d989f1..8ab8c2a8c 100644 --- a/src/poetry/core/_vendor/pyrsistent/_checked_types.py +++ b/src/poetry/core/_vendor/pyrsistent/_checked_types.py @@ -1,7 +1,8 @@ -from ._compat import Iterable -import six +from enum import Enum + +from abc import abstractmethod, ABCMeta +from collections.abc import Iterable -from pyrsistent._compat import Enum, string_types from pyrsistent._pmap import PMap, pmap from pyrsistent._pset import PSet, pset from pyrsistent._pvector import PythonPVector, python_pvector @@ -14,9 +15,11 @@ class CheckedType(object): __slots__ = () @classmethod + @abstractmethod def create(cls, source_data, _factory_fields=None): raise NotImplementedError() + @abstractmethod def serialize(self, format=None): raise NotImplementedError() @@ -48,7 +51,7 @@ def __str__(self): _preserved_iterable_types = ( - Enum, + Enum, ) """Some types are themselves iterable, but we want to use the type itself and not its members for the type specification. This defines a set of such types @@ -69,7 +72,7 @@ def maybe_parse_user_type(t): """ is_type = isinstance(t, type) is_preserved = isinstance(t, type) and issubclass(t, _preserved_iterable_types) - is_string = isinstance(t, string_types) + is_string = isinstance(t, str) is_iterable = isinstance(t, Iterable) if is_preserved: @@ -159,7 +162,7 @@ def store_invariants(dct, bases, destination_name, source_name): dct[destination_name] = tuple(wrap_invariant(inv) for inv in invariants) -class _CheckedTypeMeta(type): +class _CheckedTypeMeta(ABCMeta): def __new__(mcs, name, bases, dct): _store_types(dct, bases, '_checked_types', '__type__') store_invariants(dct, bases, '_checked_invariants', '__invariant__') @@ -268,8 +271,7 @@ def _checked_type_create(cls, source_data, _factory_fields=None, ignore_extra=Fa return cls(source_data) -@six.add_metaclass(_CheckedTypeMeta) -class CheckedPVector(PythonPVector, CheckedType): +class CheckedPVector(PythonPVector, CheckedType, metaclass=_CheckedTypeMeta): """ A CheckedPVector is a PVector which allows specifying type and invariant checks. @@ -355,8 +357,7 @@ def evolver(self): return CheckedPVector.Evolver(self.__class__, self) -@six.add_metaclass(_CheckedTypeMeta) -class CheckedPSet(PSet, CheckedType): +class CheckedPSet(PSet, CheckedType, metaclass=_CheckedTypeMeta): """ A CheckedPSet is a PSet which allows specifying type and invariant checks. @@ -454,8 +455,7 @@ def default_serializer(self, _, key, value): _UNDEFINED_CHECKED_PMAP_SIZE = object() -@six.add_metaclass(_CheckedMapTypeMeta) -class CheckedPMap(PMap, CheckedType): +class CheckedPMap(PMap, CheckedType, metaclass=_CheckedMapTypeMeta): """ A CheckedPMap is a PMap which allows specifying type and invariant checks. diff --git a/src/poetry/core/_vendor/pyrsistent/_compat.py b/src/poetry/core/_vendor/pyrsistent/_compat.py deleted file mode 100644 index e728586af..000000000 --- a/src/poetry/core/_vendor/pyrsistent/_compat.py +++ /dev/null @@ -1,31 +0,0 @@ -from six import string_types - - -# enum compat -try: - from enum import Enum -except: - class Enum(object): pass - # no objects will be instances of this class - -# collections compat -try: - from collections.abc import ( - Container, - Hashable, - Iterable, - Mapping, - Sequence, - Set, - Sized, - ) -except ImportError: - from collections import ( - Container, - Hashable, - Iterable, - Mapping, - Sequence, - Set, - Sized, - ) diff --git a/src/poetry/core/_vendor/pyrsistent/_field_common.py b/src/poetry/core/_vendor/pyrsistent/_field_common.py index ca1cccd43..508dd2f79 100644 --- a/src/poetry/core/_vendor/pyrsistent/_field_common.py +++ b/src/poetry/core/_vendor/pyrsistent/_field_common.py @@ -1,6 +1,3 @@ -import six -import sys - from pyrsistent._checked_types import ( CheckedPMap, CheckedPSet, @@ -16,8 +13,6 @@ from pyrsistent._checked_types import wrap_invariant import inspect -PY2 = sys.version_info[0] < 3 - def set_fields(dct, bases, name): dct[name] = dict(sum([list(b.__dict__.get(name, {}).items()) for b in bases], [])) @@ -66,10 +61,7 @@ def is_field_ignore_extra_complaint(type_cls, field, ignore_extra): if not is_type_cls(type_cls, field.type): return False - if PY2: - return 'ignore_extra' in inspect.getargspec(field.factory).args - else: - return 'ignore_extra' in inspect.signature(field.factory).parameters + return 'ignore_extra' in inspect.signature(field.factory).parameters @@ -139,7 +131,7 @@ def field(type=PFIELD_NO_TYPE, invariant=PFIELD_NO_INVARIANT, initial=PFIELD_NO_ def _check_field_parameters(field): for t in field.type: - if not isinstance(t, type) and not isinstance(t, six.string_types): + if not isinstance(t, type) and not isinstance(t, str): raise TypeError('Type parameter expected, not {0}'.format(type(t))) if field.initial is not PFIELD_NO_INITIAL and \ @@ -192,7 +184,7 @@ def _types_to_names(types): """Convert a tuple of types to a human-readable string.""" return "".join(get_type(typ).__name__.capitalize() for typ in types) -def _make_seq_field_type(checked_class, item_type): +def _make_seq_field_type(checked_class, item_type, item_invariant): """Create a subclass of the given checked class with the given item type.""" type_ = _seq_field_types.get((checked_class, item_type)) if type_ is not None: @@ -200,6 +192,7 @@ def _make_seq_field_type(checked_class, item_type): class TheType(checked_class): __type__ = item_type + __invariant__ = item_invariant def __reduce__(self): return (_restore_seq_field_pickle, @@ -210,7 +203,9 @@ def __reduce__(self): _seq_field_types[checked_class, item_type] = TheType return TheType -def _sequence_field(checked_class, item_type, optional, initial): +def _sequence_field(checked_class, item_type, optional, initial, + invariant=PFIELD_NO_INVARIANT, + item_invariant=PFIELD_NO_INVARIANT): """ Create checked field for either ``PSet`` or ``PVector``. @@ -222,7 +217,7 @@ def _sequence_field(checked_class, item_type, optional, initial): :return: A ``field`` containing a checked class. """ - TheType = _make_seq_field_type(checked_class, item_type) + TheType = _make_seq_field_type(checked_class, item_type, item_invariant) if optional: def factory(argument, _factory_fields=None, ignore_extra=False): @@ -235,10 +230,13 @@ def factory(argument, _factory_fields=None, ignore_extra=False): return field(type=optional_type(TheType) if optional else TheType, factory=factory, mandatory=True, + invariant=invariant, initial=factory(initial)) -def pset_field(item_type, optional=False, initial=()): +def pset_field(item_type, optional=False, initial=(), + invariant=PFIELD_NO_INVARIANT, + item_invariant=PFIELD_NO_INVARIANT): """ Create checked ``PSet`` field. @@ -250,11 +248,14 @@ def pset_field(item_type, optional=False, initial=()): :return: A ``field`` containing a ``CheckedPSet`` of the given type. """ - return _sequence_field(CheckedPSet, item_type, optional, - initial) + return _sequence_field(CheckedPSet, item_type, optional, initial, + invariant=invariant, + item_invariant=item_invariant) -def pvector_field(item_type, optional=False, initial=()): +def pvector_field(item_type, optional=False, initial=(), + invariant=PFIELD_NO_INVARIANT, + item_invariant=PFIELD_NO_INVARIANT): """ Create checked ``PVector`` field. @@ -266,8 +267,9 @@ def pvector_field(item_type, optional=False, initial=()): :return: A ``field`` containing a ``CheckedPVector`` of the given type. """ - return _sequence_field(CheckedPVector, item_type, optional, - initial) + return _sequence_field(CheckedPVector, item_type, optional, initial, + invariant=invariant, + item_invariant=item_invariant) _valid = lambda item: (True, "") diff --git a/src/poetry/core/_vendor/pyrsistent/_helpers.py b/src/poetry/core/_vendor/pyrsistent/_helpers.py index c9c58feac..1320e6576 100644 --- a/src/poetry/core/_vendor/pyrsistent/_helpers.py +++ b/src/poetry/core/_vendor/pyrsistent/_helpers.py @@ -1,11 +1,9 @@ from functools import wraps -import six from pyrsistent._pmap import PMap, pmap from pyrsistent._pset import PSet, pset from pyrsistent._pvector import PVector, pvector - -def freeze(o): +def freeze(o, strict=True): """ Recursively convert simple Python containers into pyrsistent versions of those containers. @@ -15,6 +13,11 @@ def freeze(o): - set is converted to pset, but not recursively - tuple is converted to tuple, recursively. + If strict == True (default): + + - freeze is called on elements of pvectors + - freeze is called on values of pmaps + Sets and dict keys are not recursively frozen because they do not contain mutable data by convention. The main exception to this rule is that dict keys and set elements are often instances of mutable objects that @@ -28,18 +31,21 @@ def freeze(o): (1, pvector([])) """ typ = type(o) - if typ is dict: - return pmap(dict((k, freeze(v)) for k, v in six.iteritems(o))) - if typ is list: - return pvector(map(freeze, o)) + if typ is dict or (strict and isinstance(o, PMap)): + return pmap({k: freeze(v, strict) for k, v in o.items()}) + if typ is list or (strict and isinstance(o, PVector)): + curried_freeze = lambda x: freeze(x, strict) + return pvector(map(curried_freeze, o)) if typ is tuple: - return tuple(map(freeze, o)) + curried_freeze = lambda x: freeze(x, strict) + return tuple(map(curried_freeze, o)) if typ is set: + # impossible to have anything that needs freezing inside a set or pset return pset(o) return o -def thaw(o): +def thaw(o, strict=True): """ Recursively convert pyrsistent containers into simple Python containers. @@ -48,6 +54,11 @@ def thaw(o): - pset is converted to set, but not recursively - tuple is converted to tuple, recursively. + If strict == True (the default): + + - thaw is called on elements of lists + - thaw is called on values in dicts + >>> from pyrsistent import s, m, v >>> thaw(s(1, 2)) {1, 2} @@ -56,14 +67,18 @@ def thaw(o): >>> thaw((1, v())) (1, []) """ - if isinstance(o, PVector): - return list(map(thaw, o)) - if isinstance(o, PMap): - return dict((k, thaw(v)) for k, v in o.iteritems()) + typ = type(o) + if isinstance(o, PVector) or (strict and typ is list): + curried_thaw = lambda x: thaw(x, strict) + return list(map(curried_thaw, o)) + if isinstance(o, PMap) or (strict and typ is dict): + return {k: thaw(v, strict) for k, v in o.items()} + if typ is tuple: + curried_thaw = lambda x: thaw(x, strict) + return tuple(map(curried_thaw, o)) if isinstance(o, PSet): + # impossible to thaw inside psets or sets return set(o) - if type(o) is tuple: - return tuple(map(thaw, o)) return o diff --git a/src/poetry/core/_vendor/pyrsistent/_immutable.py b/src/poetry/core/_vendor/pyrsistent/_immutable.py index a89bd7552..7c7594533 100644 --- a/src/poetry/core/_vendor/pyrsistent/_immutable.py +++ b/src/poetry/core/_vendor/pyrsistent/_immutable.py @@ -1,7 +1,5 @@ import sys -import six - def immutable(members='', name='Immutable', verbose=False): """ @@ -48,7 +46,7 @@ def immutable(members='', name='Immutable', verbose=False): AttributeError: Cannot set frozen members id_ """ - if isinstance(members, six.string_types): + if isinstance(members, str): members = members.replace(',', ' ').split() def frozen_member_test(): @@ -98,8 +96,8 @@ def set(self, **kwargs): from collections import namedtuple namespace = dict(namedtuple=namedtuple, __name__='pyrsistent_immutable') try: - six.exec_(template, namespace) + exec(template, namespace) except SyntaxError as e: - raise SyntaxError(e.message + ':\n' + template) + raise SyntaxError(str(e) + ':\n' + template) from e - return namespace[name] \ No newline at end of file + return namespace[name] diff --git a/src/poetry/core/_vendor/pyrsistent/_pbag.py b/src/poetry/core/_vendor/pyrsistent/_pbag.py index 9905e9a6e..9cf5840b7 100644 --- a/src/poetry/core/_vendor/pyrsistent/_pbag.py +++ b/src/poetry/core/_vendor/pyrsistent/_pbag.py @@ -1,4 +1,4 @@ -from ._compat import Container, Iterable, Sized, Hashable +from collections.abc import Container, Iterable, Sized, Hashable from functools import reduce from pyrsistent._pmap import pmap @@ -154,7 +154,7 @@ def __lt__(self, other): # Multiset-style operations similar to collections.Counter def __add__(self, other): - """ + """ Combine elements from two PBags. >>> pbag([1, 2, 2]) + pbag([2, 3, 3]) @@ -168,7 +168,7 @@ def __add__(self, other): return PBag(result.persistent()) def __sub__(self, other): - """ + """ Remove elements from one PBag that are present in another. >>> pbag([1, 2, 2, 2, 3]) - pbag([2, 3, 3, 4]) @@ -184,9 +184,9 @@ def __sub__(self, other): elif elem in self: result.remove(elem) return PBag(result.persistent()) - + def __or__(self, other): - """ + """ Union: Keep elements that are present in either of two PBags. >>> pbag([1, 2, 2, 2]) | pbag([2, 3, 3]) @@ -200,11 +200,11 @@ def __or__(self, other): newcount = max(count, other_count) result[elem] = newcount return PBag(result.persistent()) - + def __and__(self, other): """ Intersection: Only keep elements that are present in both PBags. - + >>> pbag([1, 2, 2, 2]) & pbag([2, 3, 3]) pbag([2]) """ @@ -216,7 +216,7 @@ def __and__(self, other): if newcount > 0: result[elem] = newcount return PBag(result.persistent()) - + def __hash__(self): """ Hash based on value of elements. diff --git a/src/poetry/core/_vendor/pyrsistent/_pclass.py b/src/poetry/core/_vendor/pyrsistent/_pclass.py index a437f7164..fd31a95d6 100644 --- a/src/poetry/core/_vendor/pyrsistent/_pclass.py +++ b/src/poetry/core/_vendor/pyrsistent/_pclass.py @@ -1,4 +1,3 @@ -import six from pyrsistent._checked_types import (InvariantException, CheckedType, _restore_pickle, store_invariants) from pyrsistent._field_common import ( set_fields, check_type, is_field_ignore_extra_complaint, PFIELD_NO_INITIAL, serialize, check_global_invariants @@ -35,8 +34,7 @@ def _check_and_set_attr(cls, field, name, value, result, invariant_errors): setattr(result, name, value) -@six.add_metaclass(PClassMeta) -class PClass(CheckedType): +class PClass(CheckedType, metaclass=PClassMeta): """ A PClass is a python class with a fixed set of specified fields. PClasses are declared as python classes inheriting from PClass. It is defined the same way that PRecords are and behaves like a PRecord in all aspects except that it diff --git a/src/poetry/core/_vendor/pyrsistent/_pdeque.py b/src/poetry/core/_vendor/pyrsistent/_pdeque.py index 5147b3fa6..bd11bfa03 100644 --- a/src/poetry/core/_vendor/pyrsistent/_pdeque.py +++ b/src/poetry/core/_vendor/pyrsistent/_pdeque.py @@ -1,4 +1,4 @@ -from ._compat import Sequence, Hashable +from collections.abc import Sequence, Hashable from itertools import islice, chain from numbers import Integral from pyrsistent._plist import plist @@ -276,8 +276,8 @@ def remove(self, elem): # This is severely inefficient with a double reverse, should perhaps implement a remove_last()? return PDeque(self._left_list, self._right_list.reverse().remove(elem).reverse(), self._length - 1) - except ValueError: - raise ValueError('{0} not found in PDeque'.format(elem)) + except ValueError as e: + raise ValueError('{0} not found in PDeque'.format(elem)) from e def reverse(self): """ diff --git a/src/poetry/core/_vendor/pyrsistent/_plist.py b/src/poetry/core/_vendor/pyrsistent/_plist.py index 8b4267f5e..bea7f5ecf 100644 --- a/src/poetry/core/_vendor/pyrsistent/_plist.py +++ b/src/poetry/core/_vendor/pyrsistent/_plist.py @@ -1,4 +1,4 @@ -from ._compat import Sequence, Hashable +from collections.abc import Sequence, Hashable from numbers import Integral from functools import reduce @@ -143,7 +143,7 @@ def __lt__(self, other): def __eq__(self, other): """ Traverses the lists, checking equality of elements. - + This is an O(n) operation, but preserves the standard semantics of list equality. """ if not isinstance(other, _PListBase): @@ -179,8 +179,8 @@ def __getitem__(self, index): try: return self._drop(index).first - except AttributeError: - raise IndexError("PList index out of range") + except AttributeError as e: + raise IndexError("PList index out of range") from e def _drop(self, count): if count < 0: diff --git a/src/poetry/core/_vendor/pyrsistent/_pmap.py b/src/poetry/core/_vendor/pyrsistent/_pmap.py index e8a0ec53f..056d478ef 100644 --- a/src/poetry/core/_vendor/pyrsistent/_pmap.py +++ b/src/poetry/core/_vendor/pyrsistent/_pmap.py @@ -1,6 +1,5 @@ -from ._compat import Mapping, Hashable +from collections.abc import Mapping, Hashable from itertools import chain -import six from pyrsistent._pvector import pvector from pyrsistent._transformations import transform @@ -32,12 +31,12 @@ class PMap(object): >>> m1 = m(a=1, b=3) >>> m2 = m1.set('c', 3) >>> m3 = m2.remove('a') - >>> m1 - pmap({'b': 3, 'a': 1}) - >>> m2 - pmap({'c': 3, 'b': 3, 'a': 1}) - >>> m3 - pmap({'c': 3, 'b': 3}) + >>> m1 == {'a': 1, 'b': 3} + True + >>> m2 == {'a': 1, 'b': 3, 'c': 3} + True + >>> m3 == {'b': 3, 'c': 3} + True >>> m3['c'] 3 >>> m3.c @@ -93,10 +92,10 @@ def __iter__(self): def __getattr__(self, key): try: return self[key] - except KeyError: + except KeyError as e: raise AttributeError( "{0} has no attribute '{1}'".format(type(self).__name__, key) - ) + ) from e def iterkeys(self): for k, _ in self.iteritems(): @@ -146,7 +145,7 @@ def __eq__(self, other): return dict(self.iteritems()) == dict(other.iteritems()) elif isinstance(other, dict): return dict(self.iteritems()) == other - return dict(self.iteritems()) == dict(six.iteritems(other)) + return dict(self.iteritems()) == dict(other.items()) __ne__ = Mapping.__ne__ @@ -172,12 +171,12 @@ def set(self, key, val): >>> m1 = m(a=1, b=2) >>> m2 = m1.set('a', 3) >>> m3 = m1.set('c' ,4) - >>> m1 - pmap({'b': 2, 'a': 1}) - >>> m2 - pmap({'b': 2, 'a': 3}) - >>> m3 - pmap({'c': 4, 'b': 2, 'a': 1}) + >>> m1 == {'a': 1, 'b': 2} + True + >>> m2 == {'a': 3, 'b': 2} + True + >>> m3 == {'a': 1, 'b': 2, 'c': 4} + True """ return self.evolver().set(key, val).persistent() @@ -214,8 +213,8 @@ def update(self, *maps): maps the rightmost (last) value is inserted. >>> m1 = m(a=1, b=2) - >>> m1.update(m(a=2, c=3), {'a': 17, 'd': 35}) - pmap({'c': 3, 'b': 2, 'a': 17, 'd': 35}) + >>> m1.update(m(a=2, c=3), {'a': 17, 'd': 35}) == {'a': 17, 'b': 2, 'c': 3, 'd': 35} + True """ return self.update_with(lambda l, r: r, *maps) @@ -226,8 +225,8 @@ def update_with(self, update_fn, *maps): >>> from operator import add >>> m1 = m(a=1, b=2) - >>> m1.update_with(add, m(a=2)) - pmap({'b': 2, 'a': 3}) + >>> m1.update_with(add, m(a=2)) == {'a': 3, 'b': 2} + True The reverse behaviour of the regular merge. Keep the leftmost element instead of the rightmost. @@ -245,6 +244,8 @@ def update_with(self, update_fn, *maps): def __add__(self, other): return self.update(other) + __or__ = __add__ + def __reduce__(self): # Pickling support return pmap, (dict(self),) @@ -380,15 +381,15 @@ def evolver(self): The underlying pmap remains the same: - >>> m1 - pmap({'b': 2, 'a': 1}) + >>> m1 == {'a': 1, 'b': 2} + True The changes are kept in the evolver. An updated pmap can be created using the persistent() function on the evolver. >>> m2 = e.persistent() - >>> m2 - pmap({'c': 3, 'b': 2}) + >>> m2 == {'b': 2, 'c': 3} + True The new pmap will share data with the original pmap in the same way that would have been done if only using operations on the pmap. @@ -418,7 +419,7 @@ def _turbo_mapping(initial, pre_size): # key collisions initial = dict(initial) - for k, v in six.iteritems(initial): + for k, v in initial.items(): h = hash(k) index = h % size bucket = buckets[index] @@ -441,10 +442,10 @@ def pmap(initial={}, pre_size=0): may have a positive performance impact in the cases where you know beforehand that a large number of elements will be inserted into the map eventually since it will reduce the number of reallocations required. - >>> pmap({'a': 13, 'b': 14}) - pmap({'b': 14, 'a': 13}) + >>> pmap({'a': 13, 'b': 14}) == {'a': 13, 'b': 14} + True """ - if not initial: + if not initial and pre_size == 0: return _EMPTY_PMAP return _turbo_mapping(initial, pre_size) @@ -452,9 +453,9 @@ def pmap(initial={}, pre_size=0): def m(**kwargs): """ - Creates a new persitent map. Inserts all key value arguments into the newly created map. + Creates a new persistent map. Inserts all key value arguments into the newly created map. - >>> m(a=13, b=14) - pmap({'b': 14, 'a': 13}) + >>> m(a=13, b=14) == {'a': 13, 'b': 14} + True """ return pmap(kwargs) diff --git a/src/poetry/core/_vendor/pyrsistent/_precord.py b/src/poetry/core/_vendor/pyrsistent/_precord.py index ec8d32c3d..1ee8198a1 100644 --- a/src/poetry/core/_vendor/pyrsistent/_precord.py +++ b/src/poetry/core/_vendor/pyrsistent/_precord.py @@ -1,4 +1,3 @@ -import six from pyrsistent._checked_types import CheckedType, _restore_pickle, InvariantException, store_invariants from pyrsistent._field_common import ( set_fields, check_type, is_field_ignore_extra_complaint, PFIELD_NO_INITIAL, serialize, check_global_invariants @@ -23,8 +22,7 @@ def __new__(mcs, name, bases, dct): return super(_PRecordMeta, mcs).__new__(mcs, name, bases, dct) -@six.add_metaclass(_PRecordMeta) -class PRecord(PMap, CheckedType): +class PRecord(PMap, CheckedType, metaclass=_PRecordMeta): """ A PRecord is a PMap with a fixed set of specified fields. Records are declared as python classes inheriting from PRecord. Because it is a PMap it has full support for all Mapping methods such as iteration and element @@ -48,7 +46,7 @@ def __new__(cls, **kwargs): for k, v in cls._precord_initial_values.items()) initial_values.update(kwargs) - e = _PRecordEvolver(cls, pmap(), _factory_fields=factory_fields, _ignore_extra=ignore_extra) + e = _PRecordEvolver(cls, pmap(pre_size=len(cls._precord_fields)), _factory_fields=factory_fields, _ignore_extra=ignore_extra) for k, v in initial_values.items(): e[k] = v diff --git a/src/poetry/core/_vendor/pyrsistent/_pset.py b/src/poetry/core/_vendor/pyrsistent/_pset.py index a972ec533..4fae8278f 100644 --- a/src/poetry/core/_vendor/pyrsistent/_pset.py +++ b/src/poetry/core/_vendor/pyrsistent/_pset.py @@ -1,9 +1,7 @@ -from ._compat import Set, Hashable +from collections.abc import Set, Hashable import sys from pyrsistent._pmap import pmap -PY2 = sys.version_info[0] < 3 - class PSet(object): """ @@ -44,7 +42,7 @@ def __len__(self): return len(self._map) def __repr__(self): - if PY2 or not self: + if not self: return 'p' + str(set(self)) return 'pset([{0}])'.format(str(set(self))[1:-1]) @@ -98,7 +96,7 @@ def remove(self, element): if element in self._map: return self.evolver().remove(element).persistent() - raise KeyError("Element '%s' not present in PSet" % element) + raise KeyError("Element '%s' not present in PSet" % repr(element)) def discard(self, element): """ diff --git a/src/poetry/core/_vendor/pyrsistent/_pvector.py b/src/poetry/core/_vendor/pyrsistent/_pvector.py index 82232782b..2aff0e8b4 100644 --- a/src/poetry/core/_vendor/pyrsistent/_pvector.py +++ b/src/poetry/core/_vendor/pyrsistent/_pvector.py @@ -1,8 +1,7 @@ from abc import abstractmethod, ABCMeta -from ._compat import Sequence, Hashable +from collections.abc import Sequence, Hashable from numbers import Integral import operator -import six from pyrsistent._transformations import transform @@ -411,8 +410,7 @@ def remove(self, value): l.remove(value) return _EMPTY_PVECTOR.extend(l) -@six.add_metaclass(ABCMeta) -class PVector(object): +class PVector(metaclass=ABCMeta): """ Persistent vector implementation. Meant as a replacement for the cases where you would normally use a Python list. diff --git a/src/poetry/core/_vendor/pyrsistent/_toolz.py b/src/poetry/core/_vendor/pyrsistent/_toolz.py index 6643ee860..a7faed165 100644 --- a/src/poetry/core/_vendor/pyrsistent/_toolz.py +++ b/src/poetry/core/_vendor/pyrsistent/_toolz.py @@ -39,7 +39,7 @@ DAMAGE. """ import operator -from six.moves import reduce +from functools import reduce def get_in(keys, coll, default=None, no_default=False): @@ -80,4 +80,4 @@ def get_in(keys, coll, default=None, no_default=False): except (KeyError, IndexError, TypeError): if no_default: raise - return default \ No newline at end of file + return default diff --git a/src/poetry/core/_vendor/pyrsistent/_transformations.py b/src/poetry/core/_vendor/pyrsistent/_transformations.py index 612098969..7544843ac 100644 --- a/src/poetry/core/_vendor/pyrsistent/_transformations.py +++ b/src/poetry/core/_vendor/pyrsistent/_transformations.py @@ -1,13 +1,9 @@ import re -import six try: from inspect import Parameter, signature except ImportError: signature = None - try: - from inspect import getfullargspec as getargspec - except ImportError: - from inspect import getargspec + from inspect import getfullargspec _EMPTY_SENTINEL = object() @@ -35,7 +31,7 @@ def discard(evolver, key): def rex(expr): """ Regular expression matcher to use together with transform functions """ r = re.compile(expr) - return lambda key: isinstance(key, six.string_types) and r.match(key) + return lambda key: isinstance(key, str) and r.match(key) def ny(_): @@ -107,7 +103,7 @@ def _get_keys_and_values(structure, key_spec): if signature is None: def _get_arity(f): - argspec = getargspec(f) + argspec = getfullargspec(f) return len(argspec.args) - len(argspec.defaults or ()) else: def _get_arity(f): diff --git a/src/poetry/core/_vendor/six.LICENSE b/src/poetry/core/_vendor/six.LICENSE deleted file mode 100644 index de6633112..000000000 --- a/src/poetry/core/_vendor/six.LICENSE +++ /dev/null @@ -1,18 +0,0 @@ -Copyright (c) 2010-2020 Benjamin Peterson - -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/src/poetry/core/_vendor/six.py b/src/poetry/core/_vendor/six.py deleted file mode 100644 index 4e15675d8..000000000 --- a/src/poetry/core/_vendor/six.py +++ /dev/null @@ -1,998 +0,0 @@ -# Copyright (c) 2010-2020 Benjamin Peterson -# -# 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. - -"""Utilities for writing code that runs on Python 2 and 3""" - -from __future__ import absolute_import - -import functools -import itertools -import operator -import sys -import types - -__author__ = "Benjamin Peterson " -__version__ = "1.16.0" - - -# Useful for very coarse version differentiation. -PY2 = sys.version_info[0] == 2 -PY3 = sys.version_info[0] == 3 -PY34 = sys.version_info[0:2] >= (3, 4) - -if PY3: - string_types = str, - integer_types = int, - class_types = type, - text_type = str - binary_type = bytes - - MAXSIZE = sys.maxsize -else: - string_types = basestring, - integer_types = (int, long) - class_types = (type, types.ClassType) - text_type = unicode - binary_type = str - - if sys.platform.startswith("java"): - # Jython always uses 32 bits. - MAXSIZE = int((1 << 31) - 1) - else: - # It's possible to have sizeof(long) != sizeof(Py_ssize_t). - class X(object): - - def __len__(self): - return 1 << 31 - try: - len(X()) - except OverflowError: - # 32-bit - MAXSIZE = int((1 << 31) - 1) - else: - # 64-bit - MAXSIZE = int((1 << 63) - 1) - del X - -if PY34: - from importlib.util import spec_from_loader -else: - spec_from_loader = None - - -def _add_doc(func, doc): - """Add documentation to a function.""" - func.__doc__ = doc - - -def _import_module(name): - """Import module, returning the module after the last dot.""" - __import__(name) - return sys.modules[name] - - -class _LazyDescr(object): - - def __init__(self, name): - self.name = name - - def __get__(self, obj, tp): - result = self._resolve() - setattr(obj, self.name, result) # Invokes __set__. - try: - # This is a bit ugly, but it avoids running this again by - # removing this descriptor. - delattr(obj.__class__, self.name) - except AttributeError: - pass - return result - - -class MovedModule(_LazyDescr): - - def __init__(self, name, old, new=None): - super(MovedModule, self).__init__(name) - if PY3: - if new is None: - new = name - self.mod = new - else: - self.mod = old - - def _resolve(self): - return _import_module(self.mod) - - def __getattr__(self, attr): - _module = self._resolve() - value = getattr(_module, attr) - setattr(self, attr, value) - return value - - -class _LazyModule(types.ModuleType): - - def __init__(self, name): - super(_LazyModule, self).__init__(name) - self.__doc__ = self.__class__.__doc__ - - def __dir__(self): - attrs = ["__doc__", "__name__"] - attrs += [attr.name for attr in self._moved_attributes] - return attrs - - # Subclasses should override this - _moved_attributes = [] - - -class MovedAttribute(_LazyDescr): - - def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None): - super(MovedAttribute, self).__init__(name) - if PY3: - if new_mod is None: - new_mod = name - self.mod = new_mod - if new_attr is None: - if old_attr is None: - new_attr = name - else: - new_attr = old_attr - self.attr = new_attr - else: - self.mod = old_mod - if old_attr is None: - old_attr = name - self.attr = old_attr - - def _resolve(self): - module = _import_module(self.mod) - return getattr(module, self.attr) - - -class _SixMetaPathImporter(object): - - """ - A meta path importer to import six.moves and its submodules. - - This class implements a PEP302 finder and loader. It should be compatible - with Python 2.5 and all existing versions of Python3 - """ - - def __init__(self, six_module_name): - self.name = six_module_name - self.known_modules = {} - - def _add_module(self, mod, *fullnames): - for fullname in fullnames: - self.known_modules[self.name + "." + fullname] = mod - - def _get_module(self, fullname): - return self.known_modules[self.name + "." + fullname] - - def find_module(self, fullname, path=None): - if fullname in self.known_modules: - return self - return None - - def find_spec(self, fullname, path, target=None): - if fullname in self.known_modules: - return spec_from_loader(fullname, self) - return None - - def __get_module(self, fullname): - try: - return self.known_modules[fullname] - except KeyError: - raise ImportError("This loader does not know module " + fullname) - - def load_module(self, fullname): - try: - # in case of a reload - return sys.modules[fullname] - except KeyError: - pass - mod = self.__get_module(fullname) - if isinstance(mod, MovedModule): - mod = mod._resolve() - else: - mod.__loader__ = self - sys.modules[fullname] = mod - return mod - - def is_package(self, fullname): - """ - Return true, if the named module is a package. - - We need this method to get correct spec objects with - Python 3.4 (see PEP451) - """ - return hasattr(self.__get_module(fullname), "__path__") - - def get_code(self, fullname): - """Return None - - Required, if is_package is implemented""" - self.__get_module(fullname) # eventually raises ImportError - return None - get_source = get_code # same as get_code - - def create_module(self, spec): - return self.load_module(spec.name) - - def exec_module(self, module): - pass - -_importer = _SixMetaPathImporter(__name__) - - -class _MovedItems(_LazyModule): - - """Lazy loading of moved objects""" - __path__ = [] # mark as package - - -_moved_attributes = [ - MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"), - MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"), - MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"), - MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"), - MovedAttribute("intern", "__builtin__", "sys"), - MovedAttribute("map", "itertools", "builtins", "imap", "map"), - MovedAttribute("getcwd", "os", "os", "getcwdu", "getcwd"), - MovedAttribute("getcwdb", "os", "os", "getcwd", "getcwdb"), - MovedAttribute("getoutput", "commands", "subprocess"), - MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"), - MovedAttribute("reload_module", "__builtin__", "importlib" if PY34 else "imp", "reload"), - MovedAttribute("reduce", "__builtin__", "functools"), - MovedAttribute("shlex_quote", "pipes", "shlex", "quote"), - MovedAttribute("StringIO", "StringIO", "io"), - MovedAttribute("UserDict", "UserDict", "collections"), - MovedAttribute("UserList", "UserList", "collections"), - MovedAttribute("UserString", "UserString", "collections"), - MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"), - MovedAttribute("zip", "itertools", "builtins", "izip", "zip"), - MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"), - MovedModule("builtins", "__builtin__"), - MovedModule("configparser", "ConfigParser"), - MovedModule("collections_abc", "collections", "collections.abc" if sys.version_info >= (3, 3) else "collections"), - MovedModule("copyreg", "copy_reg"), - MovedModule("dbm_gnu", "gdbm", "dbm.gnu"), - MovedModule("dbm_ndbm", "dbm", "dbm.ndbm"), - MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread" if sys.version_info < (3, 9) else "_thread"), - MovedModule("http_cookiejar", "cookielib", "http.cookiejar"), - MovedModule("http_cookies", "Cookie", "http.cookies"), - MovedModule("html_entities", "htmlentitydefs", "html.entities"), - MovedModule("html_parser", "HTMLParser", "html.parser"), - MovedModule("http_client", "httplib", "http.client"), - MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"), - MovedModule("email_mime_image", "email.MIMEImage", "email.mime.image"), - MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"), - MovedModule("email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart"), - MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"), - MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"), - MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"), - MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"), - MovedModule("cPickle", "cPickle", "pickle"), - MovedModule("queue", "Queue"), - MovedModule("reprlib", "repr"), - MovedModule("socketserver", "SocketServer"), - MovedModule("_thread", "thread", "_thread"), - MovedModule("tkinter", "Tkinter"), - MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"), - MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"), - MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"), - MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"), - MovedModule("tkinter_tix", "Tix", "tkinter.tix"), - MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"), - MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"), - MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"), - MovedModule("tkinter_colorchooser", "tkColorChooser", - "tkinter.colorchooser"), - MovedModule("tkinter_commondialog", "tkCommonDialog", - "tkinter.commondialog"), - MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"), - MovedModule("tkinter_font", "tkFont", "tkinter.font"), - MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"), - MovedModule("tkinter_tksimpledialog", "tkSimpleDialog", - "tkinter.simpledialog"), - MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"), - MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"), - MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"), - MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"), - MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"), - MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"), -] -# Add windows specific modules. -if sys.platform == "win32": - _moved_attributes += [ - MovedModule("winreg", "_winreg"), - ] - -for attr in _moved_attributes: - setattr(_MovedItems, attr.name, attr) - if isinstance(attr, MovedModule): - _importer._add_module(attr, "moves." + attr.name) -del attr - -_MovedItems._moved_attributes = _moved_attributes - -moves = _MovedItems(__name__ + ".moves") -_importer._add_module(moves, "moves") - - -class Module_six_moves_urllib_parse(_LazyModule): - - """Lazy loading of moved objects in six.moves.urllib_parse""" - - -_urllib_parse_moved_attributes = [ - MovedAttribute("ParseResult", "urlparse", "urllib.parse"), - MovedAttribute("SplitResult", "urlparse", "urllib.parse"), - MovedAttribute("parse_qs", "urlparse", "urllib.parse"), - MovedAttribute("parse_qsl", "urlparse", "urllib.parse"), - MovedAttribute("urldefrag", "urlparse", "urllib.parse"), - MovedAttribute("urljoin", "urlparse", "urllib.parse"), - MovedAttribute("urlparse", "urlparse", "urllib.parse"), - MovedAttribute("urlsplit", "urlparse", "urllib.parse"), - MovedAttribute("urlunparse", "urlparse", "urllib.parse"), - MovedAttribute("urlunsplit", "urlparse", "urllib.parse"), - MovedAttribute("quote", "urllib", "urllib.parse"), - MovedAttribute("quote_plus", "urllib", "urllib.parse"), - MovedAttribute("unquote", "urllib", "urllib.parse"), - MovedAttribute("unquote_plus", "urllib", "urllib.parse"), - MovedAttribute("unquote_to_bytes", "urllib", "urllib.parse", "unquote", "unquote_to_bytes"), - MovedAttribute("urlencode", "urllib", "urllib.parse"), - MovedAttribute("splitquery", "urllib", "urllib.parse"), - MovedAttribute("splittag", "urllib", "urllib.parse"), - MovedAttribute("splituser", "urllib", "urllib.parse"), - MovedAttribute("splitvalue", "urllib", "urllib.parse"), - MovedAttribute("uses_fragment", "urlparse", "urllib.parse"), - MovedAttribute("uses_netloc", "urlparse", "urllib.parse"), - MovedAttribute("uses_params", "urlparse", "urllib.parse"), - MovedAttribute("uses_query", "urlparse", "urllib.parse"), - MovedAttribute("uses_relative", "urlparse", "urllib.parse"), -] -for attr in _urllib_parse_moved_attributes: - setattr(Module_six_moves_urllib_parse, attr.name, attr) -del attr - -Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes - -_importer._add_module(Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"), - "moves.urllib_parse", "moves.urllib.parse") - - -class Module_six_moves_urllib_error(_LazyModule): - - """Lazy loading of moved objects in six.moves.urllib_error""" - - -_urllib_error_moved_attributes = [ - MovedAttribute("URLError", "urllib2", "urllib.error"), - MovedAttribute("HTTPError", "urllib2", "urllib.error"), - MovedAttribute("ContentTooShortError", "urllib", "urllib.error"), -] -for attr in _urllib_error_moved_attributes: - setattr(Module_six_moves_urllib_error, attr.name, attr) -del attr - -Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes - -_importer._add_module(Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"), - "moves.urllib_error", "moves.urllib.error") - - -class Module_six_moves_urllib_request(_LazyModule): - - """Lazy loading of moved objects in six.moves.urllib_request""" - - -_urllib_request_moved_attributes = [ - MovedAttribute("urlopen", "urllib2", "urllib.request"), - MovedAttribute("install_opener", "urllib2", "urllib.request"), - MovedAttribute("build_opener", "urllib2", "urllib.request"), - MovedAttribute("pathname2url", "urllib", "urllib.request"), - MovedAttribute("url2pathname", "urllib", "urllib.request"), - MovedAttribute("getproxies", "urllib", "urllib.request"), - MovedAttribute("Request", "urllib2", "urllib.request"), - MovedAttribute("OpenerDirector", "urllib2", "urllib.request"), - MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"), - MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"), - MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"), - MovedAttribute("ProxyHandler", "urllib2", "urllib.request"), - MovedAttribute("BaseHandler", "urllib2", "urllib.request"), - MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"), - MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"), - MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"), - MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"), - MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"), - MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"), - MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"), - MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"), - MovedAttribute("HTTPHandler", "urllib2", "urllib.request"), - MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"), - MovedAttribute("FileHandler", "urllib2", "urllib.request"), - MovedAttribute("FTPHandler", "urllib2", "urllib.request"), - MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"), - MovedAttribute("UnknownHandler", "urllib2", "urllib.request"), - MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"), - MovedAttribute("urlretrieve", "urllib", "urllib.request"), - MovedAttribute("urlcleanup", "urllib", "urllib.request"), - MovedAttribute("URLopener", "urllib", "urllib.request"), - MovedAttribute("FancyURLopener", "urllib", "urllib.request"), - MovedAttribute("proxy_bypass", "urllib", "urllib.request"), - MovedAttribute("parse_http_list", "urllib2", "urllib.request"), - MovedAttribute("parse_keqv_list", "urllib2", "urllib.request"), -] -for attr in _urllib_request_moved_attributes: - setattr(Module_six_moves_urllib_request, attr.name, attr) -del attr - -Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes - -_importer._add_module(Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"), - "moves.urllib_request", "moves.urllib.request") - - -class Module_six_moves_urllib_response(_LazyModule): - - """Lazy loading of moved objects in six.moves.urllib_response""" - - -_urllib_response_moved_attributes = [ - MovedAttribute("addbase", "urllib", "urllib.response"), - MovedAttribute("addclosehook", "urllib", "urllib.response"), - MovedAttribute("addinfo", "urllib", "urllib.response"), - MovedAttribute("addinfourl", "urllib", "urllib.response"), -] -for attr in _urllib_response_moved_attributes: - setattr(Module_six_moves_urllib_response, attr.name, attr) -del attr - -Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes - -_importer._add_module(Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"), - "moves.urllib_response", "moves.urllib.response") - - -class Module_six_moves_urllib_robotparser(_LazyModule): - - """Lazy loading of moved objects in six.moves.urllib_robotparser""" - - -_urllib_robotparser_moved_attributes = [ - MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"), -] -for attr in _urllib_robotparser_moved_attributes: - setattr(Module_six_moves_urllib_robotparser, attr.name, attr) -del attr - -Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes - -_importer._add_module(Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"), - "moves.urllib_robotparser", "moves.urllib.robotparser") - - -class Module_six_moves_urllib(types.ModuleType): - - """Create a six.moves.urllib namespace that resembles the Python 3 namespace""" - __path__ = [] # mark as package - parse = _importer._get_module("moves.urllib_parse") - error = _importer._get_module("moves.urllib_error") - request = _importer._get_module("moves.urllib_request") - response = _importer._get_module("moves.urllib_response") - robotparser = _importer._get_module("moves.urllib_robotparser") - - def __dir__(self): - return ['parse', 'error', 'request', 'response', 'robotparser'] - -_importer._add_module(Module_six_moves_urllib(__name__ + ".moves.urllib"), - "moves.urllib") - - -def add_move(move): - """Add an item to six.moves.""" - setattr(_MovedItems, move.name, move) - - -def remove_move(name): - """Remove item from six.moves.""" - try: - delattr(_MovedItems, name) - except AttributeError: - try: - del moves.__dict__[name] - except KeyError: - raise AttributeError("no such move, %r" % (name,)) - - -if PY3: - _meth_func = "__func__" - _meth_self = "__self__" - - _func_closure = "__closure__" - _func_code = "__code__" - _func_defaults = "__defaults__" - _func_globals = "__globals__" -else: - _meth_func = "im_func" - _meth_self = "im_self" - - _func_closure = "func_closure" - _func_code = "func_code" - _func_defaults = "func_defaults" - _func_globals = "func_globals" - - -try: - advance_iterator = next -except NameError: - def advance_iterator(it): - return it.next() -next = advance_iterator - - -try: - callable = callable -except NameError: - def callable(obj): - return any("__call__" in klass.__dict__ for klass in type(obj).__mro__) - - -if PY3: - def get_unbound_function(unbound): - return unbound - - create_bound_method = types.MethodType - - def create_unbound_method(func, cls): - return func - - Iterator = object -else: - def get_unbound_function(unbound): - return unbound.im_func - - def create_bound_method(func, obj): - return types.MethodType(func, obj, obj.__class__) - - def create_unbound_method(func, cls): - return types.MethodType(func, None, cls) - - class Iterator(object): - - def next(self): - return type(self).__next__(self) - - callable = callable -_add_doc(get_unbound_function, - """Get the function out of a possibly unbound function""") - - -get_method_function = operator.attrgetter(_meth_func) -get_method_self = operator.attrgetter(_meth_self) -get_function_closure = operator.attrgetter(_func_closure) -get_function_code = operator.attrgetter(_func_code) -get_function_defaults = operator.attrgetter(_func_defaults) -get_function_globals = operator.attrgetter(_func_globals) - - -if PY3: - def iterkeys(d, **kw): - return iter(d.keys(**kw)) - - def itervalues(d, **kw): - return iter(d.values(**kw)) - - def iteritems(d, **kw): - return iter(d.items(**kw)) - - def iterlists(d, **kw): - return iter(d.lists(**kw)) - - viewkeys = operator.methodcaller("keys") - - viewvalues = operator.methodcaller("values") - - viewitems = operator.methodcaller("items") -else: - def iterkeys(d, **kw): - return d.iterkeys(**kw) - - def itervalues(d, **kw): - return d.itervalues(**kw) - - def iteritems(d, **kw): - return d.iteritems(**kw) - - def iterlists(d, **kw): - return d.iterlists(**kw) - - viewkeys = operator.methodcaller("viewkeys") - - viewvalues = operator.methodcaller("viewvalues") - - viewitems = operator.methodcaller("viewitems") - -_add_doc(iterkeys, "Return an iterator over the keys of a dictionary.") -_add_doc(itervalues, "Return an iterator over the values of a dictionary.") -_add_doc(iteritems, - "Return an iterator over the (key, value) pairs of a dictionary.") -_add_doc(iterlists, - "Return an iterator over the (key, [values]) pairs of a dictionary.") - - -if PY3: - def b(s): - return s.encode("latin-1") - - def u(s): - return s - unichr = chr - import struct - int2byte = struct.Struct(">B").pack - del struct - byte2int = operator.itemgetter(0) - indexbytes = operator.getitem - iterbytes = iter - import io - StringIO = io.StringIO - BytesIO = io.BytesIO - del io - _assertCountEqual = "assertCountEqual" - if sys.version_info[1] <= 1: - _assertRaisesRegex = "assertRaisesRegexp" - _assertRegex = "assertRegexpMatches" - _assertNotRegex = "assertNotRegexpMatches" - else: - _assertRaisesRegex = "assertRaisesRegex" - _assertRegex = "assertRegex" - _assertNotRegex = "assertNotRegex" -else: - def b(s): - return s - # Workaround for standalone backslash - - def u(s): - return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape") - unichr = unichr - int2byte = chr - - def byte2int(bs): - return ord(bs[0]) - - def indexbytes(buf, i): - return ord(buf[i]) - iterbytes = functools.partial(itertools.imap, ord) - import StringIO - StringIO = BytesIO = StringIO.StringIO - _assertCountEqual = "assertItemsEqual" - _assertRaisesRegex = "assertRaisesRegexp" - _assertRegex = "assertRegexpMatches" - _assertNotRegex = "assertNotRegexpMatches" -_add_doc(b, """Byte literal""") -_add_doc(u, """Text literal""") - - -def assertCountEqual(self, *args, **kwargs): - return getattr(self, _assertCountEqual)(*args, **kwargs) - - -def assertRaisesRegex(self, *args, **kwargs): - return getattr(self, _assertRaisesRegex)(*args, **kwargs) - - -def assertRegex(self, *args, **kwargs): - return getattr(self, _assertRegex)(*args, **kwargs) - - -def assertNotRegex(self, *args, **kwargs): - return getattr(self, _assertNotRegex)(*args, **kwargs) - - -if PY3: - exec_ = getattr(moves.builtins, "exec") - - def reraise(tp, value, tb=None): - try: - if value is None: - value = tp() - if value.__traceback__ is not tb: - raise value.with_traceback(tb) - raise value - finally: - value = None - tb = None - -else: - def exec_(_code_, _globs_=None, _locs_=None): - """Execute code in a namespace.""" - if _globs_ is None: - frame = sys._getframe(1) - _globs_ = frame.f_globals - if _locs_ is None: - _locs_ = frame.f_locals - del frame - elif _locs_ is None: - _locs_ = _globs_ - exec("""exec _code_ in _globs_, _locs_""") - - exec_("""def reraise(tp, value, tb=None): - try: - raise tp, value, tb - finally: - tb = None -""") - - -if sys.version_info[:2] > (3,): - exec_("""def raise_from(value, from_value): - try: - raise value from from_value - finally: - value = None -""") -else: - def raise_from(value, from_value): - raise value - - -print_ = getattr(moves.builtins, "print", None) -if print_ is None: - def print_(*args, **kwargs): - """The new-style print function for Python 2.4 and 2.5.""" - fp = kwargs.pop("file", sys.stdout) - if fp is None: - return - - def write(data): - if not isinstance(data, basestring): - data = str(data) - # If the file has an encoding, encode unicode with it. - if (isinstance(fp, file) and - isinstance(data, unicode) and - fp.encoding is not None): - errors = getattr(fp, "errors", None) - if errors is None: - errors = "strict" - data = data.encode(fp.encoding, errors) - fp.write(data) - want_unicode = False - sep = kwargs.pop("sep", None) - if sep is not None: - if isinstance(sep, unicode): - want_unicode = True - elif not isinstance(sep, str): - raise TypeError("sep must be None or a string") - end = kwargs.pop("end", None) - if end is not None: - if isinstance(end, unicode): - want_unicode = True - elif not isinstance(end, str): - raise TypeError("end must be None or a string") - if kwargs: - raise TypeError("invalid keyword arguments to print()") - if not want_unicode: - for arg in args: - if isinstance(arg, unicode): - want_unicode = True - break - if want_unicode: - newline = unicode("\n") - space = unicode(" ") - else: - newline = "\n" - space = " " - if sep is None: - sep = space - if end is None: - end = newline - for i, arg in enumerate(args): - if i: - write(sep) - write(arg) - write(end) -if sys.version_info[:2] < (3, 3): - _print = print_ - - def print_(*args, **kwargs): - fp = kwargs.get("file", sys.stdout) - flush = kwargs.pop("flush", False) - _print(*args, **kwargs) - if flush and fp is not None: - fp.flush() - -_add_doc(reraise, """Reraise an exception.""") - -if sys.version_info[0:2] < (3, 4): - # This does exactly the same what the :func:`py3:functools.update_wrapper` - # function does on Python versions after 3.2. It sets the ``__wrapped__`` - # attribute on ``wrapper`` object and it doesn't raise an error if any of - # the attributes mentioned in ``assigned`` and ``updated`` are missing on - # ``wrapped`` object. - def _update_wrapper(wrapper, wrapped, - assigned=functools.WRAPPER_ASSIGNMENTS, - updated=functools.WRAPPER_UPDATES): - for attr in assigned: - try: - value = getattr(wrapped, attr) - except AttributeError: - continue - else: - setattr(wrapper, attr, value) - for attr in updated: - getattr(wrapper, attr).update(getattr(wrapped, attr, {})) - wrapper.__wrapped__ = wrapped - return wrapper - _update_wrapper.__doc__ = functools.update_wrapper.__doc__ - - def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS, - updated=functools.WRAPPER_UPDATES): - return functools.partial(_update_wrapper, wrapped=wrapped, - assigned=assigned, updated=updated) - wraps.__doc__ = functools.wraps.__doc__ - -else: - wraps = functools.wraps - - -def with_metaclass(meta, *bases): - """Create a base class with a metaclass.""" - # This requires a bit of explanation: the basic idea is to make a dummy - # metaclass for one level of class instantiation that replaces itself with - # the actual metaclass. - class metaclass(type): - - def __new__(cls, name, this_bases, d): - if sys.version_info[:2] >= (3, 7): - # This version introduced PEP 560 that requires a bit - # of extra care (we mimic what is done by __build_class__). - resolved_bases = types.resolve_bases(bases) - if resolved_bases is not bases: - d['__orig_bases__'] = bases - else: - resolved_bases = bases - return meta(name, resolved_bases, d) - - @classmethod - def __prepare__(cls, name, this_bases): - return meta.__prepare__(name, bases) - return type.__new__(metaclass, 'temporary_class', (), {}) - - -def add_metaclass(metaclass): - """Class decorator for creating a class with a metaclass.""" - def wrapper(cls): - orig_vars = cls.__dict__.copy() - slots = orig_vars.get('__slots__') - if slots is not None: - if isinstance(slots, str): - slots = [slots] - for slots_var in slots: - orig_vars.pop(slots_var) - orig_vars.pop('__dict__', None) - orig_vars.pop('__weakref__', None) - if hasattr(cls, '__qualname__'): - orig_vars['__qualname__'] = cls.__qualname__ - return metaclass(cls.__name__, cls.__bases__, orig_vars) - return wrapper - - -def ensure_binary(s, encoding='utf-8', errors='strict'): - """Coerce **s** to six.binary_type. - - For Python 2: - - `unicode` -> encoded to `str` - - `str` -> `str` - - For Python 3: - - `str` -> encoded to `bytes` - - `bytes` -> `bytes` - """ - if isinstance(s, binary_type): - return s - if isinstance(s, text_type): - return s.encode(encoding, errors) - raise TypeError("not expecting type '%s'" % type(s)) - - -def ensure_str(s, encoding='utf-8', errors='strict'): - """Coerce *s* to `str`. - - For Python 2: - - `unicode` -> encoded to `str` - - `str` -> `str` - - For Python 3: - - `str` -> `str` - - `bytes` -> decoded to `str` - """ - # Optimization: Fast return for the common case. - if type(s) is str: - return s - if PY2 and isinstance(s, text_type): - return s.encode(encoding, errors) - elif PY3 and isinstance(s, binary_type): - return s.decode(encoding, errors) - elif not isinstance(s, (text_type, binary_type)): - raise TypeError("not expecting type '%s'" % type(s)) - return s - - -def ensure_text(s, encoding='utf-8', errors='strict'): - """Coerce *s* to six.text_type. - - For Python 2: - - `unicode` -> `unicode` - - `str` -> `unicode` - - For Python 3: - - `str` -> `str` - - `bytes` -> decoded to `str` - """ - if isinstance(s, binary_type): - return s.decode(encoding, errors) - elif isinstance(s, text_type): - return s - else: - raise TypeError("not expecting type '%s'" % type(s)) - - -def python_2_unicode_compatible(klass): - """ - A class decorator that defines __unicode__ and __str__ methods under Python 2. - Under Python 3 it does nothing. - - To support Python 2 and 3 with a single code base, define a __str__ method - returning text and apply this decorator to the class. - """ - if PY2: - if '__str__' not in klass.__dict__: - raise ValueError("@python_2_unicode_compatible cannot be applied " - "to %s because it doesn't define __str__()." % - klass.__name__) - klass.__unicode__ = klass.__str__ - klass.__str__ = lambda self: self.__unicode__().encode('utf-8') - return klass - - -# Complete the moves implementation. -# This code is at the end of this module to speed up module loading. -# Turn this module into a package. -__path__ = [] # required for PEP 302 and PEP 451 -__package__ = __name__ # see PEP 366 @ReservedAssignment -if globals().get("__spec__") is not None: - __spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable -# Remove other six meta path importers, since they cause problems. This can -# happen if six is removed from sys.modules and then reloaded. (Setuptools does -# this for some reason.) -if sys.meta_path: - for i, importer in enumerate(sys.meta_path): - # Here's some real nastiness: Another "instance" of the six module might - # be floating around. Therefore, we can't use isinstance() to check for - # the six meta path importer, since the other six instance will have - # inserted an importer with different class. - if (type(importer).__name__ == "_SixMetaPathImporter" and - importer.name == __name__): - del sys.meta_path[i] - break - del i, importer -# Finally, add the importer to the meta path import hook. -sys.meta_path.append(_importer) diff --git a/src/poetry/core/_vendor/tomlkit/__init__.py b/src/poetry/core/_vendor/tomlkit/__init__.py index 861e1f619..1abb1eb29 100644 --- a/src/poetry/core/_vendor/tomlkit/__init__.py +++ b/src/poetry/core/_vendor/tomlkit/__init__.py @@ -25,7 +25,7 @@ from .api import ws -__version__ = "0.10.2" +__version__ = "0.11.1" __all__ = [ "aot", "array", diff --git a/src/poetry/core/_vendor/tomlkit/container.py b/src/poetry/core/_vendor/tomlkit/container.py index 2db19e3cb..070c583be 100644 --- a/src/poetry/core/_vendor/tomlkit/container.py +++ b/src/poetry/core/_vendor/tomlkit/container.py @@ -46,6 +46,25 @@ def __init__(self, parsed: bool = False) -> None: def body(self) -> List[Tuple[Optional[Key], Item]]: return self._body + def unwrap(self) -> str: + unwrapped = {} + for k, v in self.items(): + if k is None: + continue + + if isinstance(k, Key): + k = k.key + + if isinstance(v, Item): + v = v.unwrap() + + if k in unwrapped: + merge_dicts(unwrapped[k], v) + else: + unwrapped[k] = v + + return unwrapped + @property def value(self) -> Dict[Any, Any]: d = {} @@ -173,7 +192,7 @@ def append(self, key: Union[Key, str, None], item: Item) -> "Container": item.name = key.key prev = self._previous_item() - prev_ws = isinstance(prev, Whitespace) or ends_with_withespace(prev) + prev_ws = isinstance(prev, Whitespace) or ends_with_whitespace(prev) if isinstance(item, Table): if item.name != key.key: item.invalidate_display_name() @@ -291,7 +310,7 @@ def append(self, key: Union[Key, str, None], item: Item) -> "Container": previous_item = self._body[-1][1] if not ( isinstance(previous_item, Whitespace) - or ends_with_withespace(previous_item) + or ends_with_whitespace(previous_item) or is_table or "\n" in previous_item.trivia.trail ): @@ -327,6 +346,25 @@ def append(self, key: Union[Key, str, None], item: Item) -> "Container": return self + def _remove_at(self, idx: int) -> None: + key = self._body[idx][0] + index = self._map.get(key) + if index is None: + raise NonExistentKey(key) + self._body[idx] = (None, Null()) + + if isinstance(index, tuple): + index = list(index) + index.remove(idx) + if len(index) == 1: + index = index.pop() + else: + index = tuple(index) + self._map[key] = index + else: + dict.__delitem__(self, key.key) + self._map.pop(key) + def remove(self, key: Union[Key, str]) -> "Container": """Remove a key from the container.""" if not isinstance(key, Key): @@ -406,7 +444,7 @@ def _insert_at(self, idx: int, key: Union[Key, str], item: Any) -> "Container": previous_item = self._body[idx - 1][1] if not ( isinstance(previous_item, Whitespace) - or ends_with_withespace(previous_item) + or ends_with_whitespace(previous_item) or isinstance(item, (AoT, Table)) or "\n" in previous_item.trivia.trail ): @@ -700,7 +738,7 @@ def _replace_at( # - it is not the last item last, _ = self._previous_item_with_index() idx = last if idx < 0 else idx - has_ws = ends_with_withespace(value) + has_ws = ends_with_whitespace(value) next_ws = idx < last and isinstance(self._body[idx + 1][1], Whitespace) if idx < last and not (next_ws or has_ws): value.append(None, Whitespace("\n")) @@ -785,7 +823,7 @@ def __init__(self, container: Container, indices: Tuple[int]) -> None: self._tables_map = {} for i in indices: - key, item = self._container._body[i] + _, item = self._container._body[i] if isinstance(item, Table): self._tables.append(item) @@ -796,6 +834,9 @@ def __init__(self, container: Container, indices: Tuple[int]) -> None: if k is not None: dict.__setitem__(self, k.key, v) + def unwrap(self) -> str: + return self._internal_container.unwrap() + @property def value(self): return self._internal_container.value @@ -820,10 +861,20 @@ def __setitem__(self, key: Union[Key, str], item: Any) -> None: if key is not None: dict.__setitem__(self, key, item) + def _remove_table(self, table: Table) -> None: + """Remove table from the parent container""" + self._tables.remove(table) + for idx, item in enumerate(self._container._body): + if item[1] is table: + self._container._remove_at(idx) + break + def __delitem__(self, key: Union[Key, str]) -> None: if key in self._tables_map: table = self._tables[self._tables_map[key]] del table[key] + if not table and len(self._tables) > 1: + self._remove_table(table) del self._tables_map[key] else: raise NonExistentKey(key) @@ -838,15 +889,12 @@ def __iter__(self) -> Iterator[str]: def __len__(self) -> int: return dict.__len__(self) - def __getattr__(self, attribute): - return getattr(self._internal_container, attribute) - def setdefault(self, key: Union[Key, str], default: Any) -> Any: super().setdefault(key, default=default) return self[key] -def ends_with_withespace(it: Any) -> bool: +def ends_with_whitespace(it: Any) -> bool: """Returns ``True`` if the given item ``it`` is a ``Table`` or ``AoT`` object ending with a ``Whitespace``. """ diff --git a/src/poetry/core/_vendor/tomlkit/items.py b/src/poetry/core/_vendor/tomlkit/items.py index bdc97f2ad..0e36b88e1 100644 --- a/src/poetry/core/_vendor/tomlkit/items.py +++ b/src/poetry/core/_vendor/tomlkit/items.py @@ -492,6 +492,10 @@ def as_string(self) -> str: """The TOML representation""" raise NotImplementedError() + def unwrap(self): + """Returns as pure python object (ppo)""" + raise NotImplementedError() + # Helpers def comment(self, comment: str) -> "Item": @@ -610,6 +614,9 @@ def __init__(self, _: int, trivia: Trivia, raw: str) -> None: if re.match(r"^[+\-]\d+$", raw): self._sign = True + def unwrap(self) -> int: + return int(self) + @property def discriminant(self) -> int: return 2 @@ -678,6 +685,9 @@ def __init__(self, _: float, trivia: Trivia, raw: str) -> None: if re.match(r"^[+\-].+$", raw): self._sign = True + def unwrap(self) -> float: + return float(self) + @property def discriminant(self) -> int: return 3 @@ -739,6 +749,9 @@ def __init__(self, t: int, trivia: Trivia) -> None: self._value = bool(t) + def unwrap(self) -> bool: + return bool(self) + @property def discriminant(self) -> int: return 4 @@ -821,6 +834,21 @@ def __init__( self._raw = raw or self.isoformat() + def unwrap(self) -> datetime: + ( + year, + month, + day, + hour, + minute, + second, + microsecond, + tzinfo, + _, + _, + ) = self._getstate() + return datetime(year, month, day, hour, minute, second, microsecond, tzinfo) + @property def discriminant(self) -> int: return 5 @@ -924,6 +952,10 @@ def __init__( self._raw = raw + def unwrap(self) -> date: + (year, month, day, _, _) = self._getstate() + return date(year, month, day) + @property def discriminant(self) -> int: return 6 @@ -996,6 +1028,10 @@ def __init__( self._raw = raw + def unwrap(self) -> datetime: + (hour, minute, second, microsecond, tzinfo, _, _) = self._getstate() + return time(hour, minute, second, microsecond, tzinfo) + @property def discriminant(self) -> int: return 7 @@ -1051,6 +1087,15 @@ def __init__(self, value: list, trivia: Trivia, multiline: bool = False) -> None self._multiline = multiline self._reindex() + def unwrap(self) -> str: + unwrapped = [] + for v in self: + if isinstance(v, Item): + unwrapped.append(v.unwrap()) + else: + unwrapped.append(v) + return unwrapped + @property def discriminant(self) -> int: return 8 @@ -1295,6 +1340,17 @@ def __init__(self, value: "container.Container", trivia: Trivia): if k is not None: dict.__setitem__(self, k.key, v) + def unwrap(self): + unwrapped = {} + for k, v in self.items(): + if isinstance(k, Key): + k = k.key + if isinstance(v, Item): + v = v.unwrap() + unwrapped[k] = v + + return unwrapped + @property def value(self) -> "container.Container": return self._value @@ -1617,6 +1673,9 @@ def __init__(self, t: StringType, _: str, original: str, trivia: Trivia) -> None self._t = t self._original = original + def unwrap(self) -> str: + return str(self) + @property def discriminant(self) -> int: return 11 @@ -1675,6 +1734,15 @@ def __init__( for table in body: self.append(table) + def unwrap(self) -> str: + unwrapped = [] + for t in self._body: + if isinstance(t, Item): + unwrapped.append(t.unwrap()) + else: + unwrapped.append(t) + return unwrapped + @property def body(self) -> List[Table]: return self._body @@ -1766,6 +1834,9 @@ class Null(Item): def __init__(self) -> None: pass + def unwrap(self) -> str: + return None + @property def discriminant(self) -> int: return -1 diff --git a/src/poetry/core/_vendor/tomlkit/parser.py b/src/poetry/core/_vendor/tomlkit/parser.py index dafc4b6ea..2f94daa96 100644 --- a/src/poetry/core/_vendor/tomlkit/parser.py +++ b/src/poetry/core/_vendor/tomlkit/parser.py @@ -146,7 +146,10 @@ def parse(self) -> TOMLDocument: key, value = item if (key is not None and key.is_multi()) or not self._merge_ws(value, body): # We actually have a table - body.append(key, value) + try: + body.append(key, value) + except Exception as e: + raise self.parse_error(ParseError, str(e)) from e self.mark() @@ -157,7 +160,10 @@ def parse(self) -> TOMLDocument: # along with it. value = self._parse_aot(value, key) - body.append(key, value) + try: + body.append(key, value) + except Exception as e: + raise self.parse_error(ParseError, str(e)) from e body.parsing(False) diff --git a/src/poetry/core/_vendor/tomlkit/toml_file.py b/src/poetry/core/_vendor/tomlkit/toml_file.py index 47c9f2c23..5b28cb037 100644 --- a/src/poetry/core/_vendor/tomlkit/toml_file.py +++ b/src/poetry/core/_vendor/tomlkit/toml_file.py @@ -1,3 +1,6 @@ +import os +import re + from .api import loads from .toml_document import TOMLDocument @@ -11,13 +14,35 @@ class TOMLFile: def __init__(self, path: str) -> None: self._path = path + self._linesep = os.linesep def read(self) -> TOMLDocument: """Read the file content as a :class:`tomlkit.toml_document.TOMLDocument`.""" with open(self._path, encoding="utf-8", newline="") as f: - return loads(f.read()) + content = f.read() + + # check if consistent line endings + num_newline = content.count("\n") + if num_newline > 0: + num_win_eol = content.count("\r\n") + if num_win_eol == num_newline: + self._linesep = "\r\n" + elif num_win_eol == 0: + self._linesep = "\n" + else: + self._linesep = "mixed" + + return loads(content) def write(self, data: TOMLDocument) -> None: """Write the TOMLDocument to the file.""" + content = data.as_string() + + # apply linesep + if self._linesep == "\n": + content = content.replace("\r\n", "\n") + elif self._linesep == "\r\n": + content = re.sub(r"(? int: # keyword with old-style TypedDict(). See https://bugs.python.org/issue42059 # The standard library TypedDict below Python 3.11 does not store runtime # information about optional and required keys when using Required or NotRequired. + # Generic TypedDicts are also impossible using typing.TypedDict on Python <3.11. TypedDict = typing.TypedDict _TypedDictMeta = typing._TypedDictMeta is_typeddict = typing.is_typeddict @@ -695,8 +707,16 @@ def __new__(cls, name, bases, ns, total=True): # Subclasses and instances of TypedDict return actual dictionaries # via _dict_new. ns['__new__'] = _typeddict_new if name == 'TypedDict' else _dict_new + # Don't insert typing.Generic into __bases__ here, + # or Generic.__init_subclass__ will raise TypeError + # in the super().__new__() call. + # Instead, monkey-patch __bases__ onto the class after it's been created. tp_dict = super().__new__(cls, name, (dict,), ns) + if any(issubclass(base, typing.Generic) for base in bases): + tp_dict.__bases__ = (typing.Generic, dict) + _maybe_adjust_parameters(tp_dict) + annotations = {} own_annotations = ns.get('__annotations__', {}) msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type" @@ -1958,3 +1978,92 @@ def decorator(cls_or_fn): if not hasattr(typing, "TypeVarTuple"): typing._collect_type_vars = _collect_type_vars typing._check_generic = _check_generic + + +# Backport typing.NamedTuple as it exists in Python 3.11. +# In 3.11, the ability to define generic `NamedTuple`s was supported. +# This was explicitly disallowed in 3.9-3.10, and only half-worked in <=3.8. +if sys.version_info >= (3, 11): + NamedTuple = typing.NamedTuple +else: + def _caller(): + try: + return sys._getframe(2).f_globals.get('__name__', '__main__') + except (AttributeError, ValueError): # For platforms without _getframe() + return None + + def _make_nmtuple(name, types, module, defaults=()): + fields = [n for n, t in types] + annotations = {n: typing._type_check(t, f"field {n} annotation must be a type") + for n, t in types} + nm_tpl = collections.namedtuple(name, fields, + defaults=defaults, module=module) + nm_tpl.__annotations__ = nm_tpl.__new__.__annotations__ = annotations + # The `_field_types` attribute was removed in 3.9; + # in earlier versions, it is the same as the `__annotations__` attribute + if sys.version_info < (3, 9): + nm_tpl._field_types = annotations + return nm_tpl + + _prohibited_namedtuple_fields = typing._prohibited + _special_namedtuple_fields = frozenset({'__module__', '__name__', '__annotations__'}) + + class _NamedTupleMeta(type): + def __new__(cls, typename, bases, ns): + assert _NamedTuple in bases + for base in bases: + if base is not _NamedTuple and base is not typing.Generic: + raise TypeError( + 'can only inherit from a NamedTuple type and Generic') + bases = tuple(tuple if base is _NamedTuple else base for base in bases) + types = ns.get('__annotations__', {}) + default_names = [] + for field_name in types: + if field_name in ns: + default_names.append(field_name) + elif default_names: + raise TypeError(f"Non-default namedtuple field {field_name} " + f"cannot follow default field" + f"{'s' if len(default_names) > 1 else ''} " + f"{', '.join(default_names)}") + nm_tpl = _make_nmtuple( + typename, types.items(), + defaults=[ns[n] for n in default_names], + module=ns['__module__'] + ) + nm_tpl.__bases__ = bases + if typing.Generic in bases: + class_getitem = typing.Generic.__class_getitem__.__func__ + nm_tpl.__class_getitem__ = classmethod(class_getitem) + # update from user namespace without overriding special namedtuple attributes + for key in ns: + if key in _prohibited_namedtuple_fields: + raise AttributeError("Cannot overwrite NamedTuple attribute " + key) + elif key not in _special_namedtuple_fields and key not in nm_tpl._fields: + setattr(nm_tpl, key, ns[key]) + if typing.Generic in bases: + nm_tpl.__init_subclass__() + return nm_tpl + + def NamedTuple(__typename, __fields=None, **kwargs): + if __fields is None: + __fields = kwargs.items() + elif kwargs: + raise TypeError("Either list of fields or keywords" + " can be provided to NamedTuple, not both") + return _make_nmtuple(__typename, __fields, module=_caller()) + + NamedTuple.__doc__ = typing.NamedTuple.__doc__ + _NamedTuple = type.__new__(_NamedTupleMeta, 'NamedTuple', (), {}) + + # On 3.8+, alter the signature so that it matches typing.NamedTuple. + # The signature of typing.NamedTuple on >=3.8 is invalid syntax in Python 3.7, + # so just leave the signature as it is on 3.7. + if sys.version_info >= (3, 8): + NamedTuple.__text_signature__ = '(typename, fields=None, /, **kwargs)' + + def _namedtuple_mro_entries(bases): + assert NamedTuple in bases + return (_NamedTuple,) + + NamedTuple.__mro_entries__ = _namedtuple_mro_entries diff --git a/src/poetry/core/_vendor/vendor.txt b/src/poetry/core/_vendor/vendor.txt index 50788c9da..cbdc1a8f5 100644 --- a/src/poetry/core/_vendor/vendor.txt +++ b/src/poetry/core/_vendor/vendor.txt @@ -1,9 +1,8 @@ attrs==21.4.0; python_version >= "3.7" and python_full_version < "3.0.0" or python_full_version >= "3.5.0" and python_version >= "3.7" -jsonschema==4.5.1; python_version >= "3.7" +jsonschema==4.6.2; python_version >= "3.7" lark==1.1.2 packaging==21.3; python_version >= "3.6" -pyparsing==3.0.8; python_full_version >= "3.6.8" and python_version >= "3.6" -pyrsistent==0.16.1; python_version >= "3.7" -six==1.16.0; python_version >= "3.7" and python_full_version < "3.0.0" or python_full_version >= "3.3.0" and python_version >= "3.7" -tomlkit==0.10.2; python_version >= "3.6" and python_version < "4.0" -typing-extensions==4.2.0; python_version >= "3.7" +pyparsing==3.0.9; python_full_version >= "3.6.8" and python_version >= "3.6" +pyrsistent==0.18.1; python_version >= "3.7" +tomlkit==0.11.1; python_version >= "3.6" and python_version < "4.0" +typing-extensions==4.3.0; python_version >= "3.7" diff --git a/vendors/poetry.lock b/vendors/poetry.lock index 123f9a416..03a8c2b30 100644 --- a/vendors/poetry.lock +++ b/vendors/poetry.lock @@ -14,7 +14,7 @@ tests_no_zope = ["coverage[toml] (>=5.0.2)", "hypothesis", "pympler", "pytest (> [[package]] name = "importlib-metadata" -version = "4.11.3" +version = "4.12.0" description = "Read metadata from Python packages" category = "main" optional = false @@ -27,11 +27,11 @@ zipp = ">=0.5" [package.extras] docs = ["sphinx", "jaraco.packaging (>=9)", "rst.linker (>=1.9)"] perf = ["ipython"] -testing = ["pytest (>=6)", "pytest-checkdocs (>=2.4)", "pytest-flake8", "pytest-cov", "pytest-enabler (>=1.0.1)", "packaging", "pyfakefs", "flufl.flake8", "pytest-perf (>=0.9.2)", "pytest-black (>=0.3.7)", "pytest-mypy (>=0.9.1)", "importlib-resources (>=1.3)"] +testing = ["pytest (>=6)", "pytest-checkdocs (>=2.4)", "pytest-flake8", "pytest-cov", "pytest-enabler (>=1.3)", "packaging", "pyfakefs", "flufl.flake8", "pytest-perf (>=0.9.2)", "pytest-black (>=0.3.7)", "pytest-mypy (>=0.9.1)", "importlib-resources (>=1.3)"] [[package]] name = "importlib-resources" -version = "5.7.1" +version = "5.8.0" description = "Read resources from Python packages" category = "main" optional = false @@ -46,7 +46,7 @@ testing = ["pytest (>=6)", "pytest-checkdocs (>=2.4)", "pytest-flake8", "pytest- [[package]] name = "jsonschema" -version = "4.5.1" +version = "4.6.2" description = "An implementation of JSON Schema validation for Python" category = "main" optional = false @@ -61,7 +61,7 @@ typing-extensions = {version = "*", markers = "python_version < \"3.8\""} [package.extras] format = ["fqdn", "idna", "isoduration", "jsonpointer (>1.13)", "rfc3339-validator", "rfc3987", "uri-template", "webcolors (>=1.11)"] -format_nongpl = ["fqdn", "idna", "isoduration", "jsonpointer (>1.13)", "rfc3339-validator", "rfc3986-validator (>0.1.0)", "uri-template", "webcolors (>=1.11)"] +format-nongpl = ["fqdn", "idna", "isoduration", "jsonpointer (>1.13)", "rfc3339-validator", "rfc3986-validator (>0.1.0)", "uri-template", "webcolors (>=1.11)"] [[package]] name = "lark" @@ -89,7 +89,7 @@ pyparsing = ">=2.0.2,<3.0.5 || >3.0.5" [[package]] name = "pyparsing" -version = "3.0.8" +version = "3.0.9" description = "pyparsing module - Classes and methods to define and execute parsing grammars" category = "main" optional = false @@ -100,26 +100,15 @@ diagrams = ["railroad-diagrams", "jinja2"] [[package]] name = "pyrsistent" -version = "0.16.1" +version = "0.18.1" description = "Persistent/Functional/Immutable data structures" category = "main" optional = false -python-versions = ">=2.7" - -[package.dependencies] -six = "*" - -[[package]] -name = "six" -version = "1.16.0" -description = "Python 2 and 3 compatibility utilities" -category = "main" -optional = false -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*" +python-versions = ">=3.7" [[package]] name = "tomlkit" -version = "0.10.2" +version = "0.11.1" description = "Style preserving TOML library" category = "main" optional = false @@ -127,7 +116,7 @@ python-versions = ">=3.6,<4.0" [[package]] name = "typing-extensions" -version = "4.2.0" +version = "4.3.0" description = "Backported and Experimental Type Hints for Python 3.7+" category = "main" optional = false @@ -148,7 +137,7 @@ testing = ["pytest (>=6)", "pytest-checkdocs (>=2.4)", "pytest-flake8", "pytest- [metadata] lock-version = "1.1" python-versions = "^3.7" -content-hash = "6676696493a6787a0200b15ce2824604a38abe424b54465481d3d79c71a0e3dd" +content-hash = "23292eec87b0c9b74619143ac531f78902eb7bf928ac406b931a481c8a25a10d" [metadata.files] attrs = [ @@ -156,16 +145,16 @@ attrs = [ {file = "attrs-21.4.0.tar.gz", hash = "sha256:626ba8234211db98e869df76230a137c4c40a12d72445c45d5f5b716f076e2fd"}, ] importlib-metadata = [ - {file = "importlib_metadata-4.11.3-py3-none-any.whl", hash = "sha256:1208431ca90a8cca1a6b8af391bb53c1a2db74e5d1cef6ddced95d4b2062edc6"}, - {file = "importlib_metadata-4.11.3.tar.gz", hash = "sha256:ea4c597ebf37142f827b8f39299579e31685c31d3a438b59f469406afd0f2539"}, + {file = "importlib_metadata-4.12.0-py3-none-any.whl", hash = "sha256:7401a975809ea1fdc658c3aa4f78cc2195a0e019c5cbc4c06122884e9ae80c23"}, + {file = "importlib_metadata-4.12.0.tar.gz", hash = "sha256:637245b8bab2b6502fcbc752cc4b7a6f6243bb02b31c5c26156ad103d3d45670"}, ] importlib-resources = [ - {file = "importlib_resources-5.7.1-py3-none-any.whl", hash = "sha256:e447dc01619b1e951286f3929be820029d48c75eb25d265c28b92a16548212b8"}, - {file = "importlib_resources-5.7.1.tar.gz", hash = "sha256:b6062987dfc51f0fcb809187cffbd60f35df7acb4589091f154214af6d0d49d3"}, + {file = "importlib_resources-5.8.0-py3-none-any.whl", hash = "sha256:7952325ffd516c05a8ad0858c74dff2c3343f136fe66a6002b2623dd1d43f223"}, + {file = "importlib_resources-5.8.0.tar.gz", hash = "sha256:568c9f16cb204f9decc8d6d24a572eeea27dacbb4cee9e6b03a8025736769751"}, ] jsonschema = [ - {file = "jsonschema-4.5.1-py3-none-any.whl", hash = "sha256:71b5e39324422543546572954ce71c67728922c104902cb7ce252e522235b33f"}, - {file = "jsonschema-4.5.1.tar.gz", hash = "sha256:7c6d882619340c3347a1bf7315e147e6d3dae439033ae6383d6acb908c101dfc"}, + {file = "jsonschema-4.6.2-py3-none-any.whl", hash = "sha256:e331e32e29743014fa59fa77895b5d8669382a4904c8ef23144f7f078ec031c7"}, + {file = "jsonschema-4.6.2.tar.gz", hash = "sha256:b19f62322b0f06927e8ae6215c01654e1885857cdcaf58ae1772b1aa97f1faf2"}, ] lark = [ {file = "lark-1.1.2-py2.py3-none-any.whl", hash = "sha256:c1ab213fc5e2d273fe2d91da218ccc8b5b92d065b17faa5e743499cb16594b7d"}, @@ -176,23 +165,39 @@ packaging = [ {file = "packaging-21.3.tar.gz", hash = "sha256:dd47c42927d89ab911e606518907cc2d3a1f38bbd026385970643f9c5b8ecfeb"}, ] pyparsing = [ - {file = "pyparsing-3.0.8-py3-none-any.whl", hash = "sha256:ef7b523f6356f763771559412c0d7134753f037822dad1b16945b7b846f7ad06"}, - {file = "pyparsing-3.0.8.tar.gz", hash = "sha256:7bf433498c016c4314268d95df76c81b842a4cb2b276fa3312cfb1e1d85f6954"}, + {file = "pyparsing-3.0.9-py3-none-any.whl", hash = "sha256:5026bae9a10eeaefb61dab2f09052b9f4307d44aee4eda64b309723d8d206bbc"}, + {file = "pyparsing-3.0.9.tar.gz", hash = "sha256:2b020ecf7d21b687f219b71ecad3631f644a47f01403fa1d1036b0c6416d70fb"}, ] pyrsistent = [ - {file = "pyrsistent-0.16.1.tar.gz", hash = "sha256:aa2ae1c2e496f4d6777f869ea5de7166a8ccb9c2e06ebcf6c7ff1b670c98c5ef"}, -] -six = [ - {file = "six-1.16.0-py2.py3-none-any.whl", hash = "sha256:8abb2f1d86890a2dfb989f9a77cfcfd3e47c2a354b01111771326f8aa26e0254"}, - {file = "six-1.16.0.tar.gz", hash = "sha256:1e61c37477a1626458e36f7b1d82aa5c9b094fa4802892072e49de9c60c4c926"}, + {file = "pyrsistent-0.18.1-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:df46c854f490f81210870e509818b729db4488e1f30f2a1ce1698b2295a878d1"}, + {file = "pyrsistent-0.18.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:5d45866ececf4a5fff8742c25722da6d4c9e180daa7b405dc0a2a2790d668c26"}, + {file = "pyrsistent-0.18.1-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:4ed6784ceac462a7d6fcb7e9b663e93b9a6fb373b7f43594f9ff68875788e01e"}, + {file = "pyrsistent-0.18.1-cp310-cp310-win32.whl", hash = "sha256:e4f3149fd5eb9b285d6bfb54d2e5173f6a116fe19172686797c056672689daf6"}, + {file = "pyrsistent-0.18.1-cp310-cp310-win_amd64.whl", hash = "sha256:636ce2dc235046ccd3d8c56a7ad54e99d5c1cd0ef07d9ae847306c91d11b5fec"}, + {file = "pyrsistent-0.18.1-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:e92a52c166426efbe0d1ec1332ee9119b6d32fc1f0bbfd55d5c1088070e7fc1b"}, + {file = "pyrsistent-0.18.1-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d7a096646eab884bf8bed965bad63ea327e0d0c38989fc83c5ea7b8a87037bfc"}, + {file = "pyrsistent-0.18.1-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:cdfd2c361b8a8e5d9499b9082b501c452ade8bbf42aef97ea04854f4a3f43b22"}, + {file = "pyrsistent-0.18.1-cp37-cp37m-win32.whl", hash = "sha256:7ec335fc998faa4febe75cc5268a9eac0478b3f681602c1f27befaf2a1abe1d8"}, + {file = "pyrsistent-0.18.1-cp37-cp37m-win_amd64.whl", hash = "sha256:6455fc599df93d1f60e1c5c4fe471499f08d190d57eca040c0ea182301321286"}, + {file = "pyrsistent-0.18.1-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:fd8da6d0124efa2f67d86fa70c851022f87c98e205f0594e1fae044e7119a5a6"}, + {file = "pyrsistent-0.18.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7bfe2388663fd18bd8ce7db2c91c7400bf3e1a9e8bd7d63bf7e77d39051b85ec"}, + {file = "pyrsistent-0.18.1-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:0e3e1fcc45199df76053026a51cc59ab2ea3fc7c094c6627e93b7b44cdae2c8c"}, + {file = "pyrsistent-0.18.1-cp38-cp38-win32.whl", hash = "sha256:b568f35ad53a7b07ed9b1b2bae09eb15cdd671a5ba5d2c66caee40dbf91c68ca"}, + {file = "pyrsistent-0.18.1-cp38-cp38-win_amd64.whl", hash = "sha256:d1b96547410f76078eaf66d282ddca2e4baae8964364abb4f4dcdde855cd123a"}, + {file = "pyrsistent-0.18.1-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:f87cc2863ef33c709e237d4b5f4502a62a00fab450c9e020892e8e2ede5847f5"}, + {file = "pyrsistent-0.18.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6bc66318fb7ee012071b2792024564973ecc80e9522842eb4e17743604b5e045"}, + {file = "pyrsistent-0.18.1-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:914474c9f1d93080338ace89cb2acee74f4f666fb0424896fcfb8d86058bf17c"}, + {file = "pyrsistent-0.18.1-cp39-cp39-win32.whl", hash = "sha256:1b34eedd6812bf4d33814fca1b66005805d3640ce53140ab8bbb1e2651b0d9bc"}, + {file = "pyrsistent-0.18.1-cp39-cp39-win_amd64.whl", hash = "sha256:e24a828f57e0c337c8d8bb9f6b12f09dfdf0273da25fda9e314f0b684b415a07"}, + {file = "pyrsistent-0.18.1.tar.gz", hash = "sha256:d4d61f8b993a7255ba714df3aca52700f8125289f84f704cf80916517c46eb96"}, ] tomlkit = [ - {file = "tomlkit-0.10.2-py3-none-any.whl", hash = "sha256:905cf92c2111ef80d355708f47ac24ad1b6fc2adc5107455940088c9bbecaedb"}, - {file = "tomlkit-0.10.2.tar.gz", hash = "sha256:30d54c0b914e595f3d10a87888599eab5321a2a69abc773bbefff51599b72db6"}, + {file = "tomlkit-0.11.1-py3-none-any.whl", hash = "sha256:1c5bebdf19d5051e2e1de6cf70adfc5948d47221f097fcff7a3ffc91e953eaf5"}, + {file = "tomlkit-0.11.1.tar.gz", hash = "sha256:61901f81ff4017951119cd0d1ed9b7af31c821d6845c8c477587bbdcd5e5854e"}, ] typing-extensions = [ - {file = "typing_extensions-4.2.0-py3-none-any.whl", hash = "sha256:6657594ee297170d19f67d55c05852a874e7eb634f4f753dbd667855e07c1708"}, - {file = "typing_extensions-4.2.0.tar.gz", hash = "sha256:f1c24655a0da0d1b67f07e17a5e6b2a105894e6824b92096378bb3668ef02376"}, + {file = "typing_extensions-4.3.0-py3-none-any.whl", hash = "sha256:25642c956049920a5aa49edcdd6ab1e06d7e5d467fc00e0506c44ac86fbfca02"}, + {file = "typing_extensions-4.3.0.tar.gz", hash = "sha256:e6d2677a32f47fc7eb2795db1dd15c1f34eff616bcaf2cfb5e997f854fa1c4a6"}, ] zipp = [ {file = "zipp-3.8.0-py3-none-any.whl", hash = "sha256:c4f6e5bbf48e74f7a38e7cc5b0480ff42b0ae5178957d564d18932525d5cf099"}, diff --git a/vendors/pyproject.toml b/vendors/pyproject.toml index 3d0868022..f830c24f5 100644 --- a/vendors/pyproject.toml +++ b/vendors/pyproject.toml @@ -24,7 +24,7 @@ python = "^3.7" jsonschema = "^4.5.1" lark = "^1.1.2" packaging = ">=20.9" -tomlkit = ">=0.10.2,<1.0.0" +tomlkit = ">=0.11.1,<1.0.0" # Needed by jsonschema and only at python < 3.8, but to make # sure that it is always delivered we add an unconditional