Skip to content

Commit 0046fdf

Browse files
committed
Fixed several typing issues and hopefully some more windows bugs
1 parent afc42ff commit 0046fdf

File tree

6 files changed

+90
-57
lines changed

6 files changed

+90
-57
lines changed

examples.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ def do_something(bar):
6161
# Sleep up to 0.1 seconds
6262
time.sleep(random.random() * 0.1)
6363

64-
with (progressbar.MultiBar() as multibar):
64+
with progressbar.MultiBar() as multibar:
6565
bar_labels = []
6666
for i in range(BARS):
6767
# Get a progressbar

progressbar/__main__.py

Lines changed: 36 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@
44
import contextlib
55
import pathlib
66
import sys
7-
from typing import BinaryIO
7+
import typing
8+
from pathlib import Path
9+
from typing import BinaryIO, TextIO
810

911
import progressbar
1012

@@ -52,7 +54,7 @@ def size_to_bytes(size_str: str) -> int:
5254
size_str = size_str[:-1]
5355

5456
# Convert the size_str to an integer and apply the exponent
55-
return int(size_str) * (1024 ** exponent)
57+
return int(size_str) * (1024**exponent)
5658

5759

5860
def create_argument_parser() -> argparse.ArgumentParser:
@@ -63,7 +65,7 @@ def create_argument_parser() -> argparse.ArgumentParser:
6365
parser = argparse.ArgumentParser(
6466
description='''
6567
Monitor the progress of data through a pipe.
66-
68+
6769
Note that this is a Python implementation of the original `pv` command
6870
that is functional but not yet feature complete.
6971
'''
@@ -270,28 +272,26 @@ def create_argument_parser() -> argparse.ArgumentParser:
270272
def main(argv: list[str] | None = None): # noqa: C901
271273
'''
272274
Main function for the `progressbar` command.
273-
'''
274-
parser = create_argument_parser()
275-
args = parser.parse_args(argv)
276275
277-
binary_mode = '' if args.line_mode else 'b'
276+
Args:
277+
argv (list[str] | None): Command-line arguments passed to the script.
278+
279+
Returns:
280+
None
281+
'''
282+
parser: argparse.ArgumentParser = create_argument_parser()
283+
args: argparse.Namespace = parser.parse_args(argv)
278284

279285
with contextlib.ExitStack() as stack:
280-
if args.output and args.output != '-':
281-
output_stream = stack.enter_context(
282-
open(args.output, 'w' + binary_mode)
283-
)
284-
else:
285-
if args.line_mode:
286-
output_stream = sys.stdout
287-
else:
288-
output_stream = sys.stdout.buffer
286+
output_stream: typing.IO[typing.Any] = _get_output_stream(
287+
args.output, args.line_mode, stack
288+
)
289289

290-
input_paths = []
291-
total_size = 0
292-
filesize_available = True
290+
input_paths: list[BinaryIO | TextIO | Path] = []
291+
total_size: int = 0
292+
filesize_available: bool = True
293293
for filename in args.input:
294-
input_path: BinaryIO | pathlib.Path
294+
input_path: typing.IO[typing.Any] | pathlib.Path
295295
if filename == '-':
296296
if args.line_mode:
297297
input_path = sys.stdin
@@ -356,12 +356,13 @@ def main(argv: list[str] | None = None): # noqa: C901
356356
for input_path in input_paths:
357357
if isinstance(input_path, pathlib.Path):
358358
input_stream = stack.enter_context(
359-
input_path.open('r' + binary_mode)
359+
input_path.open('r' if args.line_mode else 'rb')
360360
)
361361
else:
362362
input_stream = input_path
363363

364364
while True:
365+
data: str | bytes
365366
if args.line_mode:
366367
data = input_stream.readline(buffer_size)
367368
else:
@@ -377,5 +378,19 @@ def main(argv: list[str] | None = None): # noqa: C901
377378
bar.finish(dirty=True)
378379

379380

381+
def _get_output_stream(
382+
output: str | None,
383+
line_mode: bool,
384+
stack: contextlib.ExitStack,
385+
) -> typing.IO[typing.Any]:
386+
if output and output != '-':
387+
mode = 'w' if line_mode else 'wb'
388+
return stack.enter_context(open(output, mode)) # noqa: SIM115
389+
elif line_mode:
390+
return sys.stdout
391+
else:
392+
return sys.stdout.buffer
393+
394+
380395
if __name__ == '__main__':
381396
main()

progressbar/bar.py

Lines changed: 44 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -162,13 +162,13 @@ class DefaultFdMixin(ProgressBarMixinBase):
162162
#: Set the terminal to be ANSI compatible. If a terminal is ANSI
163163
#: compatible we will automatically enable `colors` and disable
164164
#: `line_breaks`.
165-
is_ansi_terminal: bool = False
165+
is_ansi_terminal: bool | None = False
166166
#: Whether the file descriptor is a terminal or not. This is used to
167167
#: determine whether to use ANSI escape codes or not.
168-
is_terminal: bool
168+
is_terminal: bool | None
169169
#: Whether to print line breaks. This is useful for logging the
170170
#: progressbar. When disabled the current line is overwritten.
171-
line_breaks: bool = True
171+
line_breaks: bool | None = True
172172
#: Specify the type and number of colors to support. Defaults to auto
173173
#: detection based on the file descriptor type (i.e. interactive terminal)
174174
#: environment variables such as `COLORTERM` and `TERM`. Color output can
@@ -179,9 +179,7 @@ class DefaultFdMixin(ProgressBarMixinBase):
179179
#: For true (24 bit/16M) color support you can use `COLORTERM=truecolor`.
180180
#: For 256 color support you can use `TERM=xterm-256color`.
181181
#: For 16 colorsupport you can use `TERM=xterm`.
182-
enable_colors: progressbar.env.ColorSupport | bool | None = (
183-
progressbar.env.COLOR_SUPPORT
184-
)
182+
enable_colors: progressbar.env.ColorSupport = progressbar.env.COLOR_SUPPORT
185183

186184
def __init__(
187185
self,
@@ -200,7 +198,7 @@ def __init__(
200198
fd = self._apply_line_offset(fd, line_offset)
201199
self.fd = fd
202200
self.is_ansi_terminal = progressbar.env.is_ansi_terminal(fd)
203-
self.is_terminal = self._determine_is_terminal(fd, is_terminal)
201+
self.is_terminal = progressbar.env.is_terminal(fd, is_terminal)
204202
self.line_breaks = self._determine_line_breaks(line_breaks)
205203
self.enable_colors = self._determine_enable_colors(enable_colors)
206204

@@ -219,29 +217,47 @@ def _apply_line_offset(
219217
else:
220218
return fd
221219

222-
def _determine_is_terminal(
223-
self,
224-
fd: base.TextIO,
225-
is_terminal: bool | None,
226-
) -> bool:
227-
if is_terminal is not None:
228-
return progressbar.env.is_terminal(fd, is_terminal)
229-
else:
230-
return progressbar.env.is_ansi_terminal(fd)
231-
232-
def _determine_line_breaks(self, line_breaks: bool | None) -> bool:
220+
def _determine_line_breaks(self, line_breaks: bool | None) -> bool | None:
233221
if line_breaks is None:
234222
return progressbar.env.env_flag(
235223
'PROGRESSBAR_LINE_BREAKS',
236224
not self.is_terminal,
237225
)
238226
else:
239-
return bool(line_breaks)
227+
return line_breaks
240228

241229
def _determine_enable_colors(
242230
self,
243231
enable_colors: progressbar.env.ColorSupport | None,
244232
) -> progressbar.env.ColorSupport:
233+
'''
234+
Determines the color support for the progress bar.
235+
236+
This method checks the `enable_colors` parameter and the environment
237+
variables `PROGRESSBAR_ENABLE_COLORS` and `FORCE_COLOR` to determine
238+
the color support.
239+
240+
If `enable_colors` is:
241+
- `None`, it checks the environment variables and the terminal
242+
compatibility to ANSI.
243+
- `True`, it sets the color support to XTERM_256.
244+
- `False`, it sets the color support to NONE.
245+
- For different values that are not instances of
246+
`progressbar.env.ColorSupport`, it raises a ValueError.
247+
248+
Args:
249+
enable_colors (progressbar.env.ColorSupport | None): The color
250+
support setting from the user. It can be None, True, False,
251+
or an instance of `progressbar.env.ColorSupport`.
252+
253+
Returns:
254+
progressbar.env.ColorSupport: The determined color support.
255+
256+
Raises:
257+
ValueError: If `enable_colors` is not None, True, False, or an
258+
instance of `progressbar.env.ColorSupport`.
259+
'''
260+
color_support = progressbar.env.ColorSupport.NONE
245261
if enable_colors is None:
246262
colors = (
247263
progressbar.env.env_flag('PROGRESSBAR_ENABLE_COLORS'),
@@ -252,21 +268,23 @@ def _determine_enable_colors(
252268
for color_enabled in colors:
253269
if color_enabled is not None:
254270
if color_enabled:
255-
enable = progressbar.env.COLOR_SUPPORT
271+
color_support = progressbar.env.COLOR_SUPPORT
256272
else:
257-
enable = progressbar.env.ColorSupport.NONE
273+
color_support = progressbar.env.ColorSupport.NONE
258274
break
259275
else:
260-
enable = False
276+
color_support = progressbar.env.ColorSupport.NONE
261277

262278
elif enable_colors is True:
263-
enable = progressbar.env.ColorSupport.XTERM_256
279+
color_support = progressbar.env.ColorSupport.XTERM_256
264280
elif enable_colors is False:
265-
enable = progressbar.env.ColorSupport.NONE
266-
elif not isinstance(enable_colors, progressbar.env.ColorSupport):
281+
color_support = progressbar.env.ColorSupport.NONE
282+
elif isinstance(enable_colors, progressbar.env.ColorSupport):
283+
color_support = enable_colors
284+
else:
267285
raise ValueError(f'Invalid color support value: {enable_colors}')
268286

269-
return enable
287+
return color_support
270288

271289
def print(self, *args: types.Any, **kwargs: types.Any) -> None:
272290
print(*args, file=self.fd, **kwargs)

progressbar/env.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ def from_env(cls):
8181
):
8282
return cls.XTERM_TRUECOLOR
8383
else:
84-
return cls.WINDOWS
84+
return cls.WINDOWS # pragma: no cover
8585

8686
support = cls.NONE
8787
for variable in variables:
@@ -142,7 +142,7 @@ def is_ansi_terminal(
142142
return is_terminal
143143

144144

145-
def is_terminal(fd: base.IO, is_terminal: bool | None = None) -> bool:
145+
def is_terminal(fd: base.IO, is_terminal: bool | None = None) -> bool | None:
146146
if is_terminal is None:
147147
# Full ansi support encompasses what we expect from a terminal
148148
is_terminal = is_ansi_terminal(fd) or None
@@ -159,7 +159,7 @@ def is_terminal(fd: base.IO, is_terminal: bool | None = None) -> bool:
159159
except Exception:
160160
is_terminal = False
161161

162-
return bool(is_terminal)
162+
return is_terminal
163163

164164

165165
# Enable Windows full color mode if possible

progressbar/terminal/os_specific/__init__.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,13 @@
1111
else:
1212
from .posix import getch as _getch
1313

14-
def _reset_console_mode():
14+
def _reset_console_mode() -> None:
1515
pass
1616

17-
def _set_console_mode():
18-
pass
17+
def _set_console_mode() -> bool:
18+
return False
1919

20-
def _get_console_mode():
20+
def _get_console_mode() -> int:
2121
return 0
2222

2323

progressbar/terminal/os_specific/windows.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ class _Event(ctypes.Union):
120120
_fields_ = (('EventType', _WORD), ('Event', _Event))
121121

122122

123-
def reset_console_mode():
123+
def reset_console_mode() -> None:
124124
_SetConsoleMode(_HANDLE(_h_console_input), _DWORD(_input_mode.value))
125125
_SetConsoleMode(_HANDLE(_h_console_output), _DWORD(_output_mode.value))
126126

@@ -144,7 +144,7 @@ def get_console_mode() -> int:
144144
return _input_mode.value
145145

146146

147-
def set_text_color(color):
147+
def set_text_color(color) -> None:
148148
_kernel32.SetConsoleTextAttribute(_h_console_output, color)
149149

150150

0 commit comments

Comments
 (0)