blob: 0f0f0ce2b547e7a5708f98a4608996d6ef5dd312 [file] [log] [blame]
Peter Pentchevd00519f2021-11-08 01:17:13 +02001"""Set up the random volume name prefix."""
2
3from __future__ import annotations
4
5import argparse
6import datetime
7import pathlib
8import random
9
10from typing import NamedTuple, Tuple # noqa: H301
11
12from . import defs
13
14DEFAULT_TAG = "osci-1-date"
15
16
17class Config(NamedTuple):
18 """Runtime configuration for the sp_rand_init tool."""
19
20 confdir: pathlib.Path
21 noop: bool
22 prefix_var: str
23 tag: str
24
25 @staticmethod
26 def default() -> Config:
27 """Build a configuration object with the default values."""
28 return Config(
29 confdir=defs.DEFAULT_CONFDIR,
30 noop=False,
31 prefix_var=defs.PREFIX_VAR,
32 tag=DEFAULT_TAG,
33 )
34
35
36def generate_prefix(cfg: Config) -> str:
37 """Generate a random name prefix."""
38 now = datetime.datetime.now()
39 rval = random.randint(1000, 9999)
40 tdate = f"{now.year:04}{now.month:02}{now.day:02}"
41 ttime = f"{now.hour:02}{now.minute:02}"
42 return f"{cfg.tag}-{tdate}-{ttime}-{rval}-"
43
44
45def store_prefix(cfg: Config) -> Tuple[pathlib.Path, str]:
46 """Generate and store the random name prefix into a file."""
47 prefix = generate_prefix(cfg)
48 conffile = cfg.confdir / defs.FILENAME
49 if not cfg.noop:
50 conffile.write_text(f"{cfg.prefix_var}={prefix}\n", encoding="UTF-8")
51 return conffile, prefix
52
53
54def parse_args() -> Config:
55 """Parse the command-line arguments."""
56 parser = argparse.ArgumentParser(prog="sp_rand_init")
57 parser.add_argument(
58 "-d",
59 "--confdir",
60 type=pathlib.Path,
61 default=defs.DEFAULT_CONFDIR,
62 help="The directory to create the configuration file in",
63 )
64 parser.add_argument(
65 "-N",
66 "--noop",
67 action="store_true",
68 help="No-operation mode; display what would have been done",
69 )
70 parser.add_argument(
71 "-p",
72 "--prefix-var",
73 type=str,
74 default=defs.PREFIX_VAR,
75 help="The name of the variable to store into the configuration file",
76 )
77 parser.add_argument(
78 "-t",
79 "--tag",
80 type=str,
81 default=DEFAULT_TAG,
82 help="The tag that the prefix should start with",
83 )
84
85 args = parser.parse_args()
86
Peter Penchev86d47602022-06-24 12:19:53 +030087 return Config(confdir=args.confdir, noop=args.noop, prefix_var=args.prefix_var, tag=args.tag)
Peter Pentchevd00519f2021-11-08 01:17:13 +020088
89
90def main() -> None:
91 """Main program: parse options, generate a prefix, store it."""
92 cfg = parse_args()
93 conffile, prefix = store_prefix(cfg)
94 print(f"{prefix}\n{conffile}")
95
96
97if __name__ == "__main__":
98 main()