thhor_crs/gerber/bom.py
Stephan I. Böttcher ee16d80ba8 gerber checkout
2026-01-06 17:41:41 +01:00

85 lines
2 KiB
Python
Executable file

#! /usr/bin/python3
from fileinput import input
from sys import stdout, argv
from getopt import getopt
oo,ff = getopt(argv[1:], "hH:")
hierarchy = '/'
for o,v in oo:
if o=="-h":
hierarchy = None
if o=="-H":
hierarchy = v
headers=[]
items=[]
for l in input(ff):
# header lines start with a hash
if l[0]=='#':
headers.append(l)
continue
# everything else is a parts, four komma separated fields
item = l.split(',')
count = int(item[0])
footprint = item[1].strip('"')
value = item[2].strip('"')
# the last field is a space separated list of refdes
parts = item[3].split()
parts = [i for i in parts if i != "(unknown)"]
parts.sort()
prefix = ""
ppp = []
for p in parts:
# hierachical refdes Xn/Rm
if hierarchy:
pp = p.split(hierarchy,1)
else:
pp = ["",p]
# toplevel parts have an empty prefix
if len(pp)==1:
pp = ["",p]
# collect all parts with the same prefix
if pp[0]==prefix:
ppp.append(p)
continue
# new prefix: emit old refdes list
if ppp:
items.append([footprint,value,prefix,count,ppp])
ppp=[p]
prefix=pp[0]
# emit last refdes list
if ppp:
items.append([footprint,value,prefix,count,ppp])
# sort by footprint/value/prefix
items.sort()
# print headers
for h in headers:
stdout.write(h)
# ten refdes per line
nni = 10
for f,v,x,c,i in items:
# first nni refdes with part attributes
l = len(i[0])
i1 = 0
i2 = 1
while i2<len(i) and l+len(i[i2]) < 40:
l += len(i[i2])+1
i2 += 1
stdout.write("%-7.7s %-16.16s %3u/%-3u %s\n"
% (f,v,len(i),c," ".join(i[i1:i2])))
# remaining refdes on continuation lines
while i2<len(i):
i1=i2
i2 += 1
l = len(i[i1])
while i2<len(i) and l+len(i[i2]) < 40:
l += len(i[i2])+1
i2 += 1
stdout.write("%33s%s\n" % (""," ".join(i[i1:i2])))