fix: report actionable project path errors
Core regression / Python core, intervention UI and release configuration (push) Successful in 4m25s
Core regression / JavaScript syntax (push) Successful in 8s
Core regression / Python core, intervention UI and release configuration (pull_request) Successful in 5m7s
Core regression / JavaScript syntax (pull_request) Successful in 7s

This commit is contained in:
阿白叔 committed 2026-11-25 09:49:54 +08:00
1 parent 46deb9cec8
commit d954b527f5
7 files changed
+261 -38

No files matched your search

@@ -27,3 +27,7 @@ class TaskCenterError(ValueError):
def _new_error_id() -> str:
date = datetime.now(timezone.utc).strftime("%Y%m%d")
return f"DXT-{date}-{secrets.token_hex(4).upper()}"
class ProjectPathError(TaskCenterError):
"""An expected filesystem failure while reading or selecting projects."""
@@ -17,7 +17,7 @@ import time
import traceback
from typing import Any, Mapping
from .errors import TaskCenterError
from .errors import ProjectPathError, TaskCenterError
from .path_access import internal_path
from .retention import rotate_text_log
@@ -62,15 +62,18 @@ class LoggingContext:
reported = error
else:
reported = TaskCenterError("unhandled_exception", "发生未处理异常")
detail = "".join(
traceback.format_exception(type(error), error, traceback_object or error.__traceback__)
)
message = reported.message
if not isinstance(error, ProjectPathError):
detail = "".join(
traceback.format_exception(type(error), error, traceback_object or error.__traceback__)
)
message += "\n" + detail.rstrip()
self.logger.error(
"error_id=%s operation=%s message=%s\n%s",
"error_id=%s operation=%s code=%s message=%s",
reported.error_id,
operation,
reported.message,
detail.rstrip(),
reported.code,
message,
)
_flush_handlers(self.logger)
return reported
@@ -3,6 +3,7 @@
from __future__ import annotations
from collections.abc import Callable
from contextlib import contextmanager
from threading import Event
import os
@@ -10,20 +11,44 @@ from pathlib import Path
import stat
from uuid import uuid4
from .errors import TaskCenterError
from .errors import ProjectPathError, TaskCenterError
from .path_access import canonical_path, internal_path, strip_extended_prefix
from .models import TaskRecord, TaskStatus
from .scanner import _is_schematic_project, _reject_reparse
from .store import TaskStore
@contextmanager
def _path_errors(path: Path):
try:
yield
except FileNotFoundError as error:
raise ProjectPathError(
"path_missing", f"找不到路径「{path}」。请确认目录或工程是否已移动或删除,然后重新选择并读取。"
) from error
except PermissionError as error:
raise ProjectPathError(
"path_denied", f"无法读取路径「{path}」。请检查当前用户的读取权限,然后重试。"
) from error
except NotADirectoryError as error:
raise _not_directory(path) from error
def _not_directory(path: Path) -> ProjectPathError:
return ProjectPathError(
"path_not_directory", f"路径「{path}」中有一项不是目录。请选择工程目录后重试。"
)
def _validated_root(root: Path, excluded_roots: tuple[Path, ...]) -> tuple[Path, tuple[Path, ...]]:
root = Path(os.path.abspath(strip_extended_prefix(root)))
for ancestor in (*reversed(root.parents), root):
_reject_reparse(internal_path(ancestor).lstat(), ancestor)
root = canonical_path(root, strict=True)
if not internal_path(root).is_dir():
raise TaskCenterError("discovery_root", "project root is not a directory")
with _path_errors(root):
for ancestor in (*reversed(root.parents), root):
details = internal_path(ancestor).lstat()
_reject_reparse(details, ancestor)
if not stat.S_ISDIR(details.st_mode):
raise _not_directory(root)
root = canonical_path(root, strict=True)
excluded = tuple(canonical_path(path) for path in excluded_roots)
if any(root.is_relative_to(blocked) for blocked in excluded):
raise TaskCenterError("discovery_root", "project root is inside an excluded directory")
@@ -50,12 +75,13 @@ def scan_project_directory(root: Path, *, excluded_roots: tuple[Path, ...] = (),
while pending:
check_cancelled()
directory = pending.pop()
_reject_reparse(internal_path(directory).lstat(), directory)
children = []
with os.scandir(internal_path(directory)) as entries:
for entry in entries:
check_cancelled()
children.append(entry)
with _path_errors(directory):
_reject_reparse(internal_path(directory).lstat(), directory)
with os.scandir(internal_path(directory)) as entries:
for entry in entries:
check_cancelled()
children.append(entry)
projects: list[Path] = []
folders: list[Path] = []
for entry in sorted(children, key=lambda item: item.name.casefold()):
@@ -63,12 +89,13 @@ def scan_project_directory(root: Path, *, excluded_roots: tuple[Path, ...] = (),
path = Path(strip_extended_prefix(entry.path))
if any(path.is_relative_to(blocked) for blocked in excluded):
continue
details = entry.stat(follow_symlinks=False)
_reject_reparse(details, path)
if stat.S_ISDIR(details.st_mode):
folders.append(path)
elif stat.S_ISREG(details.st_mode) and path.suffix.casefold() == ".prj" and _is_schematic_project(path):
projects.append(canonical_path(path, strict=True))
with _path_errors(path):
details = entry.stat(follow_symlinks=False)
_reject_reparse(details, path)
if stat.S_ISDIR(details.st_mode):
folders.append(path)
elif stat.S_ISREG(details.st_mode) and path.suffix.casefold() == ".prj" and _is_schematic_project(path):
projects.append(canonical_path(path, strict=True))
found.extend(projects)
visited += 1
if on_progress is not None:
@@ -84,35 +111,41 @@ def _validate_selected(root: Path, selected_paths: tuple[Path, ...], excluded: t
ancestor_projects: dict[Path, bool] = {}
for candidate in selected_paths:
path = Path(os.path.abspath(strip_extended_prefix(candidate)))
if not path.is_relative_to(root) or any(path.is_relative_to(blocked) for blocked in excluded):
if path == root or not path.is_relative_to(root) or any(path.is_relative_to(blocked) for blocked in excluded):
raise TaskCenterError("project_selection", "selected project is outside discovery results")
relative = path.relative_to(root)
cursor = root
for part in relative.parts:
cursor /= part
_reject_reparse(internal_path(cursor).lstat(), cursor)
if not internal_path(path).is_file() or path.suffix.casefold() != ".prj" or not _is_schematic_project(path):
raise TaskCenterError("project_selection", "selected file is not a schematic project")
with _path_errors(path):
for part in relative.parts:
cursor /= part
details = internal_path(cursor).lstat()
_reject_reparse(details, cursor)
if cursor != path and not stat.S_ISDIR(details.st_mode):
raise _not_directory(path)
if not stat.S_ISREG(details.st_mode) or path.suffix.casefold() != ".prj" or not _is_schematic_project(path):
raise TaskCenterError("project_selection", "selected file is not a schematic project")
# A project in any ancestor directory stops discovery below that directory.
directory = path.parent
while directory != root:
directory = directory.parent
if directory not in ancestor_projects:
has_project = False
with os.scandir(internal_path(directory)) as entries:
with _path_errors(directory), os.scandir(internal_path(directory)) as entries:
for entry in entries:
sibling = Path(strip_extended_prefix(entry.path))
if sibling.suffix.casefold() != ".prj" or any(sibling.is_relative_to(b) for b in excluded):
continue
details = entry.stat(follow_symlinks=False)
_reject_reparse(details, sibling)
if stat.S_ISREG(details.st_mode) and _is_schematic_project(sibling):
has_project = True
break
with _path_errors(sibling):
details = entry.stat(follow_symlinks=False)
_reject_reparse(details, sibling)
if stat.S_ISREG(details.st_mode) and _is_schematic_project(sibling):
has_project = True
break
ancestor_projects[directory] = has_project
if ancestor_projects[directory]:
raise TaskCenterError("project_selection", "selected project is hidden by an ancestor project")
selected.add(canonical_path(path, strict=True))
with _path_errors(path):
selected.add(canonical_path(path, strict=True))
return tuple(sorted(selected, key=lambda path: str(path).casefold()))
@@ -3,6 +3,8 @@ from datetime import datetime
import json
import re
from ..errors import ProjectPathError
ERROR_TEXT = {
"dsh_startup": "DSH助手启动失败,请检查发布包中的运行时和 Node.js。",
'user_forced_stop': '操作已强制中断,结果待核验。',
@@ -57,6 +59,8 @@ ERROR_TEXT = {
def format_operation_error(error):
if isinstance(error, ProjectPathError):
return f'{error.message}\n错误代码:{error.code} · 错误编号:{error.error_id}'
title = ERROR_TEXT.get(error.code, '操作未完成')
report = getattr(error, 'bom_report', None)
if report is not None:
@@ -19,6 +19,8 @@ from .workers import ServiceWorker
from .operation_state import OperationPhase
from .command_menu import CommandMenu
from .icons import icon
from .messages import format_operation_error
from ..errors import ProjectPathError
from ..bom_import_state import BomImportMachine, BomImportPhase, BomImportState
from ..bom_pending import retained_bom_rows
@@ -44,6 +46,9 @@ class DirectoryTaskDialog(QDialog):
self.scan = QPushButton('读取工程', objectName='readTaskProjects')
self.projects = QListWidget(objectName='taskProjectCandidates')
self.summary = QLabel('先读取工程,再勾选需要创建任务的项目。')
self.summary.setWordWrap(True)
self.summary.setTextFormat(Qt.TextFormat.PlainText)
self.summary.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
self.buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
self.buttons.button(QDialogButtonBox.StandardButton.Ok).setText('创建任务')
self.buttons.button(QDialogButtonBox.StandardButton.Ok).setEnabled(False)
@@ -137,7 +142,10 @@ class DirectoryTaskDialog(QDialog):
if self._closed:
return
self._scanned_root = None
self.summary.setText(getattr(error, 'message', str(error)))
if isinstance(error, ProjectPathError):
self.summary.setText(format_operation_error(error))
else:
self.summary.setText(getattr(error, 'message', str(error)))
def _finished(self):
self._worker = None