Skip to content

Commit

Permalink
Always resolve a command to a Code object.
Browse files Browse the repository at this point in the history
Allows downstream clients to rely on numerics before and after a name is defined for that command. Closes #214.
  • Loading branch information
jaraco committed Jul 14, 2024
1 parent 497aba6 commit 90d541b
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 7 deletions.
8 changes: 1 addition & 7 deletions irc/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -340,7 +340,7 @@ def _process_line(self, line):
grp = _rfc_1459_command_regexp.match(line).group

source = NickMask.from_group(grp("prefix"))
command = self._command_from_group(grp("command"))
command = events.Code.lookup(grp("command"))
arguments = message.Arguments.from_group(grp('argument'))
tags = message.Tag.from_group(grp('tags'))

Expand Down Expand Up @@ -431,12 +431,6 @@ def _handle_other(self, arguments, command, source, tags):
event = Event(command, source, target, arguments, tags)
self._handle_event(event)

@staticmethod
def _command_from_group(group):
command = group.lower()
# Translate numerics into more readable strings.
return events.numeric.get(command, command)

def _handle_event(self, event):
"""[Internal]"""
self.reactor._handle_event(self, event)
Expand Down
38 changes: 38 additions & 0 deletions irc/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,42 @@ def __init__(self, code, name):
def __int__(self):
return int(self.code)

@staticmethod
def lookup(command) -> 'Code':
"""
Lookup a command by numeric or by name.
>>> Code.lookup('002')
'yourhost'
>>> Code.lookup('002').code
'002'
>>> int(Code.lookup('002'))
2
>>> int(Code.lookup('yourhost'))
2
>>> Code.lookup('yourhost').code
'002'
If a command is supplied that's an unrecognized name or code,
a Code object is still returned.
>>> fallback = Code.lookup('Unknown-command')
>>> fallback
'unknown-command'
>>> fallback.code
'unknown-command'
>>> int(fallback)
Traceback (most recent call last):
...
ValueError: invalid literal for int() with base 10: 'unknown-command'
>>> fallback = Code.lookup('999')
>>> fallback
'999'
>>> int(fallback)
999
"""
fallback = Code(command.lower(), command.lower())
return numeric.get(command, _by_name.get(command.lower(), fallback))


_codes = itertools.starmap(
Code,
Expand All @@ -33,6 +69,8 @@ def __int__(self):

codes = {v: k for k, v in numeric.items()}

_by_name = {v: v for v in numeric.values()}

generated = [
"dcc_connect",
"dcc_disconnect",
Expand Down

0 comments on commit 90d541b

Please sign in to comment.