Fix blank BOM download and legacy worker long paths for 1.1.2

This commit is contained in:
阿白叔 committed 2026-10-15 13:53:45 +08:00
1 parent fc67d403cb
commit 714ac0bfc6
16 files changed
+284 -30

No files matched your search

+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "dx-productivity"
version = "1.1.1"
version = "1.1.2"
requires-python = ">=3.12,<3.13"
dependencies = ["PySide6>=6.7,<7", "pywin32>=306", "pywinauto>=0.6.9,<1", "openpyxl>=3.1,<4"]
@@ -6,6 +6,7 @@ import re
from pathlib import Path
from openpyxl import Workbook, load_workbook
from openpyxl.comments import Comment
from openpyxl.styles import Font, PatternFill
from openpyxl.worksheet.datavalidation import DataValidation
@@ -15,6 +16,17 @@ from .target_plan import TargetPlanRow, compile_target_rules
BOM_HEADERS = ('old_part_number', 'new_part_number', 'refdes', 'schematic_name',
'sheet_number', 'uid', 'enabled', 'custom_value', 'sync_nc')
_HEADER_HELP = (
'旧料号,必填。按文本填写,保留前导零。',
'新料号,必填。按文本填写,保留前导零。',
'位号,必填。一行可填 R1,R2,R3,支持逗号、分号、空格或顿号分隔。',
'原理图名称,可选。位号重复时用于精确匹配。',
'图页,可选。位号跨页重复时应填写图页或 UID。',
'器件 UID,可选;填写时必须与采集结果一致。',
'是否替换:TRUE/FALSE 或 是/否;留空默认替换。未列出的位号保留。',
'自定义 Value,可选;留空沿用工具原有 Value 策略。',
'同步 NC:TRUE/FALSE 或 是/否;留空默认开启。',
)
_REFDES_SPLIT = re.compile(r'[,,;;、\s]+')
_ALIASES = {
'旧料号': 'old_part_number', '旧物料编码': 'old_part_number', 'old_part': 'old_part_number',
@@ -34,9 +46,10 @@ def write_bom_template(path: Path, records=()) -> Path:
sheet.append(BOM_HEADERS)
for record in records:
sheet.append(tuple(record.get(header, '') for header in BOM_HEADERS))
for cell in sheet[1]:
for cell, help_text in zip(sheet[1], _HEADER_HELP):
cell.font = Font(bold=True, color='FFFFFF')
cell.fill = PatternFill('solid', fgColor='1D3557')
cell.comment = Comment(help_text, 'DxPartReplace')
sheet.freeze_panes = 'A2'
sheet.auto_filter.ref = sheet.dimensions
for column in ('G', 'I'):
@@ -46,6 +59,8 @@ def write_bom_template(path: Path, records=()) -> Path:
for column, width in {'A': 22, 'B': 22, 'C': 28, 'D': 18, 'E': 14,
'F': 28, 'G': 12, 'H': 24, 'I': 12}.items():
sheet.column_dimensions[column].width = width
for column in ('A', 'B', 'C', 'D', 'E', 'F', 'H'):
sheet.column_dimensions[column].number_format = '@'
path = Path(path)
workbook.save(path)
return path
@@ -65,7 +65,7 @@ def _designer_executable():
class IsolatedCadSession:
"""The supervisor never attaches to COM on the user's input desktop."""
def __init__(self, root, *, abort_event=None):
self.root = Path(root)
self.root = Path(root).resolve()
self.token = uuid4().hex
self.desktop = PrivateDesktop('dx-' + self.token, enabled=True)
self.cad = None
@@ -0,0 +1,101 @@
"""Short access paths for legacy WSH without relocating task evidence."""
from __future__ import annotations
import atexit
import ctypes
import hashlib
import os
from pathlib import Path
import tempfile
from threading import RLock
from .errors import TaskCenterError
def _short_path(path: Path) -> str | None:
function = ctypes.WinDLL('kernel32', use_last_error=True).GetShortPathNameW
function.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint]
function.restype = ctypes.c_uint
buffer = ctypes.create_unicode_buffer(32768)
count = function(str(path), buffer, len(buffer))
return buffer.value if count and count < len(buffer) else None
def _fits(root) -> bool:
# Leave room for snapshot/job suffixes and monitor handshakes.
return len(str(root)) + 100 < 260
class _AliasPool:
def __init__(self):
self.directory = None
self.links = {}
self.lock = RLock()
def alias(self, root: Path) -> Path:
import _winapi
with self.lock:
if self.directory is None:
local = Path(os.environ.get('LOCALAPPDATA') or tempfile.gettempdir())
parent = local / 'DxProductivity' / 'path-links'
parent.mkdir(parents=True, exist_ok=True)
self.directory = Path(tempfile.mkdtemp(prefix='dxp-', dir=parent))
key = hashlib.sha256(os.path.normcase(str(root)).encode('utf-8')).hexdigest()[:20]
link = self.directory / key
if not _fits(link):
raise OSError('the per-user compatibility directory is also too long')
if link not in self.links:
# Junction creation needs no symbolic-link privilege. The
# junction contains no copies and never changes the target.
_winapi.CreateJunction(str(root), str(link))
self.links[link] = root
if not link.is_junction() or link.resolve(strict=True) != root:
raise OSError('compatibility directory no longer points to the confirmed evidence')
return link
def close(self):
errors = []
with self.lock:
for link, target in tuple(self.links.items()):
try:
if link.is_junction():
if link.resolve() != target:
raise OSError('refusing to remove a redirected compatibility directory')
link.rmdir() # Remove only the link, never the target tree.
elif link.exists():
raise OSError('refusing to remove a non-junction compatibility directory')
del self.links[link]
except OSError as error:
errors.append(error)
if self.directory is not None and not self.links:
try:
self.directory.rmdir()
self.directory = None
except OSError as error:
errors.append(error)
return errors
_aliases = _AliasPool()
def cleanup_worker_aliases():
return _aliases.close()
atexit.register(cleanup_worker_aliases)
def worker_paths(script: Path, root: Path) -> tuple[str, str]:
if os.name != 'nt' or _fits(root):
return str(script), str(root)
canonical = root.resolve(strict=True)
short = _short_path(canonical)
if short and _fits(short):
return str(Path(short) / script.name), short
try:
alias = _aliases.alias(canonical)
except OSError as error:
raise TaskCenterError('quick_run_path_length',
f'无法建立长路径兼容入口:{error};尚未启动 CAD 操作。') from error
return str(alias / script.name), str(alias)
@@ -22,7 +22,7 @@ class ProjectSessionWorker:
A separate monitor thread retains the existing idle watchdog and worker job.
"""
def __init__(self, project: Path, root: Path, *, private_desktop=False):
self.project, self.root = Path(project), Path(root)
self.project, self.root = Path(project), Path(root).resolve()
self.token = uuid4().hex
self._done, self._abort = Event(), Event()
self._thread = None
@@ -1659,18 +1659,8 @@ def _next_unfinished_command(
def _vbs_worker_paths(script: Path, root: Path) -> tuple[str, str]:
"""FSO cannot see some paths beyond MAX_PATH, including monitor handshakes."""
if os.name != 'nt' or len(str(root)) + 100 < 260:
return str(script), str(root)
import ctypes
get_short_path = ctypes.WinDLL('kernel32', use_last_error=True).GetShortPathNameW
get_short_path.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint]
get_short_path.restype = ctypes.c_uint
buffer = ctypes.create_unicode_buffer(32768)
count = get_short_path(str(root.resolve(strict=True)), buffer, len(buffer))
if not count or count >= len(buffer) or len(buffer.value) + 100 >= 260:
raise TaskCenterError('quick_run_path_length',
'执行证据目录过长,且系统未提供可用短路径。请将工具和数据放到较短目录后重试;尚未启动 CAD 操作。')
return str(Path(buffer.value) / script.name), buffer.value
from .legacy_paths import worker_paths
return worker_paths(script, root)
def _resolve_cscript(windows_root: Path | None = None, is_64_bit: bool | None = None) -> Path:
@@ -135,9 +135,9 @@ class TaskCenterService:
return self._operation("preview_bom_plan", task_id,
lambda: _read_bom_plan(self._store, task_id, path))
def export_bom_template(self, task_id: str, path: Path) -> Path:
def export_bom_template(self, task_id: str | None, path: Path) -> Path:
def export():
rows = self._store.list_target_plan(task_id)
rows = self._store.list_target_plan(task_id) if task_id else ()
records = ({
'old_part_number': row.target.old_part_number,
'new_part_number': row.new_part_number,
@@ -230,7 +230,7 @@ class TrialTaskCenterWindow(QMainWindow):
self.run_panel.stop_queue_button.setEnabled(bool(self._batch_stop and not self._batch_stop.is_set()))
self.run_panel.copy_value_check.setEnabled(state.editable)
self.mapping_table.set_rules_editable(state.editable)
self.plan_panel.set_plan_editable(state.editable)
self.plan_panel.set_plan_editable(state.editable, busy=busy)
self.add_mapping_button.setEnabled(state.editable)
selected = self.mapping_table.current_rule_id() is not None
for button in (self.edit_mapping_button, self.delete_mapping_button,
@@ -26,7 +26,7 @@ ERROR_TEXT = {
"quick_run_session": "本次执行在启动或工程检查阶段停止,尚未开始本项替换。请按具体原因处理后重试。",
"quick_run_complete": "当前任务中的替换规则已经全部完成。",
"quick_run_cscript": "未找到 Windows 脚本运行组件,无法连接 DxDesigner。",
"quick_run_path_length": "执行目录过长,请使用较短的工具及数据目录。",
"quick_run_path_length": "无法建立长路径兼容入口,请查看详细错误及当前用户目录的写入权限。",
"quick_run_command": "替换命令文件无效,请查看日志。",
"quick_run_uncertain": "无法确认本次替换结果,请使用“核验并恢复中断任务”,不要直接清锁重跑。",
"quick_run_recovery": "中断任务恢复未通过,原保护状态仍保留。",
@@ -172,6 +172,7 @@ class ProjectPlanPanel(QWidget):
self.export_button = QPushButton('导出位号计划', objectName='exportTargetPlan')
self.import_bom_button = QPushButton('导入 BOM', objectName='importBomPlan')
self.export_bom_button = QPushButton('BOM 模板', objectName='exportBomTemplate')
self.export_bom_button.setToolTip('下载空白 BOM 模板,无需创建任务或采集位号')
self.select_all = QPushButton('全部替换')
self.select_none = QPushButton('全部保留')
self.bulk_part = QLineEdit(objectName='bulkTargetPart')
@@ -269,7 +270,7 @@ class ProjectPlanPanel(QWidget):
self._summary()
self.window._update_gates()
def set_plan_editable(self, editable):
def set_plan_editable(self, editable, *, busy=False):
self._editable = bool(editable)
self.table.set_plan_editable(self._editable)
for widget in (self.collect_button, self.save_button, self.import_button, self.import_bom_button,
@@ -277,8 +278,7 @@ class ProjectPlanPanel(QWidget):
widget.setEnabled(self._editable and bool(self.task_id))
self.export_button.setEnabled(self._editable and bool(self.task_id)
and bool(self.table.rows()) and not self.table.dirty)
self.export_bom_button.setEnabled(self._editable and bool(self.task_id)
and bool(self.table.rows()) and not self.table.dirty)
self.export_bom_button.setEnabled(not busy)
def _dispatch(self, operation, callback, button):
self.window._run_async(operation, callback, button, expected_task_id=self.task_id)
@@ -349,10 +349,7 @@ class ProjectPlanPanel(QWidget):
self._changed()
def export_bom(self):
if not self.task_id or self.table.dirty:
return
path, _ = QFileDialog.getSaveFileName(self, '导出 BOM 模板', '替换BOM模板.xlsx', 'Excel (*.xlsx)')
if path:
task_id = self.task_id
self._dispatch(lambda: self.window.service.export_bom_template(task_id, Path(path)),
self._dispatch(lambda: self.window.service.export_bom_template(None, Path(path)),
lambda result: self.summary.setText(f'已导出 BOM 模板:{result}'), self.export_bom_button)
@@ -1 +1 @@
VERSION = "1.1.1"
VERSION = "1.1.2"
@@ -159,7 +159,7 @@ class _OwnedWorkers:
def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abort_event=None,
process_factory=None) -> subprocess.CompletedProcess[str]:
root = Path(command[3])
root = Path(command[3]).resolve()
job_id = command[-1]
token = uuid4().hex
ready = root / f'monitor-{token}.ready'
+35
View File
@@ -62,6 +62,41 @@ def test_long_evidence_path_remains_visible_to_real_vbs(tmp_path):
assert result.returncode == 0 and result.stdout.strip() == 'True'
@pytest.mark.skipif(os.name != 'nt', reason='Windows VBS path compatibility')
def test_long_evidence_without_83_names_is_readable_and_writable_by_real_vbs(tmp_path, monkeypatch):
import ctypes
from pathlib import Path
from types import SimpleNamespace
from dx_productivity.trial_task_center.quick_run import _vbs_worker_paths, _resolve_cscript
# Reproduce a Windows volume without usable 8.3 names.
monkeypatch.setattr(ctypes, 'WinDLL', lambda *args, **kwargs:
SimpleNamespace(GetShortPathNameW=lambda *args: 0))
root = tmp_path / ('evidence-' + 'x' * 80) / ('discovery-' + 'y' * 60)
root.mkdir(parents=True)
script = root / 'QuickPartReplace.vbs'
script.write_text('Set f=CreateObject("Scripting.FileSystemObject")\n'
'WScript.Echo CStr(f.FileExists(f.BuildPath(WScript.Arguments(0), WScript.Arguments(1))))\n'
'Set s=f.CreateTextFile(f.BuildPath(WScript.Arguments(0), "written-by-vbs.txt"),True)\n'
's.Write "saved"\ns.Close\n')
marker = 'monitor-' + 'a' * 32 + '.ready'
(root / marker).write_text('token')
assert len(str(root / marker)) > 259
script_arg, root_arg = _vbs_worker_paths(script, root)
try:
assert len(root_arg) + 100 < 260
assert Path(root_arg).resolve() == root.resolve()
assert _vbs_worker_paths(script, root) == (script_arg, root_arg)
result = subprocess.run((str(_resolve_cscript()), '//nologo', script_arg, root_arg, marker),
capture_output=True, text=True, timeout=10)
assert result.returncode == 0 and result.stdout.strip() == 'True'
assert (root / 'written-by-vbs.txt').read_text() == 'saved'
finally:
from dx_productivity.trial_task_center.legacy_paths import cleanup_worker_aliases
cleanup_worker_aliases()
assert root.is_dir() and (root / marker).read_text() == 'token'
assert not Path(root_arg).exists()
def test_external_status_append_blocks_next_worker_before_cad_write(tmp_path):
from pathlib import Path
from threading import Event
+16
View File
@@ -12,6 +12,22 @@ from dx_productivity.trial_task_center import isolated_cad as runtime
from dx_productivity.trial_task_center.worker_monitor import WorkerMonitorError
@pytest.mark.skipif(os.name != 'nt', reason='Windows junction path handling')
def test_private_evidence_uses_canonical_root_behind_a_legacy_alias(tmp_path):
from dx_productivity.trial_task_center.legacy_paths import _AliasPool
root = tmp_path / ('nested-' + 'x' * 90) / ('nested-' + 'y' * 90)
root.mkdir(parents=True)
pool = _AliasPool()
try:
alias = pool.alias(root.resolve())
session = runtime.IsolatedCadSession(alias)
session._record(state='starting')
assert session.root == root.resolve()
assert (root / 'private-desktop-sessions' / (session.token + '.json')).is_file()
finally:
assert not pool.close()
@pytest.mark.skipif(os.name != 'nt', reason='Windows state-file sharing semantics')
def test_private_record_survives_a_reader_temporarily_denying_replacement(tmp_path):
import win32con
+31 -1
View File
@@ -52,11 +52,12 @@ def test_original_window_edits_target_plan_and_nc_without_export(qtbot, tmp_path
qtbot.addWidget(window)
window.open_task(task.task_id)
qtbot.waitUntil(lambda: not window._loading and not window._context_query.busy)
assert '1.1.1' in window.windowTitle()
assert '1.1.2' in window.windowTitle()
table = window.plan_panel.table
table.item(0, 0).setCheckState(Qt.CheckState.Checked)
table.item(0, 9).setCheckState(Qt.CheckState.Unchecked)
assert not window.run_panel.quick_run_button.isEnabled()
assert window.plan_panel.export_bom_button.isEnabled()
window.plan_panel.save()
qtbot.waitUntil(lambda: not window._workers, timeout=5000)
qtbot.waitUntil(lambda: not window._loading and not window._context_query.busy)
@@ -123,10 +124,39 @@ def test_project_plan_exposes_bom_import_and_template_actions(qtbot, tmp_path):
qtbot.waitUntil(lambda: not window._loading and not window._context_query.busy)
assert window.findChild(QPushButton, 'importBomPlan').text() == '导入 BOM'
assert window.findChild(QPushButton, 'exportBomTemplate').text() == 'BOM 模板'
assert window.plan_panel.export_bom_button.isEnabled()
assert not window.task_list.filter.isVisible()
window.close(); store.close()
def test_blank_bom_can_be_downloaded_without_task_or_inventory(qtbot, tmp_path, monkeypatch):
from openpyxl import load_workbook
from PySide6.QtWidgets import QFileDialog
from dx_productivity.trial_task_center.bom_plan import BOM_HEADERS
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
store = TaskStore(tmp_path / 'tasks.db')
service = TaskCenterService(store, configure_logging(tmp_path / 'data'))
window = TrialTaskCenterWindow(service)
qtbot.addWidget(window)
qtbot.waitUntil(lambda: not window._task_query.busy)
output = tmp_path / 'blank-bom.xlsx'
monkeypatch.setattr(QFileDialog, 'getSaveFileName', lambda *args: (str(output), 'Excel (*.xlsx)'))
assert window.plan_panel.export_bom_button.isEnabled()
window.plan_panel.export_bom_button.click()
qtbot.waitUntil(lambda: not window._workers and output.exists())
workbook = load_workbook(output)
try:
assert tuple(cell.value for cell in workbook.active[1]) == BOM_HEADERS
assert workbook.active.max_row == 1
finally:
workbook.close()
window.close()
store.close()
def test_batch_rules_and_target_plan_are_above_project_summary(qtbot, tmp_path):
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
+70
View File
@@ -0,0 +1,70 @@
"""Read a disposable project with long evidence paths and no usable 8.3 names."""
import argparse
import json
from pathlib import Path
import re
import shutil
import sys
import time
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'src'))
from dx_productivity.trial_task_center import legacy_paths
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
from private_desktop_observer import PrivateDesktopObserver
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--source', type=Path, required=True)
parser.add_argument('--library', type=Path, required=True)
parser.add_argument('--output', type=Path, required=True)
parser.add_argument('--old', default='4100-CA3300-T7')
args = parser.parse_args()
output, source = args.output.resolve(), args.source.resolve(strict=True)
assert not output.is_relative_to(source.parent)
assert args.library.is_file()
output.mkdir(parents=True, exist_ok=False)
shutil.copytree(source.parent, output / 'project')
project = output / 'project' / source.name
text, count = re.subn(r'(?m)^KEY CentralLibrary .*$',
lambda _: f'KEY CentralLibrary "{args.library.resolve().as_posix()}"',
project.read_text(encoding='utf-8-sig'))
assert count == 1
project.write_text(text, encoding='utf-8')
observed = output / ('evidence-' + 'x' * 60) / ('deep-' + 'y' * 60)
original_short_path = legacy_paths._short_path
legacy_paths._short_path = lambda _: None # Do not alter Windows settings.
links = []
try:
with PrivateDesktopObserver(observed):
started = time.perf_counter()
result = QuickRunPreparer(observed / 'independent-read')._discover_project_sheets(
project, (args.old,), collect_components=True)
elapsed = time.perf_counter() - started
assert result.sheets and result.components
links = list(legacy_paths._aliases.links)
assert links and all(link.is_junction() for link in links)
evidence = next((observed / 'independent-read/quick-run-history').glob('sheet-discovery-*'))
assert len(str(evidence / 'components.tsv')) > 259
session = json.loads((evidence / 'private-desktop.json').read_text(encoding='utf-8'))
assert session['state'] == 'released' and session['clean']
observation = json.loads((observed / 'desktop-observation.json').read_text(encoding='utf-8'))
assert not observation['observer_errors'] and all(observation['cad_exit_confirmed'].values())
assert all(observation['desktop_absent'].values())
assert not observation['owned_cad_became_foreground'] and not observation['owned_cad_on_input_desktop']
assert not legacy_paths.cleanup_worker_aliases()
assert all(not link.exists() for link in links)
assert (evidence / 'components.tsv').is_file()
report = {'passed': True, 'seconds': elapsed, 'sheets': list(result.sheets),
'component_count': len(result.components), 'evidence_path_length': len(str(evidence)),
'alias_paths': [str(link) for link in links], 'aliases_removed': True,
'original_evidence_retained': True, 'session': session}
(output / 'report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
print(json.dumps(report, ensure_ascii=False), flush=True)
finally:
legacy_paths._short_path = original_short_path
legacy_paths.cleanup_worker_aliases()
if __name__ == '__main__':
main()