85 lines
2.4 KiB
Python
85 lines
2.4 KiB
Python
import csv
|
|
import sys
|
|
|
|
# ANSI escape codes
|
|
CYAN = '\033[96m'
|
|
GREEN = '\033[92m'
|
|
YELLOW = '\033[93m'
|
|
MAGENTA = '\033[95m'
|
|
BLUE = '\033[94m'
|
|
RESET = '\033[0m'
|
|
|
|
|
|
def reorder_columns(rows, column_to_move="Quantity", new_index=2):
|
|
header = rows[0]
|
|
if column_to_move not in header:
|
|
return rows # no change if "Quantity" not present
|
|
|
|
# Move the column in the header
|
|
old_index = header.index(column_to_move)
|
|
new_header = header[:]
|
|
new_header.pop(old_index)
|
|
new_header.insert(new_index, column_to_move)
|
|
|
|
# Apply same reordering to all rows
|
|
reordered_rows = [new_header]
|
|
for row in rows[1:]:
|
|
if len(row) < len(header): # skip malformed rows
|
|
continue
|
|
value = row.pop(old_index)
|
|
row.insert(new_index, value)
|
|
reordered_rows.append(row)
|
|
return reordered_rows
|
|
|
|
def read_csv(file_path):
|
|
with open(file_path, newline='') as csvfile:
|
|
return list(csv.reader(csvfile))
|
|
|
|
def get_column_widths(rows):
|
|
return [max(len(str(item)) for item in col) for col in zip(*rows)]
|
|
|
|
def print_csv_colored(rows):
|
|
col_widths = get_column_widths(rows)
|
|
header, *data = rows
|
|
|
|
# Print header in cyan
|
|
header_line = "\t".join(f"{CYAN}{str(cell).ljust(width)}{RESET}" for cell, width in zip(header, col_widths))
|
|
print(header_line)
|
|
|
|
# Separator, max 80 chars
|
|
print("-" * min(len(header_line), 80))
|
|
|
|
# Colorized data
|
|
for row in data:
|
|
# Replace empty with "NA"
|
|
row_cleaned = [cell if cell else "NA" for cell in row]
|
|
|
|
if "NA" in row_cleaned:
|
|
# Entire row magenta
|
|
colored_cells = [f"{MAGENTA}{str(cell).ljust(width)}{RESET}" for cell, width in zip(row_cleaned, col_widths)]
|
|
else:
|
|
# Column-based coloring
|
|
colored_cells = []
|
|
for i, (cell, width) in enumerate(zip(row_cleaned, col_widths)):
|
|
if i == 1:
|
|
color = YELLOW
|
|
elif i == 2:
|
|
color = RESET
|
|
elif i == 3:
|
|
color = BLUE
|
|
else:
|
|
color = GREEN
|
|
colored_cells.append(f"{color}{str(cell).ljust(width)}{RESET}")
|
|
|
|
print("\t".join(colored_cells))
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
if len(sys.argv) != 2:
|
|
print("Usage: python display_bom.py <bom.csv>")
|
|
else:
|
|
rows = read_csv(sys.argv[1])
|
|
reordered = reorder_columns(rows)
|
|
print_csv_colored(reordered)
|