Code improvements, line numbering fix, reformatting (with Black)

This commit is contained in:
Lavender Perry 2021-12-23 01:34:38 -08:00
parent ec63eb4e58
commit d9c8ccabae
Signed by untrusted user: elle
GPG key ID: EF8E44AF715C28A0

112
pat
View file

@ -1,98 +1,98 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
from enum import IntEnum from sys import argv, stdin
from sys import argv, stdin, stderr from string import whitespace
import argparse import argparse
import os import os
import string
# If the program is using too much memory, try decreasing this value # If the program is using too much memory, try decreasing this value
# If some text is getting cut off, try increasing this value # If some text is getting cut off, try increasing this value
bytes_to_read = 1000000 bytes_to_read = 1000000
first_file = True line_str = lambda line: str(line).rjust(6, " ") + " "
line_str = lambda line: str(line).rjust(8, ' ') + ' '
color_print = lambda red, green, blue, string: print( color_print = lambda red, green, blue, string: print(
f"\x1b[38;2;{red};{green};{blue}m{string}", f"\033[38;2;{red};{green};{blue}m{string}", end=""
end='') )
parser = argparse.ArgumentParser(description="Output text from files with color.") parser = argparse.ArgumentParser(description="Output text from files with color.")
parser.add_argument("-n", "--number", parser.add_argument(
action="store_true", "-n", "--number", action="store_true", help="number all output lines"
help="number all output lines") )
parser.add_argument("-m", "--max_rgb_value", parser.add_argument(
type=float, nargs='?', default=255, "-m",
help="max value any r/g/b can have. 0 <= argument <= 255") "--max_rgb_value",
parser.add_argument("-c", "--color_amount", type=float,
type=int, nargs='?', default=300, nargs="?",
help="amount of colors to output. arg is divisible by 3, 0 <= arg <= max * 3.") default=255,
parser.add_argument("paths", help="max value any r/g/b can have. 0 <= argument <= 255",
nargs='*', default=['-'], )
help="a path to open ('-' for stdin)") parser.add_argument(
"-c",
"--color_amount",
type=int,
nargs="?",
default=300,
help="amount of colors to output. arg is divisible by 3, 0 <= arg <= max * 3.",
)
parser.add_argument(
"paths", nargs="*", default=["-"], help="a path to open ('-' for stdin)"
)
args = parser.parse_args() args = parser.parse_args()
# Checking arguments are valid # Checking arguments are valid
assert ( assert (
0 <= args.max_rgb_value <= 255 and 0 <= args.max_rgb_value <= 255
args.color_amount <= args.max_rgb_value * 3 and and args.color_amount <= args.max_rgb_value * 3
not args.color_amount % 3), f"Invalid arguments. Run `{argv[0]} -h` for help." and not args.color_amount % 3
), f"Invalid arguments. Run `{argv[0]} -h` for help."
class ColorInfo(IntEnum):
AMOUNT = args.color_amount
MAX_RGB_VALUE = args.max_rgb_value
PER_STAGE = args.color_amount / 3
MIN_RGB_VALUE = MAX_RGB_VALUE - PER_STAGE
colors_per_stage = args.color_amount // 3
min_rgb_value = args.max_rgb_value - colors_per_stage
line = 1 if args.number else False line = 1 if args.number else False
line_print_pending = False
# Windows command prompt / powershell support # Windows command prompt / powershell support
if os.name == "nt": if os.name == "nt":
os.system('') os.system("")
for path in args.paths: for path in args.paths:
try: with stdin if path == "-" else open(path, "r") as file:
file = stdin if path == '-' else open(path, 'r')
read_result = file.read(bytes_to_read) read_result = file.read(bytes_to_read)
except Exception as e: changes = len(list(filter(lambda c: not c in whitespace, read_result))) - 1
print(f"Error reading {path}: {e}", file=stderr) step = 0 if changes == 0 else (args.color_amount - 1) / changes
continue
changes = len(list(filter(lambda c: not c in string.whitespace, read_result))) - 1
step = 0 if changes == 0 else (ColorInfo.AMOUNT - 1) / changes
index = 0 index = 0
if line and first_file: if line:
color_print( color_print(
ColorInfo.MAX_RGB_VALUE, args.max_rgb_value, min_rgb_value, min_rgb_value, line_str(line)
ColorInfo.MIN_RGB_VALUE, )
ColorInfo.MIN_RGB_VALUE,
line_str(line))
for char in read_result: for char in read_result:
if char in string.whitespace: if line_print_pending:
print(char, end='') print(line_str(line), end="")
if line and char == '\n': line_print_pending = False
if char in whitespace:
print(char, end="")
if line and char == "\n":
line += 1 line += 1
print(line_str(line), end='') line_print_pending = True
continue continue
color_value = round(index) color_value = round(index)
value_modifier = color_value % ColorInfo.PER_STAGE value_modifier = color_value % colors_per_stage
rgb_values = [ rgb_values = [
ColorInfo.MIN_RGB_VALUE + value_modifier, min_rgb_value + value_modifier,
ColorInfo.MAX_RGB_VALUE - value_modifier, args.max_rgb_value - value_modifier,
ColorInfo.MIN_RGB_VALUE, min_rgb_value,
] ]
[red, green, blue] = [ [red, green, blue] = [
[rgb_values[1], rgb_values[0], rgb_values[2]], [rgb_values[1], rgb_values[0], rgb_values[2]],
rgb_values[::-1], rgb_values[::-1],
[rgb_values[0], rgb_values[2], rgb_values[1]], [rgb_values[0], rgb_values[2], rgb_values[1]],
][color_value // ColorInfo.PER_STAGE] ][color_value // colors_per_stage]
color_print(red, green, blue, char) color_print(red, green, blue, char)
index += step index += step
print("\x1b[0m") line_print_pending = False
print("\033[0m", end="")