Skip to content

The only downloader you need. 下载器的集大成者。

refactor(filesystem): 路径是否存在改叫 isExisting

XiaoYouChR8cf0075bd8ef
diff --git a/app/platform/desktop.py b/app/platform/desktop.py
index ce855206..4c17931e 100644
--- a/app/platform/desktop.py
+++ b/app/platform/desktop.py
@@ -9,7 +9,7 @@ from PySide6.QtGui import QDesktopServices, QDrag
from PySide6.QtWidgets import QApplication, QWidget
from loguru import logger
-from app.platform.filesystem import probe
+from app.platform.filesystem import isExisting
def buildFontFamilies(locale: QLocale, defaultFamily: str) -> list[str]:
@@ -120,7 +120,7 @@ def openFolder(path: str | PathLike[str]) -> None:
def revealInFolder(path: str | PathLike[str]) -> None:
path = Path(path)
- if probe(path):
+ if isExisting(path):
match sys.platform:
case "win32":
if not _revealInFolderShell(path):
@@ -129,7 +129,7 @@ def revealInFolder(path: str | PathLike[str]) -> None:
QProcess.startDetached("open", ["-R", str(path)])
case _:
QProcess.startDetached("xdg-open", [str(path.parent)])
- elif probe(path.parent):
+ elif isExisting(path.parent):
openFolder(path.parent)
diff --git a/app/platform/filesystem.py b/app/platform/filesystem.py
index e274b36d..65a04fcd 100644
--- a/app/platform/filesystem.py
+++ b/app/platform/filesystem.py
@@ -18,7 +18,7 @@ WINDOWS_RESERVED_FILENAMES = {
}
-def probe(path: str | PathLike[str]) -> bool:
+def isExisting(path: str | PathLike[str]) -> bool:
try:
Path(path).stat()
except (OSError, ValueError):
@@ -26,7 +26,7 @@ def probe(path: str | PathLike[str]) -> bool:
return True
-def probeDirectory(path: str | PathLike[str]) -> bool:
+def isFolder(path: str | PathLike[str]) -> bool:
try:
return S_ISDIR(Path(path).stat().st_mode)
except (OSError, ValueError):
diff --git a/app/services/browser_service.py b/app/services/browser_service.py
index 6a19b50c..0a1cd12b 100644
--- a/app/services/browser_service.py
+++ b/app/services/browser_service.py
@@ -18,7 +18,7 @@ from loguru import logger
from app.config.cfg import cfg
from app.config.constants import LATEST_EXTENSION_VERSION, VERSION
from app.config.paths import APP_DATA_DIR
-from app.platform.filesystem import probe
+from app.platform.filesystem import isExisting
from app.signal import Signal
from app.update import isNewer
@@ -173,8 +173,8 @@ def toTaskSummary(task: Task) -> dict:
"speed": speed,
"createdAt": task.createdAt,
"canPause": task.canPause,
- "canOpenFile": probe(outputPath),
- "canOpenFolder": probe(outputPath.parent),
+ "canOpenFile": isExisting(outputPath),
+ "canOpenFolder": isExisting(outputPath.parent),
"fileExt": outputPath.suffix.lstrip(".").lower(),
"packName": task.packId,
}
@@ -600,7 +600,7 @@ class BrowserService:
elif action == TaskAction.OPEN_FILE:
path = Path(task.outputPath)
- if not probe(path):
+ if not isExisting(path):
self._sendResult(session, MessageType.TASK_ACTION_RESULT, requestId,
ok=False, message="文件尚未生成")
return
@@ -608,7 +608,7 @@ class BrowserService:
elif action == TaskAction.OPEN_FOLDER:
path = Path(task.outputPath)
- if not probe(path.parent):
+ if not isExisting(path.parent):
self._sendResult(session, MessageType.TASK_ACTION_RESULT, requestId,
ok=False, message="目录不存在")
return
diff --git a/app/services/task_service.py b/app/services/task_service.py
index ce9677da..ada9dfbb 100644
--- a/app/services/task_service.py
+++ b/app/services/task_service.py
@@ -12,7 +12,7 @@ from loguru import logger
from app.config.cfg import cfg
from app.config.paths import APP_DATA_DIR
-from app.platform.filesystem import probe, splitStemExt
+from app.platform.filesystem import isExisting, splitStemExt
from app.signal import Signal
if TYPE_CHECKING:
@@ -210,7 +210,7 @@ class TaskService:
def isTaken() -> bool:
op = task.outputPath
- return op in storePaths or probe(op) or probe(f"{op}.ghd")
+ return op in storePaths or isExisting(op) or isExisting(f"{op}.ghd")
if not isTaken():
return
@@ -318,7 +318,7 @@ class TaskService:
from app.models.task import TaskStatus
for task in self._store.loadSaved():
self.taskAdded.emit(task)
- if task.status == TaskStatus.COMPLETED and task.hasOutputFile and probe(task.outputPath):
+ if task.status == TaskStatus.COMPLETED and task.hasOutputFile and isExisting(task.outputPath):
self._watchFile(task)
elif task.status in {TaskStatus.WAITING, TaskStatus.RUNNING}:
task.setStatus(TaskStatus.WAITING)
@@ -440,7 +440,7 @@ class TaskService:
self._fileWatcher.removePath(path)
def _onWatchedFileChanged(self, path: str) -> None:
- if probe(path):
+ if isExisting(path):
return
taskId = self._watchedPaths.pop(path, None)
if taskId is None:
diff --git a/app/view/cards/task_cards.py b/app/view/cards/task_cards.py
index 8fc43179..519812e4 100644
--- a/app/view/cards/task_cards.py
+++ b/app/view/cards/task_cards.py
@@ -19,7 +19,7 @@ from app.config.cfg import cfg
from app.format import toReadableSize, toReadableTime
from app.models.task import TaskStatus, SpecialFileSize
from app.platform.desktop import openFile, revealInFolder
-from app.platform.filesystem import probe, probeDirectory
+from app.platform.filesystem import isExisting, isFolder
from app.view.components.labels import IconBodyLabel, IconStrongBodyLabel
from app.view.components.category_settings import toCategoryName
from app.i18n import toLocalizedError
@@ -90,12 +90,12 @@ VERIFY_HASH_BUTTON = ButtonSpec("verifyHash", FluentIcon.FINGERPRINT, N("TaskCar
default=BUTTON_HIDDEN,
states={
TaskStatus.COMPLETED: lambda t: ButtonState(
- enabled=t.hasOutputFile and probe(t.outputPath)),
+ enabled=t.hasOutputFile and isExisting(t.outputPath)),
})
OPEN_FILE_BUTTON = ButtonSpec("openFile", FluentIcon.LINK, N("TaskCard", "打开文件"), states={
TaskStatus.COMPLETED: lambda t: ButtonState(
- enabled=not t.hasOutputFile or probe(t.outputPath)),
+ enabled=not t.hasOutputFile or isExisting(t.outputPath)),
})
OPEN_FOLDER_BUTTON = ButtonSpec("openFolder", FluentIcon.FOLDER, N("TaskCard", "打开文件夹"))
@@ -255,7 +255,7 @@ class TaskCard(CardWidget):
elif task.status == TaskStatus.COMPLETED:
self.progressBar.pause()
self.progressBar.hide()
- self._isFileMissing = task.hasOutputFile and not probe(task.outputPath)
+ self._isFileMissing = task.hasOutputFile and not isExisting(task.outputPath)
if self._isFileMissing:
self._setStatus(self.tr("文件不存在"))
self.statusLabel.setTextColor(QColor(200, 160, 80), QColor(200, 170, 100))
@@ -336,7 +336,7 @@ class TaskCard(CardWidget):
self._taskService.delete(self._task, deleteFiles.isChecked())
def _onVerifyHashClicked(self) -> None:
- if probeDirectory(self._task.outputPath) or not probe(self._task.outputPath):
+ if isFolder(self._task.outputPath) or not isExisting(self._task.outputPath):
self._setStatus(self.tr("文件不存在,无法校验"))
return
from app.view.dialogs.file_hash import FileHashDialog
@@ -456,7 +456,7 @@ class TaskCard(CardWidget):
def _canDrag(self) -> bool:
return (self._task.status == TaskStatus.COMPLETED
and self._task.hasOutputFile
- and probe(self._task.outputPath))
+ and isExisting(self._task.outputPath))
def resizeEvent(self, e) -> None:
self.progressBar.setGeometry(4, self.height() - 4, self.width() - 8, 4)
diff --git a/app/view/pages/task_page.py b/app/view/pages/task_page.py
index 0fdaea02..baa9d7a0 100644
--- a/app/view/pages/task_page.py
+++ b/app/view/pages/task_page.py
@@ -20,7 +20,7 @@ from app.view.components.scroll_area import ScrollArea
from app.config.cfg import cfg
from app.format import toReadableSize
from app.models.task import TaskStatus
-from app.platform.filesystem import probe
+from app.platform.filesystem import isExisting
from app.view.cards.task_cards import TaskCard
from app.view.components.category_settings import toCategoryName
from app.view.components.labels import IconBodyLabel
@@ -375,7 +375,7 @@ class TaskPage(QWidget):
self._selectedIds.clear()
for taskId in self._displayOrder:
task = self._taskService.taskById(taskId)
- if task and task.hasOutputFile and not probe(task.outputPath):
+ if task and task.hasOutputFile and not isExisting(task.outputPath):
self._selectedIds.add(taskId)
for taskId, card in self._liveCards.items():
card.setChecked(taskId in self._selectedIds)
@@ -749,7 +749,7 @@ class TaskPage(QWidget):
if (task := self._taskService.taskById(tid))
and task.status == TaskStatus.COMPLETED
and task.hasOutputFile
- and probe(task.outputPath)
+ and isExisting(task.outputPath)
]
else:
task = self._taskService.taskById(taskId)
diff --git a/tests/test_filesystem_probe.py b/tests/test_filesystem_probe.py
deleted file mode 100644
index b8c02eb5..00000000
--- a/tests/test_filesystem_probe.py
+++ /dev/null
@@ -1,28 +0,0 @@
-from __future__ import annotations
-
-from pathlib import Path
-
-from app.platform.filesystem import probe, probeDirectory
-
-
-def test_probe_missing(tmp_path: Path):
- assert probe(tmp_path / "missing") is False
-
-
-def test_probe_present(tmp_path: Path):
- file = tmp_path / "file"
- file.write_text("x")
- assert probe(file) is True
- assert probeDirectory(file) is False
- assert probeDirectory(tmp_path) is True
-
-
-def test_probe_stat_failure(tmp_path: Path, monkeypatch):
- def fail(self, *, follow_symlinks=True):
- error = OSError(22, "参数错误")
- error.winerror = 87
- raise error
-
- monkeypatch.setattr(Path, "stat", fail)
- assert probe(tmp_path / "zh-cn_windows_11.iso") is False
- assert probeDirectory(tmp_path / "zh-cn_windows_11.iso") is False
diff --git a/tests/test_is_existing.py b/tests/test_is_existing.py
new file mode 100644
index 00000000..19b76abb
--- /dev/null
+++ b/tests/test_is_existing.py
@@ -0,0 +1,28 @@
+from __future__ import annotations
+
+from pathlib import Path
+
+from app.platform.filesystem import isExisting, isFolder
+
+
+def test_isExisting_missing(tmp_path: Path):
+ assert isExisting(tmp_path / "missing") is False
+
+
+def test_isExisting_present(tmp_path: Path):
+ file = tmp_path / "file"
+ file.write_text("x")
+ assert isExisting(file) is True
+ assert isFolder(file) is False
+ assert isFolder(tmp_path) is True
+
+
+def test_isExisting_stat_failure(tmp_path: Path, monkeypatch):
+ def fail(self, *, follow_symlinks=True):
+ error = OSError(22, "参数错误")
+ error.winerror = 87
+ raise error
+
+ monkeypatch.setattr(Path, "stat", fail)
+ assert isExisting(tmp_path / "zh-cn_windows_11.iso") is False
+ assert isFolder(tmp_path / "zh-cn_windows_11.iso") is False