Skip to content

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

fix(runtime): 运行中的程序也能更新和卸载

XiaoYouChRd73a7a8f440b
diff --git a/app/install.py b/app/install.py
index ce5ad69f..3188c803 100644
--- a/app/install.py
+++ b/app/install.py
@@ -2,15 +2,30 @@ from __future__ import annotations
import asyncio
import hashlib
+import glob
import shutil
import tarfile
import zipfile
from pathlib import Path
+from typing import BinaryIO
+from uuid import uuid4
from app.models.task import TaskError
from app.platform.filesystem import deletePath
+def deleteInstalled(path: Path) -> None:
+ if path.exists() or path.is_symlink():
+ path.rename(path.with_name(f"{path.name}.{uuid4().hex[:8]}.old"))
+ for old in path.parent.glob(f"{glob.escape(path.name)}.*.old"):
+ deletePath(old)
+
+
+def installFile(source: Path, target: Path) -> None:
+ deleteInstalled(target)
+ source.replace(target)
+
+
async def installArchive(archive: Path, folder: Path, root: str = "", subtree: str = "") -> None:
safeRoot = folder.resolve()
@@ -28,6 +43,17 @@ async def installArchive(archive: Path, folder: Path, root: str = "", subtree: s
path.parent.mkdir(parents=True, exist_ok=True)
return path
+ def installStream(source: BinaryIO, target: Path, mode: int | None = None) -> None:
+ downloadPath = target.with_name(f"{target.name}.download")
+ try:
+ with open(downloadPath, "wb") as file:
+ shutil.copyfileobj(source, file)
+ if mode is not None:
+ downloadPath.chmod(mode)
+ installFile(downloadPath, target)
+ finally:
+ downloadPath.unlink(missing_ok=True)
+
def install() -> None:
lowered = archive.name.lower()
if lowered.endswith((".zip", ".whl")):
@@ -35,16 +61,15 @@ async def installArchive(archive: Path, folder: Path, root: str = "", subtree: s
for info in zf.infolist():
if info.is_dir() or (path := toMemberPath(info.filename)) is None:
continue
- with zf.open(info) as source, open(path, "wb") as target:
- shutil.copyfileobj(source, target)
+ with zf.open(info) as source:
+ installStream(source, path)
elif lowered.endswith(".tar.gz"):
with tarfile.open(archive, "r:gz") as tf:
for member in tf.getmembers():
if not member.isfile() or (path := toMemberPath(member.name)) is None:
continue
- with tf.extractfile(member) as source, open(path, "wb") as target:
- shutil.copyfileobj(source, target)
- path.chmod(member.mode & 0o777)
+ with tf.extractfile(member) as source:
+ installStream(source, path, member.mode & 0o777)
else:
raise TaskError("不支持的压缩格式:{name}", name=archive.name)
diff --git a/app/models/__init__.py b/app/models/__init__.py
index f7d2e3e1..e69de29b 100644
--- a/app/models/__init__.py
+++ b/app/models/__init__.py
@@ -1,17 +0,0 @@
-from app.models.task import (
- Task,
- TaskStep,
- TaskStatus,
- SpecialFileSize,
- TaskFile,
- TaskOptions,
- ResourceTaskOptions,
- PageTaskOptions,
- MergeTaskOptions,
-)
-from app.models.pack import (
- FeaturePack,
- TaskParser,
- FileType,
- PackConfig,
-)
diff --git a/app/models/pack.py b/app/models/pack.py
index cd1a68df..87d1089a 100644
--- a/app/models/pack.py
+++ b/app/models/pack.py
@@ -2,7 +2,6 @@ from __future__ import annotations
import asyncio
import json
-import shutil
import tomllib
from dataclasses import dataclass
from pathlib import Path
@@ -12,6 +11,7 @@ from loguru import logger
from app.config.cfg import cfg, ConfigItem
+from app.install import deleteInstalled
from app.platform.filesystem import findExecutable
if TYPE_CHECKING:
@@ -21,7 +21,6 @@ if TYPE_CHECKING:
from app.services.speed_meter import SpeedMeter
from PySide6.QtCore import Signal
from PySide6.QtWidgets import QWidget
- from qfluentwidgets import FluentIcon
from app.view.components.setting_card_group import CollapsibleSettingCardGroup
@@ -178,10 +177,7 @@ class BinaryRuntime:
def delete(self) -> None:
for path in self.installedPaths():
- if path.is_dir() and not path.is_symlink():
- shutil.rmtree(path)
- else:
- path.unlink(missing_ok=True)
+ deleteInstalled(path)
class PackPage:
diff --git a/docs/adr/0017-runtime-install-is-not-a-task.md b/docs/adr/0017-runtime-install-is-not-a-task.md
index a60956f5..dcc019b7 100644
--- a/docs/adr/0017-runtime-install-is-not-a-task.md
+++ b/docs/adr/0017-runtime-install-is-not-a-task.md
@@ -15,4 +15,6 @@ Install Folder 由用户选定、可能是共用目录,所以安装只覆盖
- 安装不受 Download Speed Limit 约束,也不进 Speed Meter。
- `RuntimeStatus.progress` 只表示主安装包的下载百分比:0 为准备、1~99 为下载、100 为安装。
+- 安装和卸载一律先改名再替换/删除,运行中的程序也能更新:原地覆盖时 macOS 会杀掉被覆盖的程序,Linux 写入失败,Windows 不能覆盖或删除但三平台都允许改名。
+ 新文件先写到同目录的临时文件,旧文件改名为 `<名>.<随机>.old` 再换入;删不掉的 `.old` 在下次安装或卸载时清理。
- 第三方包布局变了(例如多出外层目录)时,安装后 `isAppManaged()` 为假,安装以「安装后未找到」失败,需要在 pack 里改 `root`。
diff --git a/features/yt_dlp_pack/config.py b/features/yt_dlp_pack/config.py
index a01af245..0e68370c 100644
--- a/features/yt_dlp_pack/config.py
+++ b/features/yt_dlp_pack/config.py
@@ -4,6 +4,7 @@ import ast
import platform
import sys
from pathlib import Path
+from typing import TYPE_CHECKING
from app.config.cfg import BoolValidator, ConfigItem, FolderValidator
from app.i18n import N
@@ -13,10 +14,13 @@ from app.models.pack import BinaryRuntime, PackConfig, VersionInfo
from app.platform.android import IS_ANDROID
from app.platform.filesystem import findExecutable
from app.models.task import TaskError
-from app.install import installArchive
+from app.install import installArchive, installFile
from app.sources import Repo, fetchLatestRelease, fetchPypiFile, fetchPypiReleases, fetchReleaseAsset
from app.update import parseVersion
+if TYPE_CHECKING:
+ from PySide6.QtWidgets import QWidget
+
QJS_REPO = Repo("quickjs-ng/quickjs", mirrors={"gitcode": "XiaoYouChR/quickjs-mirror"})
COOKIE_DOMAIN = ".youtube.com"
AUTH_COOKIE_NAMES = ("LOGIN_INFO", "SAPISID", "__Secure-1PAPISID", "__Secure-3PAPISID")
@@ -212,9 +216,14 @@ class YouTubeRuntime(BinaryRuntime):
if not IS_ANDROID:
qjsTag = (await fetchLatestRelease(QJS_REPO)).version
qjsPath = folder / ("qjs.exe" if sys.platform == "win32" else "qjs")
- await fetchReleaseAsset(QJS_REPO, qjsTag, _qjsAssetName(), qjsPath)
- if sys.platform != "win32":
- qjsPath.chmod(qjsPath.stat().st_mode | 0o755)
+ downloadPath = qjsPath.with_name(f"{qjsPath.name}.download")
+ try:
+ await fetchReleaseAsset(QJS_REPO, qjsTag, _qjsAssetName(), downloadPath)
+ if sys.platform != "win32":
+ downloadPath.chmod(downloadPath.stat().st_mode | 0o755)
+ installFile(downloadPath, qjsPath)
+ finally:
+ downloadPath.unlink(missing_ok=True)
_, wheelUrl = await fetchNightlyWheel()
archive = folder / "yt_dlp.whl"
diff --git a/tests/test_runtime_install.py b/tests/test_runtime_install.py
index 050851c6..50ca22c7 100644
--- a/tests/test_runtime_install.py
+++ b/tests/test_runtime_install.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import asyncio
import hashlib
import io
+import shutil
import sys
import tarfile
import zipfile
@@ -10,7 +11,7 @@ from pathlib import Path
import pytest
-from app.install import installArchive, matchSha256
+from app.install import deleteInstalled, installArchive, installFile, matchSha256
from app.models.pack import BinaryRuntime, VersionInfo
from app.models.task import TaskError
from app.services.coroutine_runner import CoroutineRunner
@@ -85,6 +86,101 @@ async def test_unsafe_member_is_rejected_and_archive_deleted(tmp_path):
assert not archive.exists()
+def lockRunning(monkeypatch):
+ unlink, rmtree = Path.unlink, shutil.rmtree
+
+ def lockedUnlink(path, missing_ok=False):
+ if path.name.endswith(".old"):
+ raise PermissionError(f"{path} is running")
+ unlink(path, missing_ok=missing_ok)
+
+ def lockedRmtree(path, ignore_errors=False, **kwargs):
+ if Path(path).name.endswith(".old"):
+ if ignore_errors:
+ return
+ raise PermissionError(f"{path} is running")
+ rmtree(path, ignore_errors=ignore_errors, **kwargs)
+
+ monkeypatch.setattr(Path, "unlink", lockedUnlink)
+ monkeypatch.setattr(shutil, "rmtree", lockedRmtree)
+
+ def unlock():
+ monkeypatch.setattr(Path, "unlink", unlink)
+ monkeypatch.setattr(shutil, "rmtree", rmtree)
+
+ return unlock
+
+
+def test_install_file_replaces_a_running_file(tmp_path):
+ target = tmp_path / "ffmpeg"
+ target.write_bytes(b"old")
+ source = tmp_path / "ffmpeg.download"
+ source.write_bytes(b"new")
+
+ with target.open("rb") as running:
+ installFile(source, target)
+ assert running.read() == b"old"
+
+ assert target.read_bytes() == b"new"
+ assert [p.name for p in tmp_path.iterdir()] == ["ffmpeg"]
+
+
+def test_install_file_leaves_a_locked_old_file_until_next_install(tmp_path, lockRunning):
+ target = tmp_path / "ffmpeg"
+ target.write_bytes(b"old")
+ (tmp_path / "ffmpeg.download").write_bytes(b"new")
+
+ installFile(tmp_path / "ffmpeg.download", target)
+
+ assert target.read_bytes() == b"new"
+ oldFiles = sorted(tmp_path.glob("ffmpeg.*.old"))
+ assert [p.read_bytes() for p in oldFiles] == [b"old"]
+
+ lockRunning()
+ (tmp_path / "ffmpeg.download").write_bytes(b"newer")
+ installFile(tmp_path / "ffmpeg.download", target)
+
+ assert [p.name for p in tmp_path.iterdir()] == ["ffmpeg"]
+ assert target.read_bytes() == b"newer"
+
+
+def test_delete_installed_folder_keeps_neighbours(tmp_path):
+ (tmp_path / "yt_dlp").mkdir()
+ (tmp_path / "yt_dlp" / "__init__.py").write_bytes(b"init")
+ (tmp_path / "notes.txt").write_bytes(b"user")
+
+ deleteInstalled(tmp_path / "yt_dlp")
+
+ assert [p.name for p in tmp_path.iterdir()] == ["notes.txt"]
+
+
+def test_delete_installed_leaves_a_locked_folder_until_next_delete(tmp_path, lockRunning):
+ (tmp_path / "yt_dlp").mkdir()
+ (tmp_path / "yt_dlp" / "__init__.py").write_bytes(b"init")
+
+ deleteInstalled(tmp_path / "yt_dlp")
+
+ assert not (tmp_path / "yt_dlp").exists()
+ assert len(list(tmp_path.glob("yt_dlp.*.old"))) == 1
+
+ lockRunning()
+ deleteInstalled(tmp_path / "yt_dlp")
+
+ assert list(tmp_path.iterdir()) == []
+
+
+async def test_tar_replaces_a_locked_file_and_keeps_its_mode(tmp_path, lockRunning):
+ (tmp_path / "ffmpeg").write_bytes(b"old")
+ archive = writeTar(tmp_path / "ffmpeg.tar.gz", {"ffmpeg": b"new"}, mode=0o750)
+
+ await installArchive(archive, tmp_path)
+
+ assert (tmp_path / "ffmpeg").read_bytes() == b"new"
+ assert (tmp_path / "ffmpeg").stat().st_mode & 0o777 == 0o750
+ assert sorted(p.name for p in tmp_path.iterdir() if not p.name.endswith(".old")) == ["ffmpeg"]
+
+
@pytest.mark.parametrize("digestOf, expected", [(b"payload", True), (b"other", False)])
async def test_match_sha256(tmp_path, digestOf, expected):
file = tmp_path / "ffmpeg.tar.gz"