forked from realpython/materials
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
51 lines (34 loc) · 1.25 KB
/
Copy pathcli.py
File metadata and controls
51 lines (34 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
"""
Command line arguments parsing.
"""
import argparse
import pathlib
from dataclasses import dataclass
from typing import Optional
@dataclass
class CommandLineArguments:
"""Parsed command line arguments."""
bitmap: pathlib.Path
encode: Optional[pathlib.Path]
decode: bool
erase: bool
def parse_args() -> CommandLineArguments:
"""Parse command line arguments."""
parser = argparse.ArgumentParser()
parser.add_argument("bitmap", type=path_factory)
modes = parser.add_mutually_exclusive_group()
modes.add_argument("--encode", "-e", metavar="file", type=path_factory)
modes.add_argument("--decode", "-d", action="store_true")
modes.add_argument("--erase", "-x", action="store_true")
args = parser.parse_args()
if not any([args.encode, args.decode, args.erase]):
parser.error("Mode required: --encode file | --decode | --erase")
return CommandLineArguments(**vars(args))
def path_factory(argument: str) -> pathlib.Path:
"""Convert the argument to a path instance."""
path = pathlib.Path(argument)
if not path.exists():
raise argparse.ArgumentTypeError("file doesn't exist")
if not path.is_file():
raise argparse.ArgumentTypeError("must be a file")
return path