Files
New Design Review pretty-print/display_bom.py
2025-06-02 01:31:02 +00:00

95 lines
2.9 KiB
Python

import csv
import sys
import os
# Import pprint_color and COLOR_LOOKUP from your module
sys.path.append(os.path.join(os.path.dirname(__file__), '.allspice/pretty-print'))
from pretty_print import pprint_color, COLOR_LOOKUP
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
old_index = header.index(column_to_move)
new_header = header[:]
new_header.pop(old_index)
new_header.insert(new_index, column_to_move)
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):
header, *data = rows
widths = []
for col_idx in range(len(header)):
header_len = len(str(header[col_idx]))
data_len = max(
len(str(row[col_idx]) if len(row) > col_idx and row[col_idx] else "NA")
for row in data
)
widths.append(max(header_len, data_len))
return widths
def print_csv_colored(rows):
col_widths = get_column_widths(rows)
header, *data = rows
# Print header in Tech Blue on Clear White
header_line = "".join(str(cell).ljust(width + 2) for cell, width in zip(header, col_widths))
pprint_color(header_line, fg_color="Clear White", bg_color="Tech Blue")
# Separator line
print("-" * min(len(header_line), 80))
# Data rows without labels
for row in data:
row_cleaned = [cell if cell else "NA" for cell in row]
if "NA" in row_cleaned:
for cell, width in zip(row_cleaned, col_widths):
content = str(cell).ljust(width + 2)
pprint_color(content, fg_color="Clear White", bg_color="Red", end="")
print()
else:
for i, (cell, width) in enumerate(zip(row_cleaned, col_widths)):
# Color logic per column
if i == 0:
fg = "Clear White"
bg = "Darker Green"
elif i == 1 or i == 3:
fg = "Clear White"
bg = "Tech Blue"
else:
fg = "Clear White"
bg = "Darker Green"
content = str(cell).ljust(width + 2)
pprint_color(content, fg_color=fg, bg_color=bg, end="")
print()
if __name__ == "__main__":
if len(sys.argv) != 2:
pprint_color("Usage: python display_bom.py <bom.csv>", fg_color="Red")
else:
rows = read_csv(sys.argv[1])
reordered = reorder_columns(rows)
print_csv_colored(reordered)