#!/usr/bin/env python3 """BOM Manager — analyze KiCad schematic BOM properties and manage BOM files. Reads KiCad 6+ .kicad_sch files and KiCad 5 .sch files (read only), detects the project's part number convention, classifies existing part numbers by distributor, identifies gaps, and outputs a structured report. Can also export/merge BOM tracking CSV files. Usage: # Analyze a schematic (human-readable output) python3 bom_manager.py analyze path/to/schematic.kicad_sch # JSON output for programmatic use python3 bom_manager.py analyze path/to/schematic.kicad_sch --json # Show only parts with missing fields python3 bom_manager.py analyze path/to/schematic.kicad_sch --gaps-only # Include all hierarchical sub-sheets python3 bom_manager.py analyze path/to/schematic.kicad_sch --recursive # Export BOM tracking CSV (creates or merges with existing) python3 bom_manager.py export path/to/schematic.kicad_sch -o bom/bom.csv # Export with recursive sub-sheets python3 bom_manager.py export path/to/schematic.kicad_sch -o bom/bom.csv --recursive # A KiCad 10 design variant (default: the default variant) python3 bom_manager.py analyze path/to/schematic.kicad_sch --recursive --variant "ETD 39" """ from __future__ import annotations import argparse import io import json import re import sys from collections import Counter from pathlib import Path import _core_path # noqa: F401 from bom_fields import (FIELD_ALIASES, POPULATE_UNFITTED, _ALIAS_LOOKUP, _SLOT_NAME_RE, _SLOT_PN_RE, _SUPPLIER_NAME_MAP, _canonical_for, _first_nonblank_stripped, _pick_mpn_from_props, _slot_pn_number, _symbol_slots) from kicad_core.diagnostics import record from kicad_core.fields import (merge_unit_fields, MPN_FIELD_ALIASES, MPN_FIELD_ALIASES_PRIMARY, MPN_FIELD_ALIASES_GENERIC, DIGIKEY_FIELD_ALIASES, normalize_field_name) from kicad_core.instances import tilde_is_empty, variant_overrides from kicad_core.sexp import get_value, parse from kicad_sexp import (atomic_write_text, find_matching_paren, direct_child, direct_value, find_sub_sheet_entries, iter_placed_symbol_blocks, resolved_instance, sheet_variant, symbol_instances_of) # Canonical field names to use when creating new properties CANONICAL_NAMES = { "mpn": "MPN", "manufacturer": "Manufacturer", "digikey": "DigiKey", "mouser": "Mouser", "lcsc": "LCSC", "element14": "element14", } # Standard KiCad fields (not BOM-relevant custom fields) STANDARD_FIELDS = { "Reference", "Value", "Footprint", "Datasheet", "Description", "Sim.Device", "Sim.Pins", "Sim.Type", "Sim.Name", "Sim.Library", "ki_fp_filters", "ki_keywords", "ki_description", "ki_locked", "Intersheetrefs", } # DNP field name variants DNP_FIELDS = {"DNP", "dnp", "DONOTPLACE", "DNM", "POPULATE", "Do Not Populate"} # BOM Comments field name variants — freeform per-component notes for ordering/assembly # Ordered list for extraction priority (first match wins); set for fast membership checks _BOM_COMMENT_NAMES = [ "BOM Comments", "BOM_Comments", "BOM Comment", "BOM_Comment", "BOM Notes", "BOM_Notes", "BOM Note", "BOM_Note", "Ordering Notes", "Ordering_Notes", "Order Notes", "Assembly Notes", "Assembly_Notes", "Notes", "Remarks", "Comment", ] BOM_COMMENT_FIELDS = set(_BOM_COMMENT_NAMES) # Reference prefix patterns for component classification _REF_TYPE = { "C": "capacitor", "R": "resistor", "L": "inductor", "D": "diode", "U": "ic", "Q": "transistor", "J": "connector", "P": "connector", "SW": "switch", "F": "fuse", "Y": "crystal", "X": "crystal", "BT": "battery", "LS": "speaker", "BZ": "buzzer", "M": "motor", "TP": "test_point", "MH": "mounting_hole", "H": "mounting_hole", "FL": "filter", "FB": "ferrite_bead", "T": "transformer", "K": "relay", "LED": "led", } # --------------------------------------------------------------------------- # Schematic parsing # --------------------------------------------------------------------------- def extract_placed_symbols(text: str) -> list[tuple[int, int, str]]: """Find all placed symbol blocks (not lib_symbols) in a .kicad_sch file. Returns list of (start_pos, end_pos, block_text) tuples. """ return iter_placed_symbol_blocks(text) def extract_properties(symbol_block: str) -> dict[str, str]: """Extract all (property "name" "value" ...) from a symbol block.""" props = {} for match in re.finditer( r'\(property\s+"((?:[^"\\]|\\.)*)"\s+"((?:[^"\\]|\\.)*)"', symbol_block, ): name = match.group(1) value = match.group(2) props[name] = value return props def is_in_bom(symbol_block: str) -> bool: """Check if a symbol has (in_bom yes).""" match = re.search(r'\(in_bom\s+(yes|no)\)', symbol_block) return match is not None and match.group(1) == "yes" def is_dnp(symbol_block: str, props: dict[str, str]) -> bool: """Check if a symbol is marked DNP.""" # KiCad 7+ built-in DNP flag match = re.search(r'\(dnp\s+(yes|no)\)', symbol_block) if match and match.group(1) == "yes": return True # Custom DNP fields for field in DNP_FIELDS: val = props.get(field, "").strip().upper() # POPULATE is a population flag, so "1" / "yes" / "true" mean fitted if field == "POPULATE": if val.lower() in POPULATE_UNFITTED: return True continue if val in ("YES", "TRUE", "1", "DNP"): return True return False def classify_reference(ref: str) -> str: """Classify component type from reference designator prefix.""" if ref.startswith("#"): return "power_symbol" # Try longest prefix matches first for prefix in sorted(_REF_TYPE, key=len, reverse=True): if ref.startswith(prefix): return _REF_TYPE[prefix] return "other" # --------------------------------------------------------------------------- # Part number pattern detection # --------------------------------------------------------------------------- def classify_pn_by_pattern(value: str) -> str | None: """Try to classify a part number by its pattern. Returns canonical name or None.""" value = value.strip() if not value or value == "~": return None # DigiKey: ends with -ND (sometimes with digits before ND) if re.search(r'-\d*-?ND$', value): return "digikey" # LCSC: C followed by 3-8 digits (exactly) if re.match(r'^C\d{3,8}$', value): return "lcsc" # Mouser: 2-3 digit numeric prefix + hyphen + alphanumeric manufacturer PN if re.match(r'^\d{2,3}-[A-Za-z0-9]', value): return "mouser" return None # --------------------------------------------------------------------------- # Convention detection # --------------------------------------------------------------------------- def detect_convention( all_symbols: list[dict], ) -> dict: """Detect the project's BOM field naming convention. Returns a dict describing which field names are used, how they map to canonical names, and which distributor appears to be preferred. """ # Count occurrences of each property name across all symbols field_counts: Counter[str] = Counter() populated_counts: dict[str, int] = {} # canonical -> count of non-empty values # Also detect "Supplier N" / "Supplier N Part #" pattern (KiCad field names) # Maps the value inside the Supplier field to canonical distributor names # Track KiCad "Supplier N" slot mappings: slot_number -> (name_field, pn_field, canonical) supplier_slots: dict[int, dict] = {} # "supplier" here refers to KiCad field names for sym in all_symbols: for name, value in sym["raw_properties"].items(): if name in STANDARD_FIELDS: continue field_counts[name] += 1 canonical = _canonical_for(name) if canonical and value.strip(): populated_counts[canonical] = populated_counts.get(canonical, 0) + 1 # Detect KiCad "Supplier N" field pattern sup_match = _SLOT_NAME_RE.match(name.strip()) if sup_match and value.strip(): slot = int(sup_match.group(1)) dist_name = value.strip().lower() canonical_sup = _SUPPLIER_NAME_MAP.get(dist_name) if canonical_sup and slot not in supplier_slots: supplier_slots[slot] = { "name_field": name, "canonical": canonical_sup, } # Detect KiCad "Supplier N Part #" or "Supplier N Part Number" field pn_slot = _slot_pn_number(name) if pn_slot is not None: slot = pn_slot if slot in supplier_slots: supplier_slots[slot]["pn_field"] = name # Count this as a populated distributor field can = supplier_slots[slot]["canonical"] if value.strip(): populated_counts[can] = populated_counts.get(can, 0) + 1 # Build field mapping: canonical -> actual field name used in this project field_mapping: dict[str, str] = {} for name in field_counts: canonical = _canonical_for(name) if canonical: # If multiple aliases map to same canonical, pick the most common if canonical not in field_mapping or field_counts[name] > field_counts.get(field_mapping[canonical], 0): field_mapping[canonical] = name # Add KiCad supplier slot mappings (only if not already mapped by direct field names) for slot_info in supplier_slots.values(): can = slot_info["canonical"] if can not in field_mapping and "pn_field" in slot_info: field_mapping[can] = slot_info["pn_field"] # Determine preferred distributor by populated count distributor_counts = { k: v for k, v in populated_counts.items() if k in ("digikey", "mouser", "lcsc", "element14") } preferred_distributor = None if distributor_counts: preferred_distributor = max(distributor_counts, key=distributor_counts.get) # Check if field names are already canonical names_canonical = all( field_mapping.get(c) == CANONICAL_NAMES.get(c) for c in field_mapping if c in CANONICAL_NAMES ) # What fields should be suggested for new parts # Always include MPN + Manufacturer, plus whatever distributors the project uses suggested = ["MPN", "Manufacturer"] for dist in ("digikey", "mouser", "lcsc", "element14"): if dist in field_mapping: suggested.append(field_mapping[dist]) elif dist == preferred_distributor: suggested.append(CANONICAL_NAMES[dist]) return { "field_mapping": field_mapping, # canonical -> actual field name "field_counts": dict(field_counts), # actual field name -> symbol count "populated_counts": populated_counts, # canonical -> non-empty count "preferred_distributor": preferred_distributor, "names_canonical": names_canonical, "suggested_fields": suggested, } # --------------------------------------------------------------------------- # BOM grouping # --------------------------------------------------------------------------- def generate_bom(symbols: list[dict], convention: dict, group_by: str = 'value+footprint') -> list[dict]: """Group symbols into BOM lines and identify gaps.""" groups: dict[tuple, dict] = {} seen_refs = set() field_map = convention["field_mapping"] # KiCad takes a multi-unit part's fields from its lowest unit that sets them; the library # unit count gates the merge, a placed unit above 1 standing in when the library is unknown units_by_ref: dict[str, list[dict]] = {} for sym in symbols: units_by_ref.setdefault(sym["reference"], []).append(sym) for sym in symbols: ref = sym["reference"] comp_type = sym["type"] # Skip power symbols and non-BOM components if comp_type == "power_symbol" or not sym["in_bom"]: continue if ref in seen_refs: continue seen_refs.add(ref) props = sym["raw_properties"] units = units_by_ref[ref] if "?" not in ref and any((u.get("unit_count") or (2 if u.get("unit", 1) > 1 else 1)) > 1 for u in units): props = merge_unit_fields((u.get("unit", 1), u["raw_properties"]) for u in units) slots = _symbol_slots(props) # Extract canonical field values using the project's actual field names def get_canonical(canonical_name: str) -> str: if canonical_name == "mpn": # The project's declared MPN field is # authoritative among manufacturer-specific names when it is # itself primary-tier and populated on this symbol — file # order only breaks ties between OTHER primaries. mpn_field = field_map.get("mpn") if (mpn_field and normalize_field_name(mpn_field) in MPN_FIELD_ALIASES_PRIMARY and props.get(mpn_field, "").strip()): return props.get(mpn_field, "").strip() # A manufacturer-specific field on THIS symbol always # outranks the project's convention-majority field when that # majority field is generic (e.g. the majority field is # `Part#`, but this symbol also carries `MPN`). primary = _first_nonblank_stripped(props, MPN_FIELD_ALIASES_PRIMARY) if primary: return primary actual_name = field_map.get(canonical_name) if actual_name and _slot_pn_number(actual_name) is not None: actual_name = None # slot fields are read per symbol below if actual_name: val = props.get(actual_name, "").strip() if val: return val # Try all known aliases as fallback (normalized match). # Also reached when the convention-majority field is empty on # this symbol. if canonical_name == "mpn": return _pick_mpn_from_props(props) for actual, val in props.items(): if _canonical_for(actual) == canonical_name and val.strip(): return val.strip() return slots.get(canonical_name, "") mpn = get_canonical("mpn") manufacturer = get_canonical("manufacturer") digikey = get_canonical("digikey") mouser = get_canonical("mouser") lcsc = get_canonical("lcsc") element14 = get_canonical("element14") datasheet = props.get("Datasheet", "").strip() description = props.get("Description", "").strip() value = props.get("Value", "").strip() footprint = props.get("Footprint", "").strip() # Extract BOM comments — freeform per-component notes bom_comment = "" for field_name in _BOM_COMMENT_NAMES: val = props.get(field_name, "").strip() if val: bom_comment = val break # A line never mixes DNP and fitted parts dnp = bool(sym["dnp"]) if group_by == 'mpn': group_key = (dnp, mpn) if mpn else (dnp, value, footprint, mpn) elif group_by == 'value': group_key = (dnp, value) else: # 'value+footprint' — current default group_key = (dnp, value, footprint, mpn) if group_key not in groups: groups[group_key] = { "value": value, "footprint": footprint, "mpn": mpn, "manufacturer": manufacturer, "digikey": digikey, "mouser": mouser, "lcsc": lcsc, "element14": element14, "datasheet": datasheet, "description": description, "bom_comments": [], "references": [], "quantity": 0, "dnp": sym["dnp"], "type": comp_type, } if bom_comment and bom_comment not in groups[group_key]["bom_comments"]: groups[group_key]["bom_comments"].append(bom_comment) groups[group_key]["references"].append(ref) groups[group_key]["quantity"] += 1 # Sort by first reference bom = sorted( groups.values(), key=lambda g: _ref_sort_key(g["references"][0]) if g["references"] else ("", 0), ) # Identify gaps for each BOM line for entry in bom: entry["gaps"] = _find_gaps(entry, convention) return bom def _ref_sort_key(ref: str) -> tuple[str, int]: """Sort reference designators naturally: C1, C2, C10, R1, U1.""" match = re.match(r'^([A-Za-z]+)(\d+)$', ref) if match: return (match.group(1), int(match.group(2))) return (ref, 0) def _find_gaps(entry: dict, convention: dict) -> list[str]: """Identify which fields are missing that should be populated.""" gaps = [] comp_type = entry["type"] # Skip gap analysis for test points, mounting holes, etc. if comp_type in ("test_point", "mounting_hole", "power_symbol"): return gaps if entry["dnp"]: return gaps # MPN should always be present for real components if not entry["mpn"]: gaps.append("mpn") # Manufacturer is strongly recommended alongside MPN if entry["mpn"] and not entry["manufacturer"]: gaps.append("manufacturer") # Datasheet URL should be present for anything with an MPN ds = entry["datasheet"] if entry["mpn"] and (not ds or ds == "~" or "://" not in ds): gaps.append("datasheet") # Check distributor fields that this project uses field_map = convention["field_mapping"] for dist in ("digikey", "mouser", "lcsc", "element14"): if dist in field_map and not entry.get(dist): gaps.append(dist) return gaps # --------------------------------------------------------------------------- # Full analysis # --------------------------------------------------------------------------- _VERSION = re.compile(r'\(version\s+(\d+)\)') # KiCad applies a root's (symbol_instances) only when the root predates this file version. _SYMBOL_INSTANCES_BEFORE = 20221002 def _file_version(text: str) -> int | None: match = _VERSION.search(text) return int(match.group(1)) if match else None def _library_unit_counts(text: str) -> dict[str, int]: """Library symbol name -> number of units (sub-symbols `NAME__