Skip to content

Commit

Permalink
Merge pull request #27 from diegoherranz/naming_and_formatting
Browse files Browse the repository at this point in the history
Naming and formatting
  • Loading branch information
SchrodingersGat authored Jan 15, 2018
2 parents da8de61 + 9ec3a0b commit 75cb5a6
Show file tree
Hide file tree
Showing 13 changed files with 127 additions and 129 deletions.
2 changes: 1 addition & 1 deletion KiBOM/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@
import component
import sort
import preferences
import bom_writer
import bom_writer
26 changes: 13 additions & 13 deletions KiBOM/bom_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ def TmpFileCopy(filename):

if os.path.exists(filename) and os.path.isfile(filename):
shutil.copyfile(filename, filename + ".tmp")

"""
Write BoM to file
filename = output file path
Expand All @@ -25,50 +25,50 @@ def TmpFileCopy(filename):
prefs = BomPref object
"""
def WriteBoM(filename, groups, net, headings = columns.ColumnList._COLUMNS_DEFAULT, prefs=None):

filename = os.path.abspath(filename)

#no preferences supplied, use defaults
if not prefs:
prefs = BomPref()

#remove any headings that appear in the ignore[] list
headings = [h for h in headings if not h.lower() in [i.lower() for i in prefs.ignore]]

#if no extension is given, assume .csv (and append!)
if len(filename.split('.')) < 2:
filename += ".csv"

#make a temporary copy of the output file
TmpFileCopy(filename)

ext = filename.split('.')[-1].lower()

result = False

#CSV file writing
if ext in ["csv","tsv","txt"]:
if WriteCSV(filename, groups, net, headings, prefs):
print("CSV Output -> {fn}".format(fn=filename))
result = True
else:
print("Error writing CSV output")

elif ext in ["htm","html"]:
if WriteHTML(filename, groups, net, headings, prefs):
print("HTML Output -> {fn}".format(fn=filename))
result = True
else:
print("Error writing HTML output")

elif ext in ["xml"]:
if WriteXML(filename, groups, net, headings, prefs):
print("XML Output -> {fn}".format(fn=filename))
result = True
else:
print("Error writing XML output")

else:
print("Unsupported file extension: {ext}".format(ext=ext))

return result
10 changes: 5 additions & 5 deletions KiBOM/columns.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@ class ColumnList:
COL_PART = 'Part'
COL_PART_LIB = 'Part Lib'
COL_DATASHEET = 'Datasheet'

#default columns for groups
COL_GRP_QUANTITY = 'Quantity Per PCB'
COL_GRP_TOTAL_COST = 'Total Cost' #Total cost based on quantity
COL_GRP_BUILD_QUANTITY = 'Build Quantity'

#generated columns
_COLUMNS_GEN = [
COL_GRP_QUANTITY,
Expand All @@ -34,7 +34,7 @@ class ColumnList:
COL_GRP_BUILD_QUANTITY,
COL_DATASHEET
]

#default columns
#these columns are 'immutable'
_COLUMNS_PROTECTED = [
Expand All @@ -55,11 +55,11 @@ def __str__(self):

def __repr__(self):
return self.__str__()

def __init__(self, cols=_COLUMNS_DEFAULT):

self.columns = []

#make a copy of the supplied columns
for col in cols:
self.AddColumn(col)
Expand Down
4 changes: 2 additions & 2 deletions KiBOM/component.py
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,7 @@ class ComponentGroup():
"""
def __init__(self, prefs=None):
self.components = []
self.fields = dict.fromkeys(ColumnList._COLUMNS_DEFAULT) #columns loaded from KiCAD
self.fields = dict.fromkeys(ColumnList._COLUMNS_DEFAULT) #columns loaded from KiCad

if not prefs:
prefs = BomPref()
Expand Down Expand Up @@ -425,7 +425,7 @@ def updateFields(self):
self.fields[ColumnList.COL_FP_LIB] = ""
self.fields[ColumnList.COL_FP] = ""

#return a dict of the KiCAD data based on the supplied columns
#return a dict of the KiCad data based on the supplied columns
#NOW WITH UNICODE SUPPORT!
def getRow(self, columns):
row = []
Expand Down
34 changes: 17 additions & 17 deletions KiBOM/csv_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@
"""

def WriteCSV(filename, groups, net, headings, prefs):

filename = os.path.abspath(filename)

#delimeter is assumed from file extension
#override delimiter if separator specified
if prefs.separatorCSV != None:
Expand All @@ -30,49 +30,49 @@ def WriteCSV(filename, groups, net, headings, prefs):
delimiter = "\t"
else:
return False

nGroups = len(groups)
nTotal = sum([g.getCount() for g in groups])
nFitted = sum([g.getCount() for g in groups if g.isFitted()])
nBuild = nFitted * prefs.boards

with open(filename, "w") as f:

writer = csv.writer(f, delimiter=delimiter, lineterminator="\n")

if not prefs.hideHeaders:
if prefs.numberRows:
writer.writerow(["Component"] + headings)
else:
writer.writerow(headings)

count = 0
rowCount = 1

for i, group in enumerate(groups):
if prefs.ignoreDNF and not group.isFitted(): continue

row = group.getRow(headings)

if prefs.numberRows:
row = [str(rowCount)] + row

#deal with unicode characters
#row = [el.decode('latin-1') for el in row]
writer.writerow(row)

try:
count += group.getCount()
except:
pass

rowCount += 1

if not prefs.hideHeaders:
#blank rows
for i in range(5):
writer.writerow([])

writer.writerow(["Component Groups:",nGroups])
writer.writerow(["Component Count:",nTotal])
writer.writerow(["Fitted Components:", nFitted])
Expand All @@ -83,5 +83,5 @@ def WriteCSV(filename, groups, net, headings, prefs):
writer.writerow(["BoM Date:",net.getDate()])
writer.writerow(["Schematic Source:",net.getSource()])
writer.writerow(["KiCad Version:",net.getTool()])
return True

return True
64 changes: 32 additions & 32 deletions KiBOM/html_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,27 +7,27 @@
BG_KICAD = "#FFE6B3"
BG_USER = "#E6F9FF"
BG_EMPTY = "#FF8080"

#return a background color for a given column title
def bgColor(col):
#auto-generated columns
if col in ColumnList._COLUMNS_GEN:
return BG_GEN
#kicad protected columns
#KiCad protected columns
elif col in ColumnList._COLUMNS_PROTECTED:
return BG_KICAD
#additional user columns
else:
else:
return BG_USER

def link(text):

for t in ["http","https","ftp","www"]:
if text.startswith(t):
return '<a href="{t}">{t}</a>'.format(t=text)

return text

"""
Write BoM out to a HTML file
filename = path to output file (must be a .htm or .html file)
Expand All @@ -38,26 +38,26 @@ def link(text):
"""

def WriteHTML(filename, groups, net, headings, prefs):

if not filename.endswith(".html") and not filename.endswith(".htm"):
print("{fn} is not a valid html file".format(fn=filename))
return False

nGroups = len(groups)
nTotal = sum([g.getCount() for g in groups])
nFitted = sum([g.getCount() for g in groups if g.isFitted()])
nBuild = nFitted * prefs.boards

with open(filename,"w") as html:

#header
html.write("<html>\n")
html.write("<head>\n")
html.write('\t<meta charset="UTF-8">\n') #UTF-8 encoding for unicode support
html.write("</head>\n")
html.write("<body>\n")


#PCB info
if not prefs.hideHeaders:
html.write("<h2>KiBoM PCB Bill of Materials</h2>\n")
Expand All @@ -75,14 +75,14 @@ def WriteHTML(filename, groups, net, headings, prefs):
html.write("</table>\n")
html.write("<br>\n")
html.write("<h2>Component Groups</h2>\n")
html.write('<p style="background-color: {bg}">Kicad Fields (default)</p>\n'.format(bg=BG_KICAD))
html.write('<p style="background-color: {bg}">KiCad Fields (default)</p>\n'.format(bg=BG_KICAD))
html.write('<p style="background-color: {bg}">Generated Fields</p>\n'.format(bg=BG_GEN))
html.write('<p style="background-color: {bg}">User Fields</p>\n'.format(bg=BG_USER))
html.write('<p style="background-color: {bg}">Empty Fields</p>\n'.format(bg=BG_EMPTY))

#component groups
html.write('<table border="1">\n')

#row titles:
html.write("<tr>\n")
if prefs.numberRows:
Expand All @@ -94,38 +94,38 @@ def WriteHTML(filename, groups, net, headings, prefs):
h=h,
bg = ' bgcolor="{c}"'.format(c=bg) if bg else ''))
html.write("</tr>\n")

rowCount = 0

for i,group in enumerate(groups):

if prefs.ignoreDNF and not group.isFitted(): continue

row = group.getRow(headings)

rowCount += 1


html.write("<tr>\n")

if prefs.numberRows:
html.write('\t<td align="center">{n}</td>\n'.format(n=rowCount))

for n, r in enumerate(row):

if len(r) == 0:
bg = BG_EMPTY
else:
bg = bgColor(headings[n])

html.write('\t<td align="center"{bg}>{val}</td>\n'.format(bg=' bgcolor={c}'.format(c=bg) if bg else '', val=link(r)))


html.write("</tr>\n")

html.write("</table>\n")
html.write("<br><br>\n")

html.write("</body></html>")
return True

return True
Loading

0 comments on commit 75cb5a6

Please # to comment.