fix: read effective instance properties in native inventory

This commit is contained in:
阿白叔 committed 2026-10-17 14:01:40 +08:00
1 parent 2ad0a3c6c7
commit ea024da325
4 files changed
+157 -27

No files matched your search

@@ -119,6 +119,8 @@ class NativeInventoryReader:
commands = (
(str(tools[0]), '-project=' + str(source), '-icdb=' + str(target_database),
'-snap=' + snapshot, '-h', '-t', '-offline', '-file=' + str(output / 'scope.txt')),
(str(tools[0]), '-project=' + str(source), '-icdb=' + str(target_database),
'-snap=' + snapshot, '-f', '-t', '-offline', '-file=' + str(output / 'effective.txt')),
)
report_progress(on_progress, '正在使用原生接口读取工程快照中的器件和位号…')
try:
@@ -141,7 +143,8 @@ class NativeInventoryReader:
f'原生采集进程未能确认安全释放,请保留诊断记录:{evidence}') from error
_verify_sources(source_hashes)
check_cancelled(stop_event)
result = read_ascii_discovery(project, output / 'scope.txt', old_part_numbers, expected_root=block)
result = read_ascii_discovery(project, output / 'scope.txt', old_part_numbers,
expected_root=block, effective_report_path=output / 'effective.txt')
record.update(state='ready', components=len(result.components), source_hashes_unchanged=True)
report_progress(on_progress, f'原生采集完成,已核对 {len(result.components)} 个目标位号及 UID。')
except (NativeInventoryUnsupported, OSError, UnicodeError) as error:
@@ -173,12 +176,14 @@ class NativeInventoryReader:
def _run_tool(self, desktop, command, workspace, environment, output, record, stop_event):
check_cancelled(stop_event)
name = Path(command[0]).stem
report_name = Path(next(arg[6:] for arg in command if arg.startswith('-file='))).stem
log_name = name + '-' + report_name
started = time.monotonic()
metric = {'name': name, 'exit_code': None}
metric = {'name': name, 'report': report_name, 'exit_code': None}
record['tools'].append(metric)
try:
with (output / (name + '.stdout.txt')).open('wb') as stdout, (
output / (name + '.stderr.txt')).open('wb') as stderr:
with (output / (log_name + '.stdout.txt')).open('wb') as stdout, (
output / (log_name + '.stderr.txt')).open('wb') as stderr:
process = desktop.start_process(command, cwd=workspace, env=environment,
stdout=stdout, stderr=stderr)
deadline = started + self.timeout
@@ -14,6 +14,7 @@ class NativeInventoryUnsupported(ValueError):
_UID = re.compile(r'^\$\d+I\d+$')
_PROPERTY = re.compile(r'\tProp (Ref Designator|Part Number|Value)(?: (.*))?')
def read_native_text(path: Path) -> str:
@@ -26,16 +27,83 @@ def read_native_text(path: Path) -> str:
return data.decode('mbcs' if os.name == 'nt' else 'cp1252')
def _parse_scope(text, requested):
def _require_report(text, mode):
required = {'REPORT FORMAT': 'FREEFORM', 'MODE': mode, 'TEXT LISTS': 'ON',
'SYMBOLS ONLY': 'OFF', 'NETS ONLY': 'OFF', 'USER BLOCKS': 'NONE'}
for name, value in required.items():
values = re.findall(r'^\s*' + re.escape(name) + r':[ \t]*([^\r\n]+)', text, re.MULTILINE)
if [item.strip() for item in values] != [value]:
raise NativeInventoryUnsupported('原生全工程报告缺字段、被筛选或格式不受支持')
def _effective_properties(text):
_require_report(text, 'FLAT BLOCKS')
if len(re.findall(r'^Config .+', text, re.MULTILINE)) != 1:
raise NativeInventoryUnsupported('展开报告必须具有唯一配置')
result, attributes, paths = {}, {}, []
symbol = None
def finish():
if symbol is None:
return
uid, ref = symbol
if not _UID.fullmatch(uid):
if attributes.get('Part Number'):
raise NativeInventoryUnsupported('展开报告的物料缺少唯一 UID')
return
if uid in result or paths != ['']:
raise NativeInventoryUnsupported('展开报告含重复或嵌套实例,需由 CAD 核验')
if ref != attributes.get('Ref Designator', ''):
raise NativeInventoryUnsupported('展开报告的位号与属性不一致')
result[uid] = dict(attributes)
if len(result) > 100000:
raise NativeInventoryUnsupported('原生器件数量超过读取上限')
for line in text.splitlines():
if line.startswith(' Symbol '):
finish()
match = re.fullmatch(r' Symbol (.+?)\tref des ([^\t]*)\tpage [^\t]*', line)
if match is None:
raise NativeInventoryUnsupported('展开报告含不明确的器件身份')
symbol, attributes, paths = match.groups(), {}, []
elif symbol is not None and line.startswith('\tPath '):
paths.append(line[6:])
elif symbol is not None:
match = _PROPERTY.fullmatch(line)
if match:
key, value = match.groups()
if key in attributes:
raise NativeInventoryUnsupported('展开报告的器件属性不唯一')
attributes[key] = value or ''
finish()
return result
def _parse_scope(text, requested, effective):
blocks, sheets, targets = set(), set(), set()
seen_uids = set()
block, symbol, attributes = '', None, {}
def finish():
if symbol is not None and attributes.get('Part Number', '').casefold() in requested:
uid, sheet = symbol
ref, part = attributes.get('Ref Designator', ''), attributes['Part Number']
if not _UID.fullmatch(uid) or not ref:
if symbol is None:
return
uid, sheet = symbol
if not _UID.fullmatch(uid):
if attributes.get('Part Number'):
raise NativeInventoryUnsupported('全工程报告中的请求物料缺少唯一身份')
target = block, sheet, uid, ref, part, attributes.get('Value', '')
return
if uid in seen_uids or uid not in effective:
raise NativeInventoryUnsupported('分层与展开报告的 UID 不完整或重复,需由 CAD 核验')
seen_uids.add(uid)
values = effective[uid]
if attributes.get('Part Number') and 'Part Number' not in values:
raise NativeInventoryUnsupported('展开报告缺少物料生效属性')
if 'Value' in attributes and 'Value' not in values:
raise NativeInventoryUnsupported('展开报告缺少 Value 生效属性')
if values.get('Part Number', '').casefold() in requested:
ref, part = values.get('Ref Designator', ''), values['Part Number']
if not ref or 'Ref Designator' not in attributes:
raise NativeInventoryUnsupported('全工程报告中的请求物料缺少位号')
target = block, sheet, uid, ref, part, values.get('Value', '')
if target in targets:
raise NativeInventoryUnsupported('全工程报告含重复器件身份')
targets.add(target)
@@ -58,7 +126,7 @@ def _parse_scope(text, requested):
sheets.add((block, symbol[1]))
elif symbol is not None and line.startswith('\tProp '):
# Pin properties have two tabs and must never override a component.
match = re.fullmatch(r'\tProp (Ref Designator|Part Number|Value)(?: (.*))?', line)
match = _PROPERTY.fullmatch(line)
if match:
key, value = match.groups()
if key in attributes:
@@ -67,19 +135,20 @@ def _parse_scope(text, requested):
finish()
if not blocks or not sheets:
raise NativeInventoryUnsupported('全工程报告缺少原理图或图页')
if seen_uids != set(effective):
raise NativeInventoryUnsupported('分层与展开报告的器件范围不一致,需由 CAD 核验')
return blocks, sheets, targets
def read_ascii_discovery(project, report_path, old_part_numbers, *, expected_root=None):
def read_ascii_discovery(project, report_path, old_part_numbers, *, expected_root=None,
effective_report_path=None):
text = read_native_text(report_path)
required = {'REPORT FORMAT': 'FREEFORM', 'MODE': 'HIER BLOCKS', 'TEXT LISTS': 'ON',
'SYMBOLS ONLY': 'OFF', 'NETS ONLY': 'OFF', 'USER BLOCKS': 'NONE'}
for name, value in required.items():
values = re.findall(r'^\s*' + re.escape(name) + r':[ \t]*([^\r\n]+)', text, re.MULTILINE)
if [item.strip() for item in values] != [value]:
raise NativeInventoryUnsupported('原生全工程报告缺字段、被筛选或格式不受支持')
_require_report(text, 'HIER BLOCKS')
if effective_report_path is None:
raise NativeInventoryUnsupported('缺少实例生效属性报告,需由 CAD 核验')
effective = _effective_properties(read_native_text(effective_report_path))
requested = {part.casefold() for part in old_part_numbers}
blocks, available, targets = _parse_scope(text, requested)
blocks, available, targets = _parse_scope(text, requested, effective)
if expected_root is not None and expected_root not in blocks:
raise NativeInventoryUnsupported('原生全工程报告与工程根块身份不一致')
components = tuple(ComponentTarget(Path(project), *row) for row in sorted(targets))
+57 -4
View File
@@ -3,6 +3,50 @@ import pytest
from dx_productivity.trial_task_center import native_inventory_protocol as protocol
def effective_report(tmp_path, *, part='NEW', value='0R/NC', path='', duplicate=False):
output = tmp_path / 'effective.txt'
row = (' Symbol $27I100\tref des R1\tpage \n\tPath ' + path + '\n'
'\tProp Ref Designator R1\n\tProp Part Number ' + part + '\n\tProp Value ' + value + '\n')
output.write_text(' REPORT FORMAT: FREEFORM\n MODE: FLAT BLOCKS\n TEXT LISTS: ON\n'
' SYMBOLS ONLY: OFF\n NETS ONLY: OFF\n USER BLOCKS: NONE\n'
'Config default\tview none\n' + row + (row if duplicate else '') +
' Symbol $28I200\tref des R2\tpage \n\tPath \n'
'\tProp Ref Designator R2\n\tProp Part Number OLD\n\tProp Value 20K\n')
return output
def test_inventory_uses_effective_instance_part_and_value_before_filtering(tmp_path):
result = protocol.read_ascii_discovery(tmp_path / 'board.prj', report(tmp_path), ('NEW',),
effective_report_path=effective_report(tmp_path))
assert [(c.uid, c.old_part_number, c.old_value) for c in result.components] == [('$27I100', 'NEW', '0R/NC')]
assert result.components[0].schematic_name == 'board'
assert result.components[0].sheet_number == 'MAIN'
result = protocol.read_ascii_discovery(tmp_path / 'board.prj', report(tmp_path), ('OLD',),
effective_report_path=effective_report(tmp_path))
assert [c.uid for c in result.components] == ['$28I200']
@pytest.mark.parametrize('change', ['missing', 'extra', 'duplicate', 'nested', 'duplicate_property', 'multiple_configs', 'no_path', 'missing_value'])
def test_effective_inventory_requires_complete_unambiguous_uid_mapping(tmp_path, change):
flat = effective_report(tmp_path, duplicate=change == 'duplicate', path='U1' if change == 'nested' else '')
text = flat.read_text()
if change == 'missing':
text = text[:text.index(' Symbol $28I200')]
elif change == 'extra':
text += ' Symbol $29I300\tref des R3\tpage \n\tPath \n\tProp Ref Designator R3\n\tProp Part Number NEW\n'
elif change == 'duplicate_property':
text = text.replace('\tProp Part Number NEW', '\tProp Part Number NEW\n\tProp Part Number OTHER')
elif change == 'multiple_configs':
text += 'Config alternate\tview none\n'
elif change == 'no_path':
text = text.replace('\tPath \n', '')
elif change == 'missing_value':
text = text.replace('\tProp Value 0R/NC\n', '')
flat.write_text(text)
with pytest.raises(protocol.NativeInventoryUnsupported):
protocol.read_ascii_discovery(tmp_path / 'board.prj', report(tmp_path), ('NEW',), effective_report_path=flat)
def report(tmp_path):
path = tmp_path / 'report.txt'
path.write_text('iCDB Ascii Report Generation Date: test\n'
@@ -22,7 +66,8 @@ def report(tmp_path):
def test_offline_full_project_report_includes_disconnected_schematic_and_exact_uid(tmp_path):
path = report(tmp_path)
project = tmp_path / 'source.prj'
result = protocol.read_ascii_discovery(project, path, ('old',))
result = protocol.read_ascii_discovery(project, path, ('old',),
effective_report_path=effective_report(tmp_path, part='OLD', value='10K/NC'))
assert result.sheets == (('board', 'MAIN'), ('disconnected', 'AUX'))
assert [(t.project_path, t.schematic_name, t.sheet_number, t.uid, t.refdes, t.old_part_number, t.old_value)
for t in result.components] == [
@@ -56,11 +101,13 @@ def test_filtered_or_ambiguous_ascii_report_requires_com_fallback(tmp_path, chan
text = text.replace(old, new)
path.write_text(text)
with pytest.raises(protocol.NativeInventoryUnsupported):
protocol.read_ascii_discovery(tmp_path / 'source.prj', path, ('OLD',))
protocol.read_ascii_discovery(tmp_path / 'source.prj', path, ('OLD',),
effective_report_path=effective_report(tmp_path, part='OLD', value='10K/NC'))
def test_absent_requested_part_returns_empty_inventory_with_available_sheets(tmp_path):
result = protocol.read_ascii_discovery(tmp_path / 'source.prj', report(tmp_path), ('OTHER',))
result = protocol.read_ascii_discovery(tmp_path / 'source.prj', report(tmp_path), ('OTHER',),
effective_report_path=effective_report(tmp_path, part='OLD', value='10K/NC'))
assert not result.components
assert result.matched_old_parts == {('board', 'MAIN'): frozenset(), ('disconnected', 'AUX'): frozenset()}
@@ -76,7 +123,8 @@ def test_component_cache_cannot_substitute_for_complete_page_discovery(tmp_path)
def discover(path, parts, *, collect_components=False, **controls):
calls.append(collect_components)
if collect_components:
return protocol.read_ascii_discovery(project, report(tmp_path), parts)
return protocol.read_ascii_discovery(project, report(tmp_path), parts,
effective_report_path=effective_report(tmp_path, part='OLD', value='10K/NC'))
return ProjectDiscovery((('board', 'MAIN'), ('disconnected', 'AUX'), ('empty', 'BLANK')),
{('board', 'MAIN'): frozenset({'old'}), ('disconnected', 'AUX'): frozenset({'old'}),
('empty', 'BLANK'): frozenset()})
@@ -85,3 +133,8 @@ def test_component_cache_cannot_substitute_for_complete_page_discovery(tmp_path)
full = preparer.discover_project(project, ('OLD',))
assert ('empty', 'BLANK') in full.sheets
assert calls == [True, False]
def test_inventory_requires_effective_values_even_when_no_requested_base_part_matches(tmp_path):
with pytest.raises(protocol.NativeInventoryUnsupported):
protocol.read_ascii_discovery(tmp_path / 'board.prj', report(tmp_path), ('NEW',))
+7 -4
View File
@@ -37,9 +37,11 @@ def reader_fixture(tmp_path, *, fail_cleanup=False, cancel=False, corrupt=False,
assert str(source.parent) not in snapshot.read_text()
Path(options['file']).write_text(
(' REPORT FORMAT: TABULAR\n' if corrupt else ' REPORT FORMAT: FREEFORM\n') +
' MODE: HIER BLOCKS\n USER BLOCKS: NONE\n TEXT LISTS: ON\n'
(' MODE: FLAT BLOCKS\n' if '-f' in command else ' MODE: HIER BLOCKS\n') +
' USER BLOCKS: NONE\n TEXT LISTS: ON\n'
' SYMBOLS ONLY: OFF\n NETS ONLY: OFF\n'
'Block board \tRoot\n Symbol $27I100\tpage MAIN\n'
+ ('Config default\tview none\n Symbol $27I100\tref des R1\tpage \n\tPath \n'
if '-f' in command else 'Block board \tRoot\n Symbol $27I100\tpage MAIN\n') +
'\tProp Ref Designator R1\n\tProp Part Number OLD\n\tProp Value 10K\n')
def poll():
if cancel:
@@ -61,12 +63,13 @@ def test_reader_uses_a_disposable_database_and_returns_certified_native_identity
before = project.read_bytes(), (project.parent / 'database/icdb.dat').read_bytes()
messages = []
result = reader.read(project, ('OLD',), stop_event=stop, on_progress=messages.append)
assert len(calls) == 1 and released == [True]
assert len(calls) == 2 and released == [True]
assert '-h' in calls[0] and '-f' in calls[1]
assert [(c.refdes, c.uid, c.sheet_number) for c in result.components] == [('R1', '$27I100', 'MAIN')]
assert before == (project.read_bytes(), (project.parent / 'database/icdb.dat').read_bytes())
assert not list((tmp_path / 'temporary').iterdir())
record = json.loads(next((tmp_path / 'evidence').rglob('native-inventory.json')).read_text())
assert record['state'] == 'ready' and len(record['tools']) == 1
assert record['state'] == 'ready' and len(record['tools']) == 2
assert messages