Skip to content

Commit 6bb3beb

Browse files
committed
feat: Add ModeOptionalAction for handling optional command modes in argparse
1 parent 60e3fdf commit 6bb3beb

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

Jiyu_udp_attack/__main__.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,60 @@
1212
import argparse
1313
import binascii
1414

15+
from typing import Any, Sequence, cast
16+
1517
from sender import broadcast_packet
1618
from packet import pkg_message, pkg_shutdown, pkg_rename, pkg_website, pkg_execute
1719

1820

21+
class ModeOptionalAction(argparse.Action):
22+
"""
23+
Custom action for handling optional arguments in argparse.
24+
This action allows the user to specify a mode (e.g., --max or --min) for the program execution.
25+
"""
26+
27+
def __init__(self, option_strings: Sequence[str], dest: str, modes: Sequence[str], **kwargs: Any):
28+
self.modes = list(modes)
29+
30+
if any("-" in mode for mode in self.modes):
31+
raise ValueError("Modes cannot contain '-' characters. Please use a different character.")
32+
33+
_option_strings = []
34+
for option in option_strings:
35+
_option_strings.append(option)
36+
37+
for mode in self.modes:
38+
if option.startswith("--"):
39+
if option.startswith(f"--{mode}-"):
40+
raise ValueError(
41+
f"Option '{option}' cannot start with '--{mode}-'. "
42+
"Please use a different prefix for modes."
43+
)
44+
_option_strings.append(f"--{mode}-{option[2:]}")
45+
46+
return super().__init__(_option_strings, dest, **kwargs)
47+
48+
def __call__(
49+
self,
50+
parser: argparse.ArgumentParser,
51+
namespace: argparse.Namespace,
52+
values: Any,
53+
option_string: str | None = None,
54+
):
55+
if option_string in self.option_strings:
56+
option_string = cast(str, option_string)
57+
if option_string.startswith("--"):
58+
mode = option_string.split("-")[2]
59+
if mode not in self.modes:
60+
mode = None
61+
else:
62+
mode = None
63+
setattr(namespace, self.dest, (mode, values))
64+
65+
def format_usage(self) -> str:
66+
return " | ".join(self.option_strings)
67+
68+
1969
if __name__ == "__main__":
2070
parser = argparse.ArgumentParser(
2171
description="Jiyu Attack Script",

0 commit comments

Comments
 (0)