Source code for pcapkit.vendor.pop3.response_code

# -*- coding: utf-8 -*-
"""POP3 Response Code
========================

.. module:: pcapkit.vendor.pop3.response_code

This module contains the vendor crawler for **POP3 Response Code**,
which is automatically generating :class:`pcapkit.const.pop3.response_code.ResponseCode`.

The codes are IANA's POP3 Response Codes registry, which :rfc:`2449#section-9`
established. A code is hierarchical, its levels separated by ``/``, and a client
ignores the levels it does not know (:rfc:`2449#section-8`), so the generated
``_missing_`` resolves a code to the member its longest prefix of whole levels
names, and only a code no such prefix names to an unregistered member.

"""

import collections
import csv
import re
import sys
from typing import TYPE_CHECKING

from pcapkit.vendor.default import Vendor

if TYPE_CHECKING:
    from collections import Counter
    from typing import Callable

__all__ = ['ResponseCode']

#: Constant template of the registry, a ``StrEnum``.
LINE = lambda NAME, DOCS, ENUM, MODL: f'''\
# -*- coding: utf-8 -*-
# pylint: disable=line-too-long
"""{(name := DOCS.split(' [', maxsplit=1)[0])}
{'=' * (len(name) + 6)}

.. module:: {MODL.replace('vendor', 'const')}

This module contains the constant enumeration for **{name}**,
which is automatically generated from :class:`{MODL}.{NAME}`.

"""

import re
from typing import TYPE_CHECKING

from aenum import StrEnum

from pcapkit.corekit.enum import EnumRegistry
from pcapkit.corekit.sentinels import NO_DEFAULT
from pcapkit.utilities.exceptions import EnumValueError

if TYPE_CHECKING:
    from typing import Any

__all__ = ['{NAME}']


class {NAME}(EnumRegistry, StrEnum):
    """[{NAME}] {DOCS}"""

    {ENUM}

    @classmethod
    def get(cls, key: 'Any', default: 'Any' = NO_DEFAULT) -> '{NAME}':
        """Resolve ``key`` to a member, folding a :class:`str` to upper case.

        A response code is read case-insensitively (:rfc:`2449#section-8`),
        and each member is valued its code in upper case.

        Args:
            key: Key to get enum item.
            default: An already-registered value to fall back to, as
                :meth:`~pcapkit.corekit.enum.EnumLookup.get` takes it.

        Returns:
            The member ``key`` names or carries.

        Raises:
            EnumKeyError: If ``key`` names no member and there is no usable
                ``default``.
            EnumValueError: If ``key`` is not a :class:`str` and there is no
                usable ``default``.

        """
        if isinstance(key, str):
            return super().get(key.upper(), default)
        return super().get(key, default)

    @classmethod
    def _validate_value(cls, value: 'Any') -> 'None':
        """Reject ``value`` unless it is a code, as :meth:`_missing_` does.

        Args:
            value: Value about to be looked up or minted.

        Raises:
            EnumValueError: If ``value`` is not a :class:`str` of one or more
                levels separated by ``/``, as the ``resp-code`` grammar of
                :rfc:`2449#section-3` has them inside its brackets.

        """
        if not (isinstance(value, str) and re.fullmatch(r'[\\x21-\\x2e\\x30-\\x5c\\x5e-\\x7f]+(?:/[\\x21-\\x2e\\x30-\\x5c\\x5e-\\x7f]+)*', value)):
            raise EnumValueError(f'{{value!r}} is not a valid {{cls.__name__}}')

    @classmethod
    def _missing_(cls, value: 'str') -> '{NAME}':
        """Lookup function used when value is not found.

        Args:
            value: Value to get enum item, matched case-insensitively and by its
                longest prefix of whole levels that a member carries, since a
                client ignores the levels it does not know
                (:rfc:`2449#section-8`). A code no such prefix matches resolves
                to an unregistered member named after it in upper case and
                valued as given (:issue:`860`).

        """
        if not (isinstance(value, str) and re.fullmatch(r'[\\x21-\\x2e\\x30-\\x5c\\x5e-\\x7f]+(?:/[\\x21-\\x2e\\x30-\\x5c\\x5e-\\x7f]+)*', value)):
            raise ValueError(f'{{value!r}} is not a valid {{cls.__name__}}')
        levels = value.upper().split('/')
        for end in range(len(levels), 0, -1):
            prefix = '/'.join(levels[:end])
            if prefix in cls._value2member_map_:
                return cls._value2member_map_[prefix]
        return cls._unregistered_member(value, value.upper())
'''.strip()  # type: Callable[[str, str, str, str], str]


[docs] class ResponseCode(Vendor): """POP3 Response Code""" #: Link to registry. LINK = 'https://www.iana.org/assignments/pop3-extension-mechanism/pop3-extension-mechanism-2.csv' def count(self, data: 'list[str]') -> 'Counter[str]': """Count field records. Args: data: CSV data. Returns: Field recordings. """ reader = csv.reader(data) next(reader) # header return collections.Counter(map(lambda item: self.safe_name(item[0]), reader)) def process(self, data: 'list[str]') -> 'tuple[list[str], list[str]]': """Process CSV data. Args: data: CSV data. Returns: Enumeration fields and missing fields, the latter always empty: the template's ``_missing_`` is the same for every registry content. Raises: ValueError: If a code is not upper case, which the case-insensitive lookup would never find, or a reference is not an RFC. """ enum = [] # type: list[str] reader = csv.reader(data) next(reader) # header for item in reader: code, kind, refs = item[0].strip(), item[1].strip(), item[3].strip() if code != code.upper(): raise ValueError(f'{code!r} is not in upper case, which the lookup folds to') cites = [] # type: list[str] for ref in self.split_references(refs): # NOTE: raise rather than guess a citation the role cannot render (#1664). if (match := re.fullmatch(r'RFC(\d+)', ref.strip())) is None: raise ValueError(f'{code!r} cites {ref!r}, which is not an RFC') cites.append(f'[:rfc:`{match.group(1)}`]') desc = self.wrap_comment(f'{code}, in {kind} responses {"".join(cites)}') enum.append(f'#: {desc}\n {self.safe_name(code)} = {code!r}') return enum, [] def context(self, data: 'list[str]') -> 'str': """Generate constant context. Args: data: CSV data. Returns: Constant context. """ enum, _ = self.process(data) ENUM = '\n\n '.join(map(lambda s: s.rstrip(), enum)).strip() return LINE(self.NAME, self.DOCS, ENUM, self.__module__)
if __name__ == '__main__': sys.exit(ResponseCode()) # type: ignore[arg-type]