fix: preserve deep project scans and orphan recovery protection

This commit is contained in:
阿白叔 committed 2026-10-23 16:57:49 +08:00
1 parent 2a90201bfa
commit 3367bb6454
5 files changed
+116 -32

No files matched your search

@@ -11,19 +11,20 @@ import stat
from uuid import uuid4
from .errors import 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
def _validated_root(root: Path, excluded_roots: tuple[Path, ...]) -> tuple[Path, tuple[Path, ...]]:
root = Path(os.path.abspath(root))
root = Path(os.path.abspath(strip_extended_prefix(root)))
for ancestor in (*reversed(root.parents), root):
_reject_reparse(ancestor.lstat(), ancestor)
root = root.resolve(strict=True)
if not root.is_dir():
_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")
excluded = tuple(Path(path).resolve(strict=False) for path in excluded_roots)
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")
return root, excluded
@@ -49,9 +50,9 @@ def scan_project_directory(root: Path, *, excluded_roots: tuple[Path, ...] = (),
while pending:
check_cancelled()
directory = pending.pop()
_reject_reparse(directory.lstat(), directory)
_reject_reparse(internal_path(directory).lstat(), directory)
children = []
with os.scandir(directory) as entries:
with os.scandir(internal_path(directory)) as entries:
for entry in entries:
check_cancelled()
children.append(entry)
@@ -59,7 +60,7 @@ def scan_project_directory(root: Path, *, excluded_roots: tuple[Path, ...] = (),
folders: list[Path] = []
for entry in sorted(children, key=lambda item: item.name.casefold()):
check_cancelled()
path = Path(entry.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)
@@ -67,7 +68,7 @@ def scan_project_directory(root: Path, *, excluded_roots: tuple[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(path.resolve(strict=True))
projects.append(canonical_path(path, strict=True))
found.extend(projects)
visited += 1
if on_progress is not None:
@@ -82,15 +83,15 @@ def _validate_selected(root: Path, selected_paths: tuple[Path, ...], excluded: t
selected: set[Path] = set()
ancestor_projects: dict[Path, bool] = {}
for candidate in selected_paths:
path = Path(os.path.abspath(candidate))
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):
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(cursor.lstat(), cursor)
if not path.is_file() or path.suffix.casefold() != ".prj" or not _is_schematic_project(path):
_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")
# A project in any ancestor directory stops discovery below that directory.
directory = path.parent
@@ -98,9 +99,9 @@ def _validate_selected(root: Path, selected_paths: tuple[Path, ...], excluded: t
directory = directory.parent
if directory not in ancestor_projects:
has_project = False
with os.scandir(directory) as entries:
with os.scandir(internal_path(directory)) as entries:
for entry in entries:
sibling = Path(entry.path)
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)
@@ -111,7 +112,7 @@ def _validate_selected(root: Path, selected_paths: tuple[Path, ...], excluded: t
ancestor_projects[directory] = has_project
if ancestor_projects[directory]:
raise TaskCenterError("project_selection", "selected project is hidden by an ancestor project")
selected.add(path.resolve(strict=True))
selected.add(canonical_path(path, strict=True))
return tuple(sorted(selected, key=lambda path: str(path).casefold()))
@@ -120,7 +121,7 @@ def create_project_tasks(store: TaskStore, root: Path, *, selected_paths: tuple[
root, excluded = _validated_root(root, excluded_roots)
discovered = (scan_project_directory(root, excluded_roots=excluded) if selected_paths is None
else _validate_selected(root, selected_paths, excluded))
active_paths = {project.path.resolve(strict=False) for task in store.list_tasks()
active_paths = {canonical_path(project.path) for task in store.list_tasks()
if task.status not in {TaskStatus.DELETED, TaskStatus.COMPLETED}
for project in store.list_projects(task.task_id)}
pending = [path for path in discovered if path not in active_paths]
@@ -8,10 +8,11 @@ import re
import stat
from .errors import TaskCenterError
from .path_access import canonical_path, internal_path, strip_extended_prefix
def _path_identity(path: Path) -> str:
normalized = os.path.normpath(str(path))
normalized = os.path.normpath(strip_extended_prefix(path))
return os.path.normcase(normalized) if os.name == "nt" else normalized
@@ -22,7 +23,7 @@ _ICDB_DIRECTORY = re.compile(rb'^\s*KEY\s+iCDBDir\s+"[^"]+"\s*$', re.IGNORECASE
def _is_schematic_project(path: Path) -> bool:
with path.open("rb") as project_file:
with internal_path(path).open("rb") as project_file:
contents = project_file.read(_PROJECT_HEADER_LIMIT)
return bool(_DXD_FRONT_END.search(contents) and _ICDB_DIRECTORY.search(contents))
@@ -46,13 +47,13 @@ def _lexical_path(path: Path) -> str:
def scan_projects(root: Path, *, excluded_roots: tuple[Path, ...] = ()) -> tuple[Path, ...]:
"""Discover DxDesigner schematic projects without selecting or modifying them."""
root = Path(root)
root = Path(strip_extended_prefix(root))
try:
if not root.exists() or not root.is_dir():
if not internal_path(root).exists() or not internal_path(root).is_dir():
raise TaskCenterError("discovery_root", f"discovery root is not a directory: {root}")
root_details = root.lstat()
root_details = internal_path(root).lstat()
_reject_reparse(root_details, root)
canonical_root = root.resolve()
canonical_root = canonical_path(root)
excluded = tuple(_lexical_path(Path(path)) for path in excluded_roots)
root_key = _lexical_path(root)
if any(root_key == blocked or root_key.startswith(blocked + os.sep) for blocked in excluded):
@@ -66,10 +67,10 @@ def scan_projects(root: Path, *, excluded_roots: tuple[Path, ...] = ()) -> tuple
visited: set[tuple[int, int]] = set()
def read_entries(directory: Path) -> tuple[tuple[Path, os.stat_result], ...]:
with os.scandir(directory) as entries:
with os.scandir(internal_path(directory)) as entries:
result: list[tuple[Path, os.stat_result]] = []
for entry in sorted(entries, key=lambda item: item.name.casefold()):
candidate = Path(entry.path)
candidate = Path(strip_extended_prefix(entry.path))
if is_excluded(candidate):
continue
entry_details = entry.stat(follow_symlinks=False)
@@ -84,7 +85,7 @@ def scan_projects(root: Path, *, excluded_roots: tuple[Path, ...] = ()) -> tuple
and candidate.suffix.casefold() == ".prj"
and _is_schematic_project(candidate)
):
canonical = candidate.resolve()
canonical = canonical_path(candidate)
candidates.setdefault(_path_identity(canonical), canonical)
if candidates:
@@ -94,10 +95,10 @@ def scan_projects(root: Path, *, excluded_roots: tuple[Path, ...] = ()) -> tuple
directory: Path,
directory_entries: tuple[tuple[Path, os.stat_result], ...] | None = None,
) -> None:
canonical_directory = directory.resolve()
canonical_directory = canonical_path(directory)
if not _contained(canonical_root, canonical_directory):
raise TaskCenterError("discovery_containment", f"discovery path escapes its root: {directory}")
details = directory.lstat()
details = internal_path(directory).lstat()
_reject_reparse(details, directory)
identity = details.st_dev, details.st_ino
if identity in visited:
@@ -112,7 +113,7 @@ def scan_projects(root: Path, *, excluded_roots: tuple[Path, ...] = ()) -> tuple
and candidate.suffix.casefold() == ".prj"
and _is_schematic_project(candidate)
):
canonical = candidate.resolve()
canonical = canonical_path(candidate)
if not _contained(canonical_root, canonical):
raise TaskCenterError("discovery_containment", f"project path escapes its root: {candidate}")
candidates.setdefault(_path_identity(canonical), canonical)
@@ -2,6 +2,7 @@
from dataclasses import dataclass
from .models import ProjectStatus, TaskStatus
from .path_access import internal_path
@dataclass(frozen=True)
@@ -45,7 +46,7 @@ def _archive(service):
for project in store.list_projects(task.task_id)):
reason = '人工流程尚未结束;重新打开后完成核验。'
elif (service.has_interrupted_quick_run(task.task_id) or
(service._project_task_service(task.task_id)._quick_run_preparer.data_root
internal_path(service._project_task_service(task.task_id)._quick_run_preparer.data_root
/ 'quick-run' / 'uncertain.flag').exists()):
reason = '存在中断、保护或待核验结果;重新打开后使用“核验并恢复”。'
if reason:
+4 -3
View File
@@ -7,6 +7,7 @@ import subprocess
import pytest
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.path_access import strip_extended_prefix
from dx_productivity.trial_task_center.scanner import scan_projects
@@ -58,7 +59,7 @@ def test_scan_projects_stops_at_selected_project_directory_when_it_contains_prj_
real_scandir = os.scandir
def reject_nested(path: str | bytes | int) -> object:
if Path(path) != root:
if Path(strip_extended_prefix(path)) != root:
raise AssertionError(f"unexpected nested scan: {path}")
return real_scandir(path)
@@ -84,7 +85,7 @@ def test_scan_projects_reads_batch_root_once_before_recursive_fallback(
def count_root(path: str | bytes | int) -> object:
nonlocal root_reads
if Path(path) == root:
if Path(strip_extended_prefix(path)) == root:
root_reads += 1
return real_scandir(path)
@@ -138,7 +139,7 @@ def test_scan_projects_turns_inaccessible_subtree_errors_into_explicit_task_erro
real_scandir = __import__("os").scandir
def deny(path: str | bytes | int) -> object:
if Path(path) == denied:
if Path(strip_extended_prefix(path)) == denied:
raise PermissionError("denied subtree")
return real_scandir(path)
@@ -0,0 +1,80 @@
import os
from pathlib import Path
import pytest
from dx_productivity.trial_task_center.path_access import internal_path
@pytest.fixture
def deep_windows_tree(tmp_path, monkeypatch):
if os.name != 'nt':
pytest.skip('real Windows long paths')
root = tmp_path / ('projects-' + 'x' * 105) / ('revision-' + 'y' * 100)
assert len(str(root)) > 260
internal_path(root).mkdir(parents=True)
def legacy_failure(path):
return len(os.fspath(path)) >= 260 and not os.fspath(path).startswith(chr(92) * 2 + '?')
for name in ('stat', 'open', 'resolve'):
original = getattr(Path, name)
def strict(path, *args, _original=original, **kwargs):
if legacy_failure(path):
raise FileNotFoundError(2, 'MAX_PATH host cannot access unprefixed deep path')
return _original(path, *args, **kwargs)
monkeypatch.setattr(Path, name, strict)
original_scandir = os.scandir
def scandir(path):
if not isinstance(path, int) and legacy_failure(path):
raise FileNotFoundError(2, 'MAX_PATH host cannot scan unprefixed deep path')
return original_scandir(path)
monkeypatch.setattr(os, 'scandir', scandir)
return root
def test_deep_schematic_scan_keeps_canonical_projects_exclusions_and_progress(deep_windows_tree):
from dx_productivity.trial_task_center.scanner import scan_projects
from dx_productivity.trial_task_center.project_tasks import scan_project_directory, _validate_selected
root = deep_windows_tree
project = root / 'selected/board.prj'
excluded = root / 'excluded'
for path in (project, excluded / 'hidden.prj'):
internal_path(path.parent).mkdir(parents=True, exist_ok=True)
internal_path(path).write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n', encoding='utf-8')
assert scan_projects(root, excluded_roots=(excluded,)) == (project,)
progress = []
assert scan_project_directory(root, excluded_roots=(excluded,), on_progress=lambda directory, *_: progress.append(directory)) == (project,)
assert progress and all(path.is_relative_to(root) for path in progress)
assert _validate_selected(root, (project,), (excluded,)) == (project,)
def test_deep_orphan_uncertainty_flag_retains_task_without_handoff(deep_windows_tree, tmp_path, monkeypatch):
from types import SimpleNamespace
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.task_archive import archive_completed_session
store = TaskStore(tmp_path / 'tasks.db')
context = configure_logging(tmp_path / 'logs')
service = TaskCenterService(store, context)
task = service.create_task('protected')
root = deep_windows_tree
marker = root / 'quick-run/uncertain.flag'
internal_path(marker.parent).mkdir(parents=True)
internal_path(marker).write_text('needs verification', encoding='utf-8')
monkeypatch.setattr(service, 'pending_batch_resources', lambda: ())
monkeypatch.setattr(service, 'has_interrupted_quick_run', lambda task_id: False)
facade = SimpleNamespace(_quick_run_preparer=SimpleNamespace(data_root=root))
monkeypatch.setattr(service, '_project_task_service', lambda task_id: facade)
try:
report = archive_completed_session(service)
assert report.archived_ids == ()
assert report.retained_ids == (task.task_id,)
assert [item.task_id for item in service.tasks()] == [task.task_id]
assert internal_path(marker).read_text(encoding='utf-8') == 'needs verification'
assert not internal_path(marker.with_name('command.tsv')).exists()
finally:
store.close()
for handler in tuple(context.logger.handlers):
handler.close()
context.logger.removeHandler(handler)