Skip to content

Commit 7731fe2

Browse files
committed
Improve cli (only allow unknown arguments after --)
1 parent 0e1593d commit 7731fe2

File tree

2 files changed

+29
-9
lines changed

2 files changed

+29
-9
lines changed

adit_radis_shared/cli/setup.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import argparse
2+
import sys
3+
4+
import argcomplete
5+
6+
7+
def setup_root_parser(root_parser: argparse.ArgumentParser):
8+
args = sys.argv[1:]
9+
if "--" in args:
10+
idx = args.index("--")
11+
pre_args = args[:idx]
12+
post_args = args[idx + 1 :]
13+
else:
14+
pre_args = args
15+
post_args = []
16+
17+
argcomplete.autocomplete(root_parser)
18+
args, unknown_args = root_parser.parse_known_args(pre_args)
19+
20+
if unknown_args:
21+
root_parser.error(f"Unknown arguments before '--': {unknown_args}")
22+
23+
if not args.command:
24+
root_parser.print_help()
25+
sys.exit(1)
26+
27+
args.func(**vars(args), extra_args=post_args)

cli.py

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,9 @@
55
import shutil
66
import sys
77

8-
import argcomplete
9-
108
from adit_radis_shared.cli import helper as cli_helper
119
from adit_radis_shared.cli import parsers
10+
from adit_radis_shared.cli.setup import setup_root_parser
1211

1312

1413
def copy_statics(**kwargs):
@@ -69,10 +68,4 @@ def copy_file(file: str, filename: str | None = None):
6968
parser = subparsers.add_parser("copy_statics", help="Copy statics for the project")
7069
parser.set_defaults(func=copy_statics)
7170

72-
argcomplete.autocomplete(root_parser)
73-
args, extra_args = root_parser.parse_known_args()
74-
if not args.command:
75-
root_parser.print_help()
76-
sys.exit(1)
77-
78-
args.func(**vars(args), extra_args=extra_args)
71+
setup_root_parser(root_parser)

0 commit comments

Comments
 (0)