File size: 10,957 Bytes
ef0e153 |
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 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 |
from __future__ import annotations
import argparse
import contextlib
import pathlib
import sys
import typing
from pathlib import Path
from typing import IO, BinaryIO, TextIO
import progressbar
def size_to_bytes(size_str: str) -> int:
"""
Convert a size string with suffixes 'k', 'm', etc., to bytes.
Note: This function also supports '@' as a prefix to a file path to get the
file size.
>>> size_to_bytes('1024k')
1048576
>>> size_to_bytes('1024m')
1073741824
>>> size_to_bytes('1024g')
1099511627776
>>> size_to_bytes('1024')
1024
>>> size_to_bytes('1024p')
1125899906842624
"""
# Define conversion rates
suffix_exponent = {
'k': 1,
'm': 2,
'g': 3,
't': 4,
'p': 5,
}
# Initialize the default exponent to 0 (for bytes)
exponent = 0
# Check if the size starts with '@' (for file sizes, not handled here)
if size_str.startswith('@'):
return pathlib.Path(size_str[1:]).stat().st_size
# Check if the last character is a known suffix and adjust the multiplier
if size_str[-1].lower() in suffix_exponent:
# Update exponent based on the suffix
exponent = suffix_exponent[size_str[-1].lower()]
# Remove the suffix from the size_str
size_str = size_str[:-1]
# Convert the size_str to an integer and apply the exponent
return int(size_str) * (1024**exponent)
def create_argument_parser() -> argparse.ArgumentParser:
"""
Create the argument parser for the `progressbar` command.
"""
parser = argparse.ArgumentParser(
description="""
Monitor the progress of data through a pipe.
Note that this is a Python implementation of the original `pv` command
that is functional but not yet feature complete.
"""
)
# Display switches
parser.add_argument(
'-p',
'--progress',
action='store_true',
help='Turn the progress bar on.',
)
parser.add_argument(
'-t', '--timer', action='store_true', help='Turn the timer on.'
)
parser.add_argument(
'-e', '--eta', action='store_true', help='Turn the ETA timer on.'
)
parser.add_argument(
'-I',
'--fineta',
action='store_true',
help='Display the ETA as local time of arrival.',
)
parser.add_argument(
'-r', '--rate', action='store_true', help='Turn the rate counter on.'
)
parser.add_argument(
'-a',
'--average-rate',
action='store_true',
help='Turn the average rate counter on.',
)
parser.add_argument(
'-b',
'--bytes',
action='store_true',
help='Turn the total byte counter on.',
)
parser.add_argument(
'-8',
'--bits',
action='store_true',
help='Display total bits instead of bytes.',
)
parser.add_argument(
'-T',
'--buffer-percent',
action='store_true',
help='Turn on the transfer buffer percentage display.',
)
parser.add_argument(
'-A',
'--last-written',
type=int,
help='Show the last NUM bytes written.',
)
parser.add_argument(
'-F',
'--format',
type=str,
help='Use the format string FORMAT for output format.',
)
parser.add_argument(
'-n', '--numeric', action='store_true', help='Numeric output.'
)
parser.add_argument(
'-q',
'--quiet',
action='store_true',
help='No output.',
)
# Output modifiers
parser.add_argument(
'-W',
'--wait',
action='store_true',
help='Wait until the first byte has been transferred.',
)
parser.add_argument('-D', '--delay-start', type=float, help='Delay start.')
parser.add_argument(
'-s', '--size', type=str, help='Assume total data size is SIZE.'
)
parser.add_argument(
'-l',
'--line-mode',
action='store_true',
help='Count lines instead of bytes.',
)
parser.add_argument(
'-0',
'--null',
action='store_true',
help='Count lines terminated with a zero byte.',
)
parser.add_argument(
'-i', '--interval', type=float, help='Interval between updates.'
)
parser.add_argument(
'-m',
'--average-rate-window',
type=int,
help='Window for average rate calculation.',
)
parser.add_argument(
'-w',
'--width',
type=int,
help='Assume terminal is WIDTH characters wide.',
)
parser.add_argument(
'-H', '--height', type=int, help='Assume terminal is HEIGHT rows high.'
)
parser.add_argument(
'-N', '--name', type=str, help='Prefix output information with NAME.'
)
parser.add_argument(
'-f', '--force', action='store_true', help='Force output.'
)
parser.add_argument(
'-c',
'--cursor',
action='store_true',
help='Use cursor positioning escape sequences.',
)
# Data transfer modifiers
parser.add_argument(
'-L',
'--rate-limit',
type=str,
help='Limit transfer to RATE bytes per second.',
)
parser.add_argument(
'-B',
'--buffer-size',
type=str,
help='Use transfer buffer size of BYTES.',
)
parser.add_argument(
'-C', '--no-splice', action='store_true', help='Never use splice.'
)
parser.add_argument(
'-E', '--skip-errors', action='store_true', help='Ignore read errors.'
)
parser.add_argument(
'-Z',
'--error-skip-block',
type=str,
help='Skip block size when ignoring errors.',
)
parser.add_argument(
'-S',
'--stop-at-size',
action='store_true',
help='Stop transferring after SIZE bytes.',
)
parser.add_argument(
'-Y',
'--sync',
action='store_true',
help='Synchronise buffer caches to disk after writes.',
)
parser.add_argument(
'-K',
'--direct-io',
action='store_true',
help='Set O_DIRECT flag on all inputs/outputs.',
)
parser.add_argument(
'-X',
'--discard',
action='store_true',
help='Discard input data instead of transferring it.',
)
parser.add_argument(
'-d', '--watchfd', type=str, help='Watch file descriptor of process.'
)
parser.add_argument(
'-R',
'--remote',
type=int,
help='Remote control another running instance of pv.',
)
# General options
parser.add_argument(
'-P', '--pidfile', type=pathlib.Path, help='Save process ID in FILE.'
)
parser.add_argument(
'input',
help='Input file path. Uses stdin if not specified.',
default='-',
nargs='*',
)
parser.add_argument(
'-o',
'--output',
default='-',
help='Output file path. Uses stdout if not specified.',
)
return parser
def main(argv: list[str] | None = None) -> None: # noqa: C901
"""
Main function for the `progressbar` command.
Args:
argv (list[str] | None): Command-line arguments passed to the script.
Returns:
None
"""
parser: argparse.ArgumentParser = create_argument_parser()
args: argparse.Namespace = parser.parse_args(argv)
with contextlib.ExitStack() as stack:
output_stream: typing.IO[typing.Any] = _get_output_stream(
args.output, args.line_mode, stack
)
input_paths: list[BinaryIO | TextIO | Path | IO[typing.Any]] = []
total_size: int = 0
filesize_available: bool = True
for filename in args.input:
input_path: typing.IO[typing.Any] | pathlib.Path
if filename == '-':
if args.line_mode:
input_path = sys.stdin
else:
input_path = sys.stdin.buffer
filesize_available = False
else:
input_path = pathlib.Path(filename)
if not input_path.exists():
parser.error(f'File not found: {filename}')
if not args.size:
total_size += input_path.stat().st_size
input_paths.append(input_path)
# Determine the size for the progress bar (if provided)
if args.size:
total_size = size_to_bytes(args.size)
filesize_available = True
if filesize_available:
# Create the progress bar components
widgets = [
progressbar.Percentage(),
' ',
progressbar.Bar(),
' ',
progressbar.Timer(),
' ',
progressbar.FileTransferSpeed(),
]
else:
widgets = [
progressbar.SimpleProgress(),
' ',
progressbar.DataSize(),
' ',
progressbar.Timer(),
]
if args.eta:
widgets.append(' ')
widgets.append(progressbar.AdaptiveETA())
# Initialize the progress bar
bar = progressbar.ProgressBar(
# widgets=widgets,
max_value=total_size or None,
max_error=False,
)
# Data processing and updating the progress bar
buffer_size = (
size_to_bytes(args.buffer_size) if args.buffer_size else 1024
)
total_transferred = 0
bar.start()
with contextlib.suppress(KeyboardInterrupt):
for input_path in input_paths:
if isinstance(input_path, pathlib.Path):
input_stream = stack.enter_context(
input_path.open('r' if args.line_mode else 'rb')
)
else:
input_stream = input_path
while True:
data: str | bytes
if args.line_mode:
data = input_stream.readline(buffer_size)
else:
data = input_stream.read(buffer_size)
if not data:
break
output_stream.write(data)
total_transferred += len(data)
bar.update(total_transferred)
bar.finish(dirty=True)
def _get_output_stream(
output: str | None,
line_mode: bool,
stack: contextlib.ExitStack,
) -> typing.IO[typing.Any]:
if output and output != '-':
mode = 'w' if line_mode else 'wb'
return stack.enter_context(open(output, mode)) # noqa: SIM115
elif line_mode:
return sys.stdout
else:
return sys.stdout.buffer
if __name__ == '__main__':
main()
|