-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
222 lines (163 loc) · 5.13 KB
/
Copy pathapp.py
File metadata and controls
222 lines (163 loc) · 5.13 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
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
"""Main application for Python Data Shell."""
import argparse
import copy
from pathlib import Path
from storage import DEFAULT_PATH, FIELDS, load, save
from ui import console, banner, dashboard, show_records
from validators import required, iso_date, number, grade_result
class Cancelled(Exception):
"""Raised when the user cancels an entry."""
def ask(label, validator=required):
"""Prompt again only for the field that failed validation."""
while True:
value = console.input(
f"[cyan]{label}[/cyan] > "
)
if value.strip().casefold() == "/cancel":
raise Cancelled
try:
return validator(value)
except ValueError as error:
console.print(
str(error),
style="red",
markup=False,
)
def study_mode(value):
value = required(value).casefold()
if value not in ("full-time", "part-time"):
raise ValueError(
"Choose full-time or part-time."
)
return value
def collect(key):
"""Collect the fields for a new record."""
console.rule(f"NEW {key.upper()}")
row = {}
for field in FIELDS[key]:
# These fields are calculated automatically.
if field in ("Average", "Result"):
continue
validator = required
if field == "Study mode":
validator = study_mode
elif field == "Birth date":
validator = lambda value: iso_date(
value,
past=True,
)
elif field == "Submission date":
validator = iso_date
elif field == "Tuition fees":
validator = lambda value: str(number(value))
elif field in ("Written mark", "Oral mark"):
validator = lambda value: str(
number(value, 0, 100)
)
row[field] = ask(field, validator)
if key == "assignments":
average, result = grade_result(
row["Written mark"],
row["Oral mark"],
)
row["Average"] = average
row["Result"] = result
return row
def run(path):
banner()
try:
data = load(path)
except (OSError, ValueError) as error:
console.print(
f"Cannot load data: {error}",
style="red",
markup=False,
)
console.print(
"Existing file preserved. "
"Restore a valid backup before retrying."
)
return 1
while True:
dashboard(data)
choice = console.input(
"[bold cyan]data-shell[/bold cyan] > "
).strip().casefold()
if choice in ("0", "x", "exit"):
console.print(
"Goodbye! Completed entries are saved.",
style="green",
)
return 0
try:
if choice in ("1", "2", "3", "4"):
key = tuple(FIELDS)[int(choice) - 1]
row = collect(key)
updated = copy.deepcopy(data)
updated[key].append(row)
# Save to disk before updating the in-memory data.
save(updated, path)
# Update the in-memory data only after a successful save.
data = updated
console.print(
"Record saved.",
style="bold green",
)
show_records(key, [row])
elif choice in ("5", "6"):
query = (
ask("Search").casefold()
if choice == "6"
else ""
)
for key in FIELDS:
rows = [
row
for row in data[key]
if not query
or any(
query in value.casefold()
for value in row.values()
)
]
show_records(key, rows)
else:
console.print(
"Choose 0 through 6.",
style="yellow",
)
except Cancelled:
console.print(
"Entry cancelled.",
style="yellow",
)
except OSError as error:
console.print(
f"Entry NOT saved: {error}",
style="red",
markup=False,
)
console.print(
"Fix file permissions or disk space, "
"then enter the record again."
)
def main():
parser = argparse.ArgumentParser(
description="Python Data Shell - Academy Manager"
)
parser.add_argument(
"--data-file",
type=Path,
default=DEFAULT_PATH,
)
args = parser.parse_args()
try:
return run(args.data_file)
except (KeyboardInterrupt, EOFError):
console.print(
"\nGoodbye. Any unfinished entry was discarded.",
style="yellow",
)
return 0
if __name__ == "__main__":
raise SystemExit(main())