Skip to content

Commit ac81700

Browse files
committed
[core] changed console feedback to use rich instead of click
1 parent 6552c81 commit ac81700

File tree

16 files changed

+354
-274
lines changed

16 files changed

+354
-274
lines changed

src/instrumentman/datatransfer/app.py

Lines changed: 91 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,18 @@
22
from logging import getLogger
33

44
from serial import SerialTimeoutException
5-
from rich.progress import Progress, TextColumn
6-
from click_extra import echo
5+
from rich.progress import Progress, TextColumn, BarColumn, TimeElapsedColumn
76
from geocompy.communication import open_serial
87

9-
from ..utils import echo_green, echo_red, echo_yellow
8+
from ..utils import (
9+
print_success,
10+
print_error,
11+
print_warning,
12+
print_plain,
13+
console,
14+
theme_progress_interrupted,
15+
theme_progress_error
16+
)
1017

1118

1219
def main_download(
@@ -30,39 +37,77 @@ def main_download(
3037
started = False
3138
logger.info("Starting data download")
3239
logger.debug("Waiting for first line...")
33-
while True:
34-
try:
35-
data = com.receive_binary()
36-
if not started:
37-
started = True
38-
logger.debug("Received first line...")
39-
40-
if data == eof_bytes and autoclose and not include_eof:
41-
echo_green("Download finished (end-of-file)")
42-
logger.info("Download finished (end-of-file)")
43-
break
40+
with Progress(
41+
TextColumn("[progress.description]{task.description}"),
42+
BarColumn(),
43+
TextColumn("{task.completed} line(s)"),
44+
TimeElapsedColumn(),
45+
console=console
46+
) as progress:
47+
task = progress.add_task("Waiting for data...", total=None)
48+
49+
lines = 0
50+
while True:
51+
try:
52+
data = com.receive_binary()
53+
if not started:
54+
started = True
55+
logger.debug("Received first line...")
56+
progress.update(task, description="Receiving data")
57+
58+
if data == eof_bytes and autoclose and not include_eof:
59+
logger.info("Download finished (end-of-file)")
60+
61+
progress.update(
62+
task,
63+
total=lines,
64+
description="End-Of-File"
65+
)
66+
break
4467

45-
echo(data.decode("ascii", "replace"))
46-
if output is not None:
47-
output.write(data + eol_bytes)
68+
print_plain(data.decode("ascii", "replace"))
69+
lines += 1
70+
progress.update(task, completed=lines)
71+
if output is not None:
72+
output.write(data + eol_bytes)
4873

49-
if data == eof_bytes and autoclose:
50-
echo_green("Download finished (end-of-file)")
51-
logger.info("Download finished (end-of-file)")
74+
if data == eof_bytes and autoclose:
75+
logger.info("Download finished (end-of-file)")
76+
print_success("Download reached end-of-file")
77+
78+
progress.update(
79+
task,
80+
total=lines
81+
)
82+
break
83+
except SerialTimeoutException:
84+
if started and autoclose:
85+
logger.info("Download finished (timeout)")
86+
print_success("Download finished due to timeout")
87+
88+
progress.update(
89+
task,
90+
total=lines
91+
)
92+
break
93+
except KeyboardInterrupt:
94+
logger.info("Download stopped manually")
95+
print_warning("Manually interrupted")
96+
console.push_theme(theme_progress_interrupted)
97+
progress.update(
98+
task,
99+
refresh=True
100+
)
52101
break
53-
except SerialTimeoutException:
54-
if started and autoclose:
55-
echo_green("Download finished (timeout)")
56-
logger.info("Download finished (timeout)")
102+
except Exception as e:
103+
print_error(e)
104+
console.push_theme(theme_progress_error)
105+
progress.update(
106+
task,
107+
refresh=True
108+
)
109+
logger.exception("Download interrupted by error")
57110
break
58-
except KeyboardInterrupt:
59-
echo_yellow("Download stopped manually")
60-
logger.info("Download stopped manually")
61-
break
62-
except Exception as e:
63-
echo_red(f"Download interrupted by error ({e})")
64-
logger.exception("Download interrupted by error")
65-
break
66111

67112

68113
def main_upload(
@@ -86,18 +131,24 @@ def main_upload(
86131
next(file)
87132

88133
with Progress(
89-
*Progress.get_default_columns(),
90-
TextColumn("{task.completed} line(s)")
134+
TextColumn("[progress.description]{task.description}"),
135+
BarColumn(),
136+
TextColumn("{task.completed} line(s)"),
137+
TimeElapsedColumn(),
138+
console=console
91139
) as progress:
92-
for line in progress.track(file, description="Uploading..."):
140+
lines = 0
141+
task = progress.add_task("Uploading", total=None)
142+
for line in file:
143+
lines += 1
93144
com.send(line)
145+
progress.update(task, completed=lines)
146+
147+
progress.update(task, total=lines)
94148

95149
except KeyboardInterrupt:
96-
echo_yellow("Upload cancelled")
150+
print_warning("Upload cancelled")
97151
logger.info("Upload cancelled by user")
98152
except Exception as e:
99-
echo_red(f"Upload interrupted by error ({e})")
153+
print_error(f"Upload interrupted by error ({e})")
100154
logger.exception("Upload interrupted by error")
101-
else:
102-
echo_green("Upload finished")
103-
logger.info("Upload finished")

src/instrumentman/filetransfer/app.py

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,19 +6,18 @@
66
from re import compile, IGNORECASE
77
from logging import getLogger, Logger
88

9-
from click_extra import echo
10-
from rich.console import Console, RenderableType
9+
from rich.console import RenderableType
1110
from rich.text import Text
1211
from rich.tree import Tree
1312
from rich.table import Table
1413
from rich.filesize import decimal
15-
from rich.progress import Progress, TextColumn
14+
from rich.progress import Progress, TextColumn, TimeElapsedColumn
1615
from geocompy.communication import open_serial
1716
from geocompy.geo import GeoCom
1817
from geocompy.geo.gctypes import GeoComCode
1918
from geocompy.geo.gcdata import File, Device
2019

21-
from ..utils import echo_red, echo_green
20+
from ..utils import print_error, console, theme_progress_error
2221

2322

2423
_FILE = {
@@ -203,7 +202,6 @@ def run_listing_tree(
203202
depth: int = 1
204203
) -> None:
205204
filetype = filetype or "unknown"
206-
console = Console(width=120)
207205
logger.info(
208206
f"Starting content listing of '{directory}' from '{dev}' device"
209207
)
@@ -240,6 +238,7 @@ def run_listing_tree(
240238

241239
logger.info("Listing complete")
242240
treeview = build_file_tree(tree)
241+
console.width = 120
243242
console.print(treeview)
244243

245244

@@ -271,7 +270,7 @@ def run_download(
271270
_FILE[filetype]
272271
)
273272
if resp_setup.error != GeoComCode.OK or resp_setup.params is None:
274-
echo_red("Could not set up file download")
273+
print_error("Could not set up file download")
275274
logger.critical(
276275
f"Could not set up file download ({resp_setup})"
277276
)
@@ -280,21 +279,25 @@ def run_download(
280279
block_count = resp_setup.params
281280
logger.info(f"Expected number of chunks: {block_count:d}")
282281

283-
with Progress() as progress:
282+
with Progress(
283+
*Progress.get_default_columns(),
284+
TimeElapsedColumn(),
285+
console=console
286+
) as progress:
284287
for i in progress.track(range(block_count), description="Downloading"):
285288
resp_pull = download(i + 1)
286289
if resp_pull.error != GeoComCode.OK or resp_pull.params is None:
290+
console.push_theme(theme_progress_error)
291+
print_error("An error occured during download")
287292
progress.stop()
288-
echo_red("An error occured during download")
289293
logger.critical(
290294
f"An error occured during download ({resp_pull})"
291295
)
292296
return
293297

294-
echo(bytes.fromhex(resp_pull.params), file, False)
298+
file.write(bytes.fromhex(resp_pull.params))
295299

296300
logger.info("Download complete")
297-
echo_green("Download complete")
298301

299302

300303
def main_download(

src/instrumentman/inclination/app.py

Lines changed: 14 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,13 @@
77
from rich.console import Console
88
from rich.progress import track
99
from rich.table import Table, Column
10-
from click_extra import echo
1110
from geocompy.data import Angle, Coordinate
1211
from geocompy.geo import GeoCom
1312
from geocompy.geo.gctypes import GeoComCode
1413
from geocompy.communication import open_serial
1514

1615
from ..calculations import adjust_uniform_single
17-
from ..utils import echo_green
16+
from ..utils import print_success, console
1817

1918

2019
_LINE = compile(r"^\d+(?:\.\d+)?(?:,\-?\d+\.\d+){2}$")
@@ -137,15 +136,15 @@ def main_merge(
137136
inputs: list[TextIOWrapper],
138137
output: TextIOWrapper
139138
) -> None:
140-
echo("hz_deg,cross_sec,length_sec", output)
139+
output.write("hz_deg,cross_sec,length_sec\n")
141140
for item in inputs:
142141
for line in item:
143142
if not _LINE.match(line.strip()):
144143
continue
145144

146-
echo(line, output, False)
145+
output.write(line)
147146

148-
echo_green(f"Merged measurements from {len(inputs)} files.")
147+
print_success(f"Merged measurements from {len(inputs)} files.")
149148

150149

151150
def main_calc(
@@ -186,24 +185,20 @@ def main_calc(
186185
direction, inc, _ = Coordinate(x, y, z).to_polar()
187186

188187
if output is None:
189-
echo(f"""Axis aligned:
190-
inclination X: {inc_x:.1f}" +/- {inc_x_dev:.1f}"
191-
inclination Y: {inc_y:.1f}" +/- {inc_y_dev:.1f}"
188+
console.print(
189+
f"""Axis aligned:
190+
inclination X: {inc_x:.1f}" ± {inc_x_dev:.1f}"
191+
inclination Y: {inc_y:.1f}" ± {inc_y_dev:.1f}"
192192
Polar:
193193
direction: {direction.asunit('deg'):.4f}°
194194
inclination: {inc.asunit('deg') * 3600:.1f}\""""
195-
)
195+
)
196196
return
197197

198-
echo(
199-
"inc_x_sec,inc_x_dev_sec,inc_y_sec,inc_y_dev_sec,dir_deg,inc_sec",
200-
output
198+
output.write(
199+
"inc_x_sec,inc_x_dev_sec,inc_y_sec,inc_y_dev_sec,dir_deg,inc_sec\n"
201200
)
202-
203-
echo(
204-
(
205-
f"{inc_x:.1f},{inc_x_dev:.1f},{inc_y:.1f},{inc_y_dev:.1f},"
206-
f"{direction.asunit('deg'):.4f},{inc.asunit('deg') * 3600:.1f}"
207-
),
208-
output
201+
output.write(
202+
f"{inc_x:.1f},{inc_x_dev:.1f},{inc_y:.1f},{inc_y_dev:.1f},"
203+
f"{direction.asunit('deg'):.4f},{inc.asunit('deg') * 3600:.1f}\n"
209204
)

src/instrumentman/jobs/app.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
from geocompy.geo import GeoCom
77
from geocompy.geo.gctypes import GeoComCode
88

9-
from ..utils import echo_red, echo_yellow
9+
from ..utils import print_error, print_warning, console
1010

1111

1212
def run_listing(
@@ -16,21 +16,21 @@ def run_listing(
1616
logger.info("Starting job listing")
1717
resp_setup = tps.csv.setup_listing()
1818
if resp_setup.error != GeoComCode.OK:
19-
echo_red("Could not set up listing")
19+
print_error("Could not set up listing")
2020
logger.critical(
2121
f"Could not set up listing ({resp_setup})"
2222
)
2323
return
2424

2525
resp_list = tps.csv.list()
2626
if resp_list.error != GeoComCode.OK or resp_list.params is None:
27-
echo_red("Could not start listing")
27+
print_error("Could not start listing")
2828
logger.critical(f"Could not start listing ({resp_list})")
2929
return
3030

3131
job, file, _, _, _ = resp_list.params
3232
if job == "" or file == "":
33-
echo_yellow("No jobs were found")
33+
print_warning("No jobs were found")
3434
logger.info("No jobs were found")
3535
return
3636

@@ -41,7 +41,7 @@ def run_listing(
4141
col_file
4242
)
4343
table.add_row(job, file)
44-
with Live(table):
44+
with Live(table, console=console):
4545
while True:
4646
resp_list = tps.csv.list()
4747
if resp_list.error != GeoComCode.OK or resp_list.params is None:

src/instrumentman/morse/app.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@
88
from geocompy.communication import open_serial
99

1010
from ..utils import (
11-
echo_red,
12-
echo_green
11+
print_error,
12+
console
1313
)
1414

1515

@@ -98,7 +98,8 @@ def relay_message(
9898
with Progress(
9999
TextColumn("[progress.description]{task.description}"),
100100
BarColumn(),
101-
TaskProgressColumn()
101+
TaskProgressColumn(),
102+
console=console
102103
) as progress:
103104
for char in progress.track(encoded, description="Relaying message"):
104105
match char:
@@ -121,7 +122,6 @@ def relay_message(
121122
f"Invalid morse stream character: '{char}'"
122123
)
123124

124-
echo_green("Message complete")
125125
logger.info("Message complete")
126126

127127

@@ -142,7 +142,7 @@ def main(
142142
try:
143143
message.casefold().encode("ascii")
144144
except UnicodeEncodeError:
145-
echo_red("The message contains non-ASCII characters.")
145+
print_error("The message contains non-ASCII characters.")
146146
logger.critical("Message contains non-ASCII characters.")
147147
exit(1)
148148

0 commit comments

Comments
 (0)