Skip to content

Commit

Permalink
Refactor FlagConverter to handle positional flags correctly
Browse files Browse the repository at this point in the history
  • Loading branch information
Vioshim committed Apr 26, 2024
1 parent 891db7e commit 05f7609
Showing 1 changed file with 17 additions and 33 deletions.
50 changes: 17 additions & 33 deletions discord/ext/commands/flags.py
Expand Up @@ -523,32 +523,10 @@ def parse_flags(cls, argument: str, *, ignore_extra: bool = True) -> Dict[str, L
result: Dict[str, List[str]] = {}
flags = cls.__commands_flags__
aliases = cls.__commands_flag_aliases__
positional_flag = cls.__commands_flag_positional__
last_position = 0
last_flag: Optional[Flag] = None
last_flag = cls.__commands_flag_positional__

case_insensitive = cls.__commands_flag_case_insensitive__

if positional_flag is not None:
match = cls.__commands_flag_regex__.search(argument)
if match is not None:
begin, end = match.span(0)
value = argument[:begin].strip()
last_position = begin
else:
value = argument.strip()
last_position = len(argument)

if value:
name = positional_flag.name.casefold() if case_insensitive else positional_flag.name

try:
values = result[name]
except KeyError:
result[name] = [value]
else:
values.append(value)

for match in cls.__commands_flag_regex__.finditer(argument):
begin, end = match.span(0)
key = match.group('flag')
Expand All @@ -559,19 +537,25 @@ def parse_flags(cls, argument: str, *, ignore_extra: bool = True) -> Dict[str, L
key = aliases[key]

flag = flags.get(key)
if last_position and last_flag is not None:
value = argument[last_position : begin - 1].lstrip()
if not value:

if last_flag is not None and (last_position or last_flag.positional):
if last_position:
value = argument[last_position : begin - 1].lstrip()
else:
value = argument[last_position : begin].strip()

if not value and last_position:
raise MissingFlagArgument(last_flag)

name = last_flag.name.casefold() if case_insensitive else last_flag.name
if last_position or value:
name = last_flag.name.casefold() if case_insensitive else last_flag.name

try:
values = result[name]
except KeyError:
result[name] = [value]
else:
values.append(value)
try:
values = result[name]
except KeyError:
result[name] = [value]
else:
values.append(value)

last_position = end
last_flag = flag
Expand Down

0 comments on commit 05f7609

Please sign in to comment.