# -*- coding: utf-8 -*-
"""POP3 Command
==================
.. module:: pcapkit.vendor.pop3.command
This module contains the vendor crawler for **POP3 Command**,
which is automatically generating :class:`pcapkit.const.pop3.command.Command`.
No registry lists every POP3 command: :rfc:`1939#section-9` sums up the base
ones, :rfc:`2449#section-5` adds ``CAPA``, and IANA's POP3 Capabilities registry
names the commands its extensions add without listing the base ones. So the
crawler reads a ``DATA`` literal transcribed from those RFCs, as
:mod:`pcapkit.vendor.linux.arphrd` does (:ref:`const-vendor-pairing`). A keyword
no RFC there defines resolves to an unregistered member.
"""
import collections
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__ = ['Command']
#: Each command keyword mapped to the synopsis its RFC gives, or the keyword
#: alone where it gives none, and the sections that define it: the commands of
#: :rfc:`1939#section-9`, ``CAPA``, and the commands IANA's POP3 Capabilities
#: registry records as added.
DATA = {
'USER': ('USER name', (':rfc:`1939#section-7`',)),
'PASS': ('PASS string', (':rfc:`1939#section-7`',)),
'QUIT': ('QUIT', (':rfc:`1939#section-4`', ':rfc:`1939#section-6`')),
'STAT': ('STAT', (':rfc:`1939#section-5`',)),
'LIST': ('LIST [msg]', (':rfc:`1939#section-5`',)),
'RETR': ('RETR msg', (':rfc:`1939#section-5`',)),
'DELE': ('DELE msg', (':rfc:`1939#section-5`',)),
'NOOP': ('NOOP', (':rfc:`1939#section-5`',)),
'RSET': ('RSET', (':rfc:`1939#section-5`',)),
'APOP': ('APOP name digest', (':rfc:`1939#section-7`',)),
'TOP': ('TOP msg n', (':rfc:`1939#section-7`',)),
'UIDL': ('UIDL [msg]', (':rfc:`1939#section-7`',)),
'CAPA': ('CAPA', (':rfc:`2449#section-5`',)),
'STLS': ('STLS', (':rfc:`2595#section-4`',)),
'AUTH': ('AUTH mechanism [initial-response]', (':rfc:`5034#section-4`',)),
'UTF8': ('UTF8', (':rfc:`6856#section-2.1`',)),
'LANG': ('LANG', (':rfc:`6856#section-3`',)),
} # type: dict[str, tuple[str, tuple[str, ...]]]
#: 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}`.
"""
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.
Command keywords are not case-sensitive (:rfc:`1939#section-3`), and
each member is named, and valued, its keyword 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 :class:`str`, as :meth:`_missing_` does.
Args:
value: Value about to be looked up or minted.
Raises:
EnumValueError: If ``value`` is not a :class:`str`.
"""
if not isinstance(value, str):
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 against the
member names (:rfc:`1939#section-3`). A keyword no member names
resolves to an unregistered member named after it in upper case
and valued as given (:issue:`860`).
"""
if not isinstance(value, str):
raise ValueError(f'{{value!r}} is not a valid {{cls.__name__}}')
name = value.upper()
if name in cls._member_map_: # pylint: disable=no-member
return cls._member_map_[name] # pylint: disable=no-member
return cls._unregistered_member(value, name)
'''.strip() # type: Callable[[str, str, str, str], str]
[docs]
class Command(Vendor):
"""POP3 Command"""
def request(self) -> 'dict[str, tuple[str, tuple[str, ...]]]': # type: ignore[override] # pylint: disable=arguments-differ
"""Fetch registry data.
Returns:
Registry data (:data:`~pcapkit.vendor.pop3.command.DATA`).
"""
return DATA
def count(self, data: 'dict[str, tuple[str, tuple[str, ...]]]') -> 'Counter[str]': # type: ignore[override]
"""Count field records.
Args:
data: Registry data.
Returns:
Field recordings.
"""
return collections.Counter(data)
def process(self, data: 'dict[str, tuple[str, tuple[str, ...]]]') -> 'list[str]': # type: ignore[override]
"""Process registry data.
Args:
data: Registry data.
Returns:
Enumeration fields.
"""
enum = [] # type: list[str]
for keyword, (synopsis, cites) in data.items():
refs = ''.join(f'[{cite}]' for cite in cites)
enum.append(f'#: {synopsis} {refs}\n {keyword} = {keyword!r}')
return enum
def context(self, data: 'dict[str, tuple[str, tuple[str, ...]]]') -> 'str': # type: ignore[override]
"""Generate constant context.
Args:
data: Registry data.
Returns:
Constant context.
"""
ENUM = '\n\n '.join(self.process(data))
return LINE(self.NAME, self.DOCS, ENUM, self.__module__)
if __name__ == '__main__':
sys.exit(Command()) # type: ignore[arg-type]