-
Notifications
You must be signed in to change notification settings - Fork 1
/
config.py
131 lines (110 loc) · 4.01 KB
/
config.py
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# config.py
#
# This module holds config related functions. This includes the EntryInfo data
# class too.
from collections import namedtuple
from dataclasses import dataclass
from utils import to_form_url
@dataclass
class EntryInfo:
required: bool
prompt: bool
type: str
key: str
title: str
value: str
# See README's Config section for more info
TYPES = {
"words": ["w", "word", "text"],
"choice": ["m", "mc", "multiple choice"],
"checkboxes": ["c", "checkbox"],
"date": ["d"],
"time": ["t"],
"extra": ["x", "xD", "extra data"],
}
@classmethod
def from_string(cls, string):
"""
Return info on a config file line.
Parse a string of the format `[*] [!] type - key ; title = value`.
Return a dataclass (simple object) with the config info.
A string "*!type-key;title=value" would give `EntryInfo(required=True,
prompt=True, type="type", key="key", title="title", value="value")`.
Examples of config lines:
w-1000;Question=Default
! time - 1001 ; Time = current
*multiple choice - 1001 ; Class =
checkbox-1002; Languages = Python, Java, C++
*! extra-emailAddress; Email Address =
"""
string = string.strip()
if not string:
raise ValueError("Empty entry")
required = (string[0] == "*")
string = string.removeprefix("*").strip()
if not string:
raise ValueError("Missing type")
prompt = (string[0] == "!")
string = string.removeprefix("!").strip()
type, split, string = map(str.strip, string.partition("-"))
for name, aliases in cls.TYPES.items():
if type == name:
break
elif type in aliases:
type = name
break
else:
raise ValueError(f"Type not valid: {type}")
if not split:
raise ValueError("Missing type-key split '-'")
key, split, string = map(str.strip, string.partition(";"))
if not key:
raise ValueError("Missing key")
if not split:
raise ValueError("Missing key-title split ';'")
title, split, value = map(str.strip, string.partition("="))
if not title:
title = key # Title defaults to the key if absent.
if not split:
raise ValueError("Missing title-value split '='")
return cls(required, prompt, type, key, title, value)
def __str__(self):
return (
f"{'*'*self.required}{'!'*self.prompt}{self.type}"
f"-{self.key};{self.title}={self.value}"
)
ConfigInfo = namedtuple("ConfigInfo", "url entries")
def open_config(file):
"""
Open config file and return the URL and entries.
"""
if isinstance(file, str):
file = open(file)
with file:
url = to_form_url(file.readline())
entries = []
for line in file:
line = line.strip()
if not line:
continue
if line.startswith("#"):
continue
entries.append(EntryInfo.from_string(line))
return ConfigInfo(url, entries)
# - Tests
def test_entry_from_string():
# TODO: Add tests for ValueError (maybe use pytest)
a = EntryInfo(True, True, "words", "key", "title", "value")
assert EntryInfo.from_string(" *!words-key;title=value ") == a
assert EntryInfo.from_string(" * ! words - key ; title = value ") == a
b = EntryInfo(False, False, "words", "key", "key", "")
assert EntryInfo.from_string("words-key;=") == b
assert EntryInfo.from_string("w-key;=") == b
assert EntryInfo.from_string("word-key;=") == b
assert EntryInfo.from_string("text-key;=") == b
def test_entry_str():
entry = EntryInfo(True, True, "words", "key", "title", "value")
assert EntryInfo.from_string(str(entry)) == entry
line = "*!words-key;title=value"
assert str(entry) == line
assert str(EntryInfo.from_string(line)) == line