import os from typing import List, MutableMapping from ee.xml import bomFile from ee.xml.bom_file_utils import * from ee.xml.uris import DIGIKEY_URI __all__ = ["import_parts"] class Entry(object): def __init__(self, new: bool, part: bomFile.Part): self.new = new self.part = part self.pn = find_pn(part) self.dpn = find_dpn(part, DIGIKEY_URI) def import_parts(in_path, out_path): print("in: {}, out: {}".format(in_path, out_path)) in_file = bomFile.parse(in_path, True) if in_file.partsProp is None: in_file.partsProp = bomFile.PartList() in_part_list = in_file.partsProp.partProp # type: List[bomFile.Part] print("in file: {} parts".format(len(in_part_list))) if os.path.isfile(out_path): out_file = bomFile.parse(out_path, True) else: out_file = bomFile.BomFile() if out_file.partsProp is None: out_file.partsProp = bomFile.PartList() out_part_list = out_file.partsProp.partProp # type: List[bomFile.Part] print("out file: {} parts".format(len(out_part_list))) existing_parts = [] # type: List[Entry] pn_index = {} # type: MutableMapping[str, Entry] dpn_index = {} # type: MutableMapping[str, Entry] new_entry_added = 0 def add_entry(e: Entry): existing_parts.append(e) pn_index[e.pn] = e dpn_index[e.dpn] = e if e.new: out_part_list.append(e.part) nonlocal new_entry_added new_entry_added = new_entry_added + 1 print("len(out_part_list)={}".format(len(out_part_list))) for part in out_part_list: # type: bomFile.Part entry = Entry(False, part) add_entry(entry) print("loaded {} existing parts".format(len(existing_parts))) for part in in_part_list: pn_value = find_pn(part) if pn_value is None: print("Skipping part with no part number: id={}".format(part.idProp)) continue entry = pn_index.get(pn_value) if entry is not None: print("Already imported pn_value={}".format(pn_value)) continue print("Importing {}".format(pn_value)) pns = bomFile.PartNumberList() if pn_value is not None: pns.add_part_number(bomFile.PartNumber(value=pn_value)) dpn_value = find_dpn(part, DIGIKEY_URI) if dpn_value is not None: pns.add_part_number(bomFile.PartNumber(value=dpn_value, distributor=DIGIKEY_URI)) if len(pns.part_numberProp) == 0: continue new_part = bomFile.Part(part_numbers=pns) entry = Entry(True, new_part) add_entry(entry) if new_entry_added: print("Imported {} entries".format(new_entry_added)) tmp_path = out_path + ".tmp" with open(tmp_path, "w") as f: out_file.export(f, 0, name_="bom-file") os.rename(tmp_path, out_path) else: print("no new entries")