From 1719683fc3a8e4dd571753e0573232a6f5416186 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=98=BF=E7=99=BD=E5=8F=94?= <11794527+absfan@user.noreply.gitee.com> Date: Thu, 15 Oct 2026 09:27:46 +0800 Subject: [PATCH] Add cancellable directory scanning and targeted task validation --- .../trial_task_center/project_tasks.py | 104 +++++++++--- .../trial_task_center/ui/project_plan.py | 63 ++++++-- tests/v1_1/test_scan_responsiveness.py | 152 ++++++++++++++++++ 3 files changed, 289 insertions(+), 30 deletions(-) create mode 100644 tests/v1_1/test_scan_responsiveness.py diff --git a/src/dx_productivity/trial_task_center/project_tasks.py b/src/dx_productivity/trial_task_center/project_tasks.py index b596342..f49e734 100644 --- a/src/dx_productivity/trial_task_center/project_tasks.py +++ b/src/dx_productivity/trial_task_center/project_tasks.py @@ -2,6 +2,9 @@ from __future__ import annotations +from collections.abc import Callable +from threading import Event + import os from pathlib import Path import stat @@ -13,24 +16,51 @@ from .scanner import _is_schematic_project, _reject_reparse from .store import TaskStore -def scan_project_directory(root: Path, *, excluded_roots: tuple[Path, ...] = ()) -> tuple[Path, ...]: - root = Path(root) - _reject_reparse(root.lstat(), root) +def _validated_root(root: Path, excluded_roots: tuple[Path, ...]) -> tuple[Path, tuple[Path, ...]]: + root = Path(os.path.abspath(root)) + for ancestor in (*reversed(root.parents), root): + _reject_reparse(ancestor.lstat(), ancestor) root = root.resolve(strict=True) if not root.is_dir(): raise TaskCenterError("discovery_root", "project root is not a directory") - excluded = tuple(path.resolve(strict=False) for path in excluded_roots) - found: list[Path] = [] + excluded = tuple(Path(path).resolve(strict=False) 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 - def visit(directory: Path) -> None: + +def scan_project_directory(root: Path, *, excluded_roots: tuple[Path, ...] = (), + stop_event: Event | None = None, + on_progress: Callable[[Path, int, int], None] | None = None) -> tuple[Path, ...]: + """Scan cooperatively; cancellation raises rather than returning partial results. + + Progress reports (current directory, visited directories, discovered projects). + The callback runs on the scanning thread. + """ + def check_cancelled(): + if stop_event is not None and stop_event.is_set(): + raise TaskCenterError("discovery_cancelled", "directory scan cancelled") + + check_cancelled() + root, excluded = _validated_root(root, excluded_roots) + found: list[Path] = [] + pending = [root] + visited = 0 + while pending: + check_cancelled() + directory = pending.pop() _reject_reparse(directory.lstat(), directory) + children = [] with os.scandir(directory) as entries: - children = sorted(entries, key=lambda item: item.name.casefold()) + for entry in entries: + check_cancelled() + children.append(entry) projects: list[Path] = [] folders: list[Path] = [] - for entry in children: + for entry in sorted(children, key=lambda item: item.name.casefold()): + check_cancelled() path = Path(entry.path) - if any(path.resolve(strict=False).is_relative_to(blocked) for blocked in excluded): + if any(path.is_relative_to(blocked) for blocked in excluded): continue details = entry.stat(follow_symlinks=False) _reject_reparse(details, path) @@ -39,25 +69,61 @@ def scan_project_directory(root: Path, *, excluded_roots: tuple[Path, ...] = ()) elif stat.S_ISREG(details.st_mode) and path.suffix.casefold() == ".prj" and _is_schematic_project(path): projects.append(path.resolve(strict=True)) found.extend(projects) + visited += 1 + if on_progress is not None: + on_progress(directory, visited, len(found)) + check_cancelled() if not projects: - for folder in folders: - visit(folder) - - visit(root) + pending.extend(reversed(folders)) return tuple(found) +def _validate_selected(root: Path, selected_paths: tuple[Path, ...], excluded: tuple[Path, ...]) -> tuple[Path, ...]: + selected: set[Path] = set() + ancestor_projects: dict[Path, bool] = {} + for candidate in selected_paths: + path = Path(os.path.abspath(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): + 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(directory) as entries: + for entry in entries: + sibling = Path(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 + 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)) + return tuple(sorted(selected, key=lambda path: str(path).casefold())) + + def create_project_tasks(store: TaskStore, root: Path, *, selected_paths: tuple[Path, ...] | None = None, excluded_roots: tuple[Path, ...] = ()) -> tuple[TaskRecord, ...]: - root = Path(root).resolve(strict=True) - discovered = scan_project_directory(root, excluded_roots=excluded_roots) - selected = {path.resolve(strict=True) for path in selected_paths} if selected_paths is not None else set(discovered) - if not selected <= set(discovered): - raise TaskCenterError("project_selection", "selected project is outside discovery results") + 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() 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 in selected and path not in active_paths] + pending = [path for path in discovered if path not in active_paths] group_id = uuid4().hex created: list[TaskRecord] = [] with store.transaction(): diff --git a/src/dx_productivity/trial_task_center/ui/project_plan.py b/src/dx_productivity/trial_task_center/ui/project_plan.py index 9cebc99..fd6f95e 100644 --- a/src/dx_productivity/trial_task_center/ui/project_plan.py +++ b/src/dx_productivity/trial_task_center/ui/project_plan.py @@ -1,8 +1,10 @@ """Directory task creation and optional spreadsheet/direct plan editing.""" from pathlib import Path +from threading import Event +from time import monotonic -from PySide6.QtCore import Qt, QThreadPool +from PySide6.QtCore import Qt, QThreadPool, QObject, Signal, QSignalBlocker from PySide6.QtWidgets import (QDialog, QDialogButtonBox, QFileDialog, QHBoxLayout, QLabel, QLineEdit, QListWidget, QListWidgetItem, QMessageBox, QPushButton, QVBoxLayout, QWidget) @@ -12,6 +14,10 @@ from .target_table import TargetTable from .workers import ServiceWorker +class _ScanProgress(QObject): + changed = Signal(object, int, int) + + class DirectoryTaskDialog(QDialog): def __init__(self, service, parent=None): super().__init__(parent) @@ -37,6 +43,8 @@ class DirectoryTaskDialog(QDialog): layout.addWidget(self.summary) layout.addWidget(self.buttons) self._worker = None + self._stop_event = Event() + self._closed = False self._scanned_root = None self.browse.clicked.connect(self._browse) self.scan.clicked.connect(self.read_projects) @@ -56,20 +64,49 @@ class DirectoryTaskDialog(QDialog): self.buttons.button(QDialogButtonBox.StandardButton.Ok).setEnabled(False) def read_projects(self): - if self._worker is not None or not self.directory.text().strip(): + if self._worker is not None: + self._stop_event.set() + self.scan.setEnabled(False) + self.summary.setText('正在取消读取…') + return + if not self.directory.text().strip(): return root = Path(self.directory.text().strip()) self.directory.setEnabled(False) self.browse.setEnabled(False) - self.scan.setEnabled(False) + self.scan.setText('取消读取') + self.projects.clear() + self._scanned_root = None + self.buttons.button(QDialogButtonBox.StandardButton.Ok).setEnabled(False) self.summary.setText('正在读取工程…') - self._worker = ServiceWorker(lambda: self.service.scan_project_directory(root)) + self._stop_event = Event() + self._closed = False + service, stop_event = self.service, self._stop_event + progress = _ScanProgress() + progress.changed.connect(self._progress) + self._progress_signals = progress + last_report = 0.0 + def report(directory, visited, found): + nonlocal last_report + now = monotonic() + if now - last_report >= 0.1: + last_report = now + progress.changed.emit(directory, visited, found) + self._worker = ServiceWorker(lambda: service.scan_project_directory( + root, stop_event=stop_event, on_progress=report)) self._worker.signals.succeeded.connect(self._received) self._worker.signals.failed.connect(self._failed) self._worker.signals.finished.connect(self._finished) QThreadPool.globalInstance().start(self._worker) + def _progress(self, directory, visited, found): + if not self._closed and not self._stop_event.is_set(): + self.summary.setText(f'已读取 {visited} 个目录,发现 {found} 个工程;{directory}') + def _received(self, projects): + if self._closed or self._stop_event.is_set(): + return + blocker = QSignalBlocker(self.projects) self.projects.clear() self._scanned_root = Path(self.directory.text().strip()).resolve() for path in projects: @@ -79,14 +116,20 @@ class DirectoryTaskDialog(QDialog): item.setFlags(item.flags() | Qt.ItemFlag.ItemIsUserCheckable) item.setCheckState(Qt.CheckState.Checked) self.projects.addItem(item) + del blocker self._update_selection() def _failed(self, error): + if self._closed: + return self._scanned_root = None self.summary.setText(getattr(error, 'message', str(error))) def _finished(self): self._worker = None + if self._closed: + return + self.scan.setText('读取工程') self.directory.setEnabled(True) self.browse.setEnabled(True) self.scan.setEnabled(True) @@ -105,16 +148,14 @@ class DirectoryTaskDialog(QDialog): for i in range(self.projects.count()) if self.projects.item(i).checkState() == Qt.CheckState.Checked) def reject(self): - if self._worker is not None: - self.summary.setText('正在读取,请等当前扫描结束后关闭。') - return + self._closed = True + self._stop_event.set() super().reject() def closeEvent(self, event): - if self._worker is not None: - event.ignore() - else: - super().closeEvent(event) + self._closed = True + self._stop_event.set() + super().closeEvent(event) class ProjectPlanPanel(QWidget): diff --git a/tests/v1_1/test_scan_responsiveness.py b/tests/v1_1/test_scan_responsiveness.py new file mode 100644 index 0000000..845adea --- /dev/null +++ b/tests/v1_1/test_scan_responsiveness.py @@ -0,0 +1,152 @@ +from pathlib import Path +from contextlib import closing +from threading import Event + +import pytest + +from dx_productivity.trial_task_center import project_tasks +from dx_productivity.trial_task_center.errors import TaskCenterError +from dx_productivity.trial_task_center.store import TaskStore + + +def project(path): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n') + return path + + +def test_scan_cancel_discards_partial_results(tmp_path): + project(tmp_path / 'a' / 'a.prj') + project(tmp_path / 'b' / 'b.prj') + stop = Event() + updates = [] + def progress(directory, visited, found): + updates.append((directory, visited, found)) + if found: + stop.set() + with pytest.raises(TaskCenterError, match='cancel'): + project_tasks.scan_project_directory(tmp_path, stop_event=stop, on_progress=progress) + assert updates and updates[-1][2] == 1 + + +def test_selected_creation_does_not_walk_unrelated_subtree(tmp_path, monkeypatch): + root = tmp_path / 'root' + chosen = project(root / 'a' / 'b' / 'c' / 'board.prj') + project(root / 'unrelated' / 'board.prj') + original = project_tasks.os.scandir + def guarded(path): + assert Path(path) != root / 'unrelated' + return original(path) + monkeypatch.setattr(project_tasks.os, 'scandir', guarded) + with closing(TaskStore(tmp_path / 'tasks.db')) as store: + assert len(project_tasks.create_project_tasks(store, root, selected_paths=(chosen,))) == 1 + + +@pytest.mark.parametrize('kind', ['ancestor', 'excluded', 'invalid', 'outside']) +def test_selected_validation_is_atomic(tmp_path, kind): + root = tmp_path / 'root' + good = project(root / 'good' / 'board.prj') + bad = project(root / 'a' / 'deep' / 'bad.prj') + excluded = () + if kind == 'ancestor': + project(root / 'a' / 'ancestor.prj') + elif kind == 'excluded': + excluded = (root / 'a',) + elif kind == 'invalid': + bad.write_text('not a schematic') + else: + bad = project(tmp_path / 'outside' / 'bad.prj') + with closing(TaskStore(tmp_path / 'tasks.db')) as store: + with pytest.raises(TaskCenterError): + project_tasks.create_project_tasks(store, root, selected_paths=(good, bad), excluded_roots=excluded) + assert store.list_tasks() == () + + +def test_excluded_root_cannot_be_scanned(tmp_path): + project(tmp_path / 'board.prj') + with pytest.raises(TaskCenterError): + project_tasks.scan_project_directory(tmp_path, excluded_roots=(tmp_path,)) + +def test_dialog_cancel_closes_and_signals_worker(qtbot, tmp_path): + from threading import Event + from types import SimpleNamespace + from dx_productivity.trial_task_center.ui.project_plan import DirectoryTaskDialog + started = Event() + stopped = Event() + def scan(root, *, stop_event, on_progress): + on_progress(root, 3, 1) + started.set() + stop_event.wait(3) + stopped.set() + raise TaskCenterError('discovery_cancelled', 'cancelled') + dialog = DirectoryTaskDialog(SimpleNamespace(scan_project_directory=scan)) + qtbot.addWidget(dialog) + dialog.directory.setText(str(tmp_path)) + dialog.show() + dialog.read_projects() + qtbot.waitUntil(started.is_set) + qtbot.waitUntil(lambda: '3' in dialog.summary.text()) + dialog.reject() + assert not dialog.isVisible() + qtbot.waitUntil(stopped.is_set) + qtbot.waitUntil(lambda: dialog._worker is None) + assert dialog.projects.count() == 0 + + +def test_dialog_cancel_ignores_partial_success(qtbot, tmp_path): + from types import SimpleNamespace + from dx_productivity.trial_task_center.ui.project_plan import DirectoryTaskDialog + dialog = DirectoryTaskDialog(SimpleNamespace()) + qtbot.addWidget(dialog) + dialog.directory.setText(str(tmp_path)) + dialog._stop_event.set() + dialog._received((tmp_path / 'partial.prj',)) + assert dialog.projects.count() == 0 + +def test_selected_rechecks_each_ancestor_for_reparse(tmp_path, monkeypatch): + root = tmp_path / 'root' + chosen = project(root / 'a' / 'b' / 'c' / 'board.prj') + original = project_tasks._reject_reparse + def reject(details, path): + if path == root / 'a' / 'b': + raise TaskCenterError('discovery_reparse', 'reparse ancestor') + original(details, path) + monkeypatch.setattr(project_tasks, '_reject_reparse', reject) + with closing(TaskStore(tmp_path / 'tasks.db')) as store: + with pytest.raises(TaskCenterError, match='reparse'): + project_tasks.create_project_tasks(store, root, selected_paths=(chosen,)) + assert store.list_tasks() == () + + +def test_scan_pre_cancelled_does_not_touch_directory(tmp_path, monkeypatch): + stop = Event() + stop.set() + def unexpected(*args): + pytest.fail('cancelled scan touched disk') + monkeypatch.setattr(project_tasks.os, 'scandir', unexpected) + with pytest.raises(TaskCenterError, match='cancel'): + project_tasks.scan_project_directory(tmp_path, stop_event=stop) + +def test_scan_worker_can_finish_after_dialog_is_deleted(qtbot, tmp_path): + from types import SimpleNamespace + from shiboken6 import delete + from dx_productivity.trial_task_center.ui.project_plan import DirectoryTaskDialog + started, release, finished = Event(), Event(), Event() + def scan(root, *, stop_event, on_progress): + started.set() + release.wait(3) + on_progress(root, 1, 0) + finished.set() + return () + dialog = DirectoryTaskDialog(SimpleNamespace(scan_project_directory=scan)) + dialog.directory.setText(str(tmp_path)) + dialog.read_projects() + worker = dialog._worker + qtbot.waitUntil(started.is_set) + dialog.reject() + delete(dialog) + release.set() + qtbot.waitUntil(finished.is_set) + # Keep the worker alive while its queued completion signals are delivered. + qtbot.wait(20) + assert worker is not None