feat(desktop): opt-in Windows uninstall data removal
The Windows uninstaller keeps every user file by default and adds a custom page with unchecked options for desktop browser data and update caches, the desktop plugin profile, and the complete Harness home. Selecting the whole home requires a native warning that names the actual folder and the CLI impact, defaults to Cancel, and forces the desktop child selection. Silent and upgrade uninstalls never remove data, including through the legacy --delete-app-data flag, which the adapted upstream template no longer honors. Packaged Desktop records its resolved home in uninstall.ini under the Electron user-data directory so a custom DSH_HOME is offered instead of the default; a length field detects truncated NSIS reads and an invalid record disables whole-home removal. The native remover in window-frame.dll rejects protected roots and overlap with retained data, holds directory handles during traversal, and unlinks reparse points without entering their targets. Installation now also writes InstallLocation on the Windows uninstall entry, which Explorer needs to associate the Start menu shortcut with this entry so that the context-menu Uninstall launches the uninstaller directly instead of opening the installed-apps list. The upstream template only records the value under its private key. Closes #3993
This commit is contained in:
1 parent
4aba48ec03
commit
dbbecd2461
29 files changed
+721
-28
No files matched your search
@@ -0,0 +1,6 @@
|
||||
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
|
||||
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
||||
# after editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-09-18-windows-opt-in-uninstall-data.md
|
||||
2026-09-18-windows-opt-in-uninstall-data.md: c18892dd3d470ccb684f2614f9119660ddd68423
|
||||
2026-09-18-windows-opt-in-uninstall-data.zh.md: 4185b4dd8cec0b634d8159b7c5bf27674c3820a5
|
||||
@@ -0,0 +1,31 @@
|
||||
# Agent Note: Opt-in Windows uninstall data removal
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-09-18-windows-opt-in-uninstall-data.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
Desktop and CLI share conversations, credentials and settings in the Harness home. Counting profile directories cannot establish exclusive Desktop ownership: CLI profiles are created on demand. Browser storage and updater downloads also live outside that home.
|
||||
|
||||
## Decision
|
||||
|
||||
Windows uninstallation preserves data by default. The user can select desktop browser data and update caches, only `profiles/desktop`, or the entire Harness home. Whole-home selection requires a native warning with the actual path and CLI impact, defaults to Cancel, and forces the desktop child selection. Removing the parent selection restores the child's earlier independent state. Silent and upgrade uninstalls never opt into data removal.
|
||||
|
||||
The last packaged Desktop launch writes its resolved home to an INI file under Electron user data. A length field detects truncated NSIS reads. Missing legacy records select the default home; an invalid record cannot authorize home deletion. The native remover rejects protected roots and installation overlap, holds directory handles against replacement during traversal, and unlinks descendant reparse points without traversing their targets. Failure stops uninstallation and discloses possible partial deletion. This remains a current-user operation, not an all-users purge.
|
||||
|
||||
The [earlier proposal](../../rejected/feature/2026-09-08-desktop-uninstall-preserve-dsh-home.md) is superseded by explicit selection rather than unconditional external-data removal. macOS cleanup is outside this implementation. Existing Desktop packaging and profile ownership decisions remain applicable.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**Delete the whole home when desktop is the only profile.** Profile presence does not establish whether shared data is needed by CLI or a future reinstall.
|
||||
|
||||
**Always retain the home and automatically delete external caches.** Browser storage includes drafts and preferences; users choose whether to remove it. Users can also explicitly choose to discard all shared data.
|
||||
|
||||
**Use electron-builder's delete-app-data switch.** It lacks the selection hierarchy, shared-home warning and updater-cache inventory; cleanup belongs to the interactive custom page.
|
||||
|
||||
## Consequences
|
||||
|
||||
Desktop-only cleanup can retain Office runtimes and shared data. The complete-home option deletes every file under its displayed root, including user additions. Other historical homes, arbitrary plugin outputs and user projects outside selected roots are not discovered or deleted.
|
||||
|
||||
Qualification uses isolated product identities. Source regressions cover INI persistence and template adaptation; native fixtures cover retention, selective removal, junction targets and upgrade/silent behavior. The development host's Application Control blocks the unsigned test uninstaller, so native execution, installed release inventory and high-DPI visual acceptance remain unverified on that host. Compilation alone is not release qualification.
|
||||
@@ -0,0 +1,31 @@
|
||||
# Agent Note: Windows 卸载时按需清除数据
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-09-18-windows-opt-in-uninstall-data.md)
|
||||
|
||||
## Problem
|
||||
|
||||
Desktop 和 CLI 共享 Harness 主目录中的会话、凭据和设置。配置档案数量不能证明数据由 Desktop 独占:CLI 配置档案按需创建。浏览器存储和更新下载还位于主目录之外。
|
||||
|
||||
## Decision
|
||||
|
||||
Windows 卸载默认保留数据。用户可以选择桌面浏览器数据与更新缓存、仅 `profiles/desktop` 或整个 Harness 主目录。选择整个主目录需要原生警告确认,显示实际路径及 CLI 影响,默认选择取消,并强制勾选桌面子项。取消父项勾选会恢复子项先前的独立状态。静默卸载和升级不会选择清除数据。
|
||||
|
||||
最近一次打包 Desktop 启动将解析后的主目录写入 Electron 用户数据中的 INI 文件。长度字段检测 NSIS 读取截断。旧安装缺少记录时选择默认主目录;无效记录不能授权删除主目录。原生清理拒绝受保护的根目录及与安装目录重叠的路径,遍历时持有目录句柄防止路径被替换,遇到后代重解析点只移除链接,不遍历目标。失败会停止卸载,并说明可能已经删除部分数据。此操作仅针对当前用户,不清理所有用户。
|
||||
|
||||
[旧提案](../../rejected/feature/2026-09-08-desktop-uninstall-preserve-dsh-home.zh.md)中无条件删除外部数据的方案由显式选择替代。macOS 清理不属于本次实现。现有 Desktop 打包及配置档案归属决策仍然适用。
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**只有 desktop 配置档案时删除整个主目录。** 配置档案是否存在不能证明 CLI 或重新安装时不需要共享数据。
|
||||
|
||||
**始终保留主目录并自动删除外部缓存。** 浏览器存储包含草稿和偏好,应由用户选择是否删除。用户也可以明确选择丢弃全部共享数据。
|
||||
|
||||
**使用 electron-builder 的 delete-app-data 开关。** 它没有父子选择、共享主目录警告和更新缓存清单;清理由交互式自定义页面控制。
|
||||
|
||||
## Consequences
|
||||
|
||||
仅清理桌面配置档案可能保留 Office 运行环境及共享数据。整个主目录选项会删除显示根目录中的所有文件,包括用户自行添加的文件。不会发现或删除其他历史主目录、任意插件输出和所选根目录之外的用户项目。
|
||||
|
||||
验收使用独立产品身份。源码回归覆盖 INI 持久化和模板适配;原生夹具覆盖保留、分项删除、目录链接目标及升级和静默行为。开发主机的 Application Control 阻止未签名的测试卸载器,因此该主机尚未验证原生执行、已安装发布产物清单和高 DPI 视觉效果。仅编译通过不等于发布验收通过。
|
||||
-6
@@ -1,6 +0,0 @@
|
||||
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
|
||||
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
||||
# after editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write .agents/notes/proposed/feature/2026-09-08-desktop-uninstall-preserve-dsh-home.md
|
||||
2026-09-08-desktop-uninstall-preserve-dsh-home.md: e1c2435814a4563f1fed6652d521928200d4ade7
|
||||
2026-09-08-desktop-uninstall-preserve-dsh-home.zh.md: 27fd7c8cbec360db35cadc75ff26b575629ad571
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
|
||||
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
||||
# after editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write .agents/notes/rejected/feature/2026-09-08-desktop-uninstall-preserve-dsh-home.md
|
||||
2026-09-08-desktop-uninstall-preserve-dsh-home.md: 3db48b639c7b4d5c7b1b33b513052d1b798ee80e
|
||||
2026-09-08-desktop-uninstall-preserve-dsh-home.zh.md: cb46112f876e88bedc97e280c853fc5757797d55
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
# Agent Note: Uninstall Desktop while preserving the Harness home
|
||||
|
||||
Status: proposed
|
||||
Status: rejected — [Windows uses opt-in cleanup](../../implemented/feature/2026-09-18-windows-opt-in-uninstall-data.md); unconditional external-data deletion is not the chosen default, and macOS cleanup remains outside the implemented scope.
|
||||
|
||||
English | [中文](2026-09-08-desktop-uninstall-preserve-dsh-home.zh.md)
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
# Agent Note: 卸载 Desktop 并保留 Harness 主目录
|
||||
|
||||
Status: proposed
|
||||
Status: rejected — [Windows 使用按需清理](../../implemented/feature/2026-09-18-windows-opt-in-uninstall-data.zh.md);默认不无条件删除外部数据,macOS 清理仍不在已实现范围内。
|
||||
|
||||
[English](2026-09-08-desktop-uninstall-preserve-dsh-home.md) | 中文
|
||||
|
||||
@@ -2,5 +2,5 @@
|
||||
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
||||
# after editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write apps/desktop/README.md
|
||||
README.md: 43cde4f41f2e82bf2d3ccce0a7e93d81234010c5
|
||||
README.zh.md: 9e300996cd7ed0428c7199e9f9bd43b6f9077e0a
|
||||
README.md: f508d875194bb59756cd3f8a6e55c6ec3478468b
|
||||
README.zh.md: 0fc85b3d6bdd3dd344d7a20cfcb257fe34addfaa
|
||||
@@ -240,6 +240,10 @@ Windows packaging compiles an x86 Win32/GDI+ helper with Visual C++ Build Tools
|
||||
|
||||
Run `pnpm --dir apps/desktop run test:installer` from the repository root on an interactive Windows x64 desktop to build and exercise a small native test payload through the production installer configuration. Each run uses a unique product identity and sequentially exercises English-only and Chinese-only installer variants, selecting test labels from the displayed welcome button. Both variants install into private directories and uninstall after testing; screenshots and results remain under `.desktop-build/installer-tests/`. The checks include upgrades to registered paths with trailing separators and rejection of drive roots. The optional `--signed` flag uses the Windows EV configuration below to sign test executables and the helper before embedding them; it does not enable an update feed.
|
||||
|
||||
The Windows uninstaller offers unchecked options for desktop browser data/update caches, the desktop plugin profile, and the complete Harness home. Selecting the complete home requires a warning confirmation and includes the desktop profile; cancelling restores its independent selection. Silent uninstalls and upgrades retain data, including when passed the legacy `--delete-app-data` flag. Packaged Desktop records its last launched home in Electron user data as `uninstall.ini`; older installations without a record offer the default home. Linked roots, protected Windows folders, and overlap with retained data stop cleanup. Locked files report failure, possibly after partial removal. The native wizard declares DPI awareness and uses Microsoft YaHei UI for Chinese. Installation records `InstallLocation` on the Windows uninstall entry so that Uninstall in the Start menu context menu launches this uninstaller instead of opening the installed-apps list. These options are Windows-only.
|
||||
|
||||
Use `node apps/desktop/scripts/test-windows-installer.mjs --uninstall-only --compile-only` to compile isolated English and Chinese fixtures. Omit `--compile-only` to run the native retention/removal checks. Hosts with Application Control may reject the unsigned test uninstaller; compilation does not establish installed-uninstall behavior or high-DPI visual acceptance.
|
||||
|
||||
### Windows EV signing
|
||||
|
||||
Runtime signing shares complete signed files across the current Windows account's worktrees. `DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_DIR` in `.env.windows` selects an absolute fixed-drive directory; the default is `%USERPROFILE%\.dsh-desktop-signing\signature-cache\v1`. Cache directories must belong to the current account and exclude other ordinary accounts from their access permissions; linked paths are rejected. Entries identify the original bytes, public certificate and signing toolchain. Every restoration checks the digest, Windows trust, timestamp and certificate before replacing the unsigned file; invalid entries stop packaging without hardware fallback. Cache age alone does not trigger signing. The cache trusts programs running as the same account and does not defend against administrators. The [runtime signature cache decision](../../.agents/notes/implemented/process/2026-09-17-windows-runtime-signature-cache.md) owns qualification and design limits.
|
||||
|
||||
@@ -240,6 +240,10 @@ Windows 打包使用 Visual C++ Build Tools 和 Windows SDK 编译 x86 Win32/GDI
|
||||
|
||||
在有交互式桌面的 Windows x64 上,从仓库根目录运行 `pnpm --dir apps/desktop run test:installer`,可将小型原生测试载荷接入正式安装配置并执行验证。每次运行使用独立产品身份,依次验证仅英文和仅中文的安装器变体,并根据实际显示的欢迎页按钮选择测试文案。两个变体均安装到私有目录并在测试后卸载;截图和结果保留在 `.desktop-build/installer-tests/` 下。检查包含末尾带分隔符的已登记路径升级,以及磁盘根目录拒绝。可选的 `--signed` 标志使用下文的 Windows EV 配置,在嵌入前对测试程序和辅助库签名;它不会启用更新源。
|
||||
|
||||
Windows 卸载程序提供默认不勾选的清理项:桌面浏览器数据与更新缓存、桌面插件配置档案、整个 Harness 主目录。选择整个主目录需要确认警告,并包含桌面配置档案;取消后恢复其独立选择。静默卸载和升级保留数据,即使传入旧的 `--delete-app-data` 参数。打包后的 Desktop 在 Electron 用户数据中的 `uninstall.ini` 记录最近启动使用的主目录;没有记录的旧安装提供默认主目录。链接根目录、受保护的 Windows 目录或与保留数据重叠的路径会阻止清理。文件占用会报告失败,此时可能已删除部分内容。原生向导声明 DPI 感知,中文使用微软雅黑 UI。安装时在 Windows 卸载注册项上记录 `InstallLocation`,使开始菜单右键菜单中的“卸载”直接启动此卸载程序,而不是打开已安装应用列表。此功能仅适用于 Windows。
|
||||
|
||||
使用 `node apps/desktop/scripts/test-windows-installer.mjs --uninstall-only --compile-only` 编译独立的中英文夹具。省略 `--compile-only` 可运行原生保留与删除检查。启用 Application Control 的主机可能拒绝未签名的测试卸载器;编译通过不代表已安装卸载行为或高 DPI 视觉验收通过。
|
||||
|
||||
### Windows EV 签名
|
||||
|
||||
运行时签名在当前 Windows 账户的各 worktree 间共享完整的已签名文件。`.env.windows` 中的 `DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_DIR` 指定固定本地磁盘上的绝对目录;默认值为 `%USERPROFILE%\.dsh-desktop-signing\signature-cache\v1`。缓存目录必须属于当前账户,访问权限不得向其他普通账户开放;带链接的路径会被拒绝。缓存项标识原始字节、公钥证书和签名工具链。每次恢复都检查摘要、Windows 信任状态、时间戳和证书,再替换未签名文件;缓存项无效会停止打包,不回退到硬件签名。不会仅因缓存较旧而重新签名。缓存信任同账户运行的程序,不防御管理员。[运行时签名缓存决策](../../.agents/notes/implemented/process/2026-09-17-windows-runtime-signature-cache.zh.md)定义验收要求和设计限制。
|
||||
|
||||
@@ -1,4 +1,28 @@
|
||||
; NSIS owns installer localization independently of the Electron application locale.
|
||||
!ifdef BUILD_UNINSTALLER
|
||||
LangString UNINSTALL_DATA_TITLE ${LANG_ENGLISH} "Choose local data to remove"
|
||||
LangString UNINSTALL_DATA_TITLE ${LANG_SIMPCHINESE} "选择要清除的本机数据"
|
||||
LangString UNINSTALL_DATA_SUBTITLE ${LANG_ENGLISH} "All data is kept by default for future installations."
|
||||
LangString UNINSTALL_DATA_SUBTITLE ${LANG_SIMPCHINESE} "默认保留所有数据,便于重新安装后继续使用。"
|
||||
LangString UNINSTALL_DATA_INTRO ${LANG_ENGLISH} "The application will be uninstalled. You can also remove the following data:"
|
||||
LangString UNINSTALL_DATA_INTRO ${LANG_SIMPCHINESE} "应用程序将被卸载。你也可以选择清除以下数据:"
|
||||
LangString UNINSTALL_LOCAL ${LANG_ENGLISH} "Remove desktop application data and caches"
|
||||
LangString UNINSTALL_LOCAL ${LANG_SIMPCHINESE} "清除桌面应用本地数据和缓存"
|
||||
LangString UNINSTALL_LOCAL_DETAIL ${LANG_ENGLISH} "Includes browser storage and downloaded updates."
|
||||
LangString UNINSTALL_LOCAL_DETAIL ${LANG_SIMPCHINESE} "包括浏览器存储和自动更新下载缓存。"
|
||||
LangString UNINSTALL_ALL ${LANG_ENGLISH} "Remove all Harness data (also affects the CLI)"
|
||||
LangString UNINSTALL_ALL ${LANG_SIMPCHINESE} "清除全部 Harness 数据(也会影响命令行版 CLI)"
|
||||
LangString UNINSTALL_DESKTOP ${LANG_ENGLISH} "Remove desktop plugins and configuration"
|
||||
LangString UNINSTALL_DESKTOP ${LANG_SIMPCHINESE} "清除桌面插件和配置"
|
||||
LangString UNINSTALL_DESKTOP_DETAIL ${LANG_ENGLISH} "Selected alone, keeps sessions and shared settings."
|
||||
LangString UNINSTALL_DESKTOP_DETAIL ${LANG_SIMPCHINESE} "单独选择时,保留会话及共享设置。"
|
||||
LangString UNINSTALL_ALL_WARNING ${LANG_ENGLISH} "Uninstalling will permanently delete all sessions, settings, API keys, plugins and runtimes, including data shared with the CLI. This cannot be undone.$\r$\n$\r$\nFolder: $UnHome"
|
||||
LangString UNINSTALL_ALL_WARNING ${LANG_SIMPCHINESE} "卸载时将永久删除所有会话、设置、API 密钥、插件及运行环境,也会影响命令行版(CLI)。此操作无法撤销。$\r$\n$\r$\n将删除的数据目录:$UnHome"
|
||||
LangString UNINSTALL_DATA_FAILED ${LANG_ENGLISH} "Could not safely remove all selected data. Some files may already have been removed. Close programs using this folder and retry, or keep the data.$\r$\n$\r$\nFolder: $UnTarget"
|
||||
LangString UNINSTALL_DATA_FAILED ${LANG_SIMPCHINESE} "无法安全清除所选数据,部分文件可能已经删除。请关闭占用此目录的程序后重试,或保留数据。$\r$\n$\r$\n目录:$UnTarget"
|
||||
LangString UNINSTALL_HOME_CONFLICT ${LANG_ENGLISH} "This folder overlaps retained Harness data, or the data location could not be verified. Uninstallation has stopped. Move your Harness data to a separate folder and launch Desktop again before retrying.$\r$\n$\r$\nFolder: $UnTarget"
|
||||
LangString UNINSTALL_HOME_CONFLICT ${LANG_SIMPCHINESE} "此目录与需要保留的 Harness 数据重叠,或无法确认数据位置,卸载已停止。请将 Harness 数据移到独立目录并重新启动 Desktop 后重试。$\r$\n$\r$\n目录:$UnTarget"
|
||||
!endif
|
||||
LangString INSTALLER_INSTALL ${LANG_ENGLISH} "Install now"
|
||||
LangString INSTALLER_INSTALL ${LANG_SIMPCHINESE} "立即安装"
|
||||
LangString INSTALLER_FINISH ${LANG_ENGLISH} "Finish"
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
// Windows data cleanup: protect shell roots and pin directory names while enumerating.
|
||||
#pragma once
|
||||
#include <shlobj.h>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace uninstall_data {
|
||||
struct Handles {
|
||||
std::vector<HANDLE> values;
|
||||
~Handles() { for (HANDLE value : values) CloseHandle(value); }
|
||||
};
|
||||
|
||||
inline bool Contains(const std::wstring& parent, const std::wstring& child) {
|
||||
return _wcsicmp(parent.c_str(), child.c_str()) == 0
|
||||
|| (child.size() > parent.size() && child[parent.size()] == L'\\'
|
||||
&& _wcsnicmp(parent.c_str(), child.c_str(), parent.size()) == 0);
|
||||
}
|
||||
|
||||
inline bool Normalize(LPCWSTR input, std::wstring& result) {
|
||||
if (!input || wcslen(input) < 4 || input[1] != L':' || input[2] != L'\\') return false;
|
||||
if (wcspbrk(input + 3, L"/:*?\"<>|\r\n\t")) return false;
|
||||
WCHAR buffer[32768];
|
||||
DWORD length = GetFullPathNameW(input, ARRAYSIZE(buffer), buffer, nullptr);
|
||||
if (!length || length >= ARRAYSIZE(buffer)) return false;
|
||||
result.assign(buffer, length);
|
||||
length = GetLongPathNameW(result.c_str(), buffer, ARRAYSIZE(buffer));
|
||||
if (length > 0 && length < ARRAYSIZE(buffer)) result.assign(buffer, length);
|
||||
while (result.size() > 3 && result.back() == L'\\') result.pop_back();
|
||||
if (result.size() <= 3 || GetDriveTypeW(result.substr(0, 3).c_str()) != DRIVE_FIXED) return false;
|
||||
for (size_t start = 3; start < result.size();) {
|
||||
size_t end = result.find(L'\\', start);
|
||||
if (end == std::wstring::npos) end = result.size();
|
||||
if (end == start || result[end - 1] == L'.' || result[end - 1] == L' ') return false;
|
||||
start = end + 1;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
inline DWORD Pin(const std::wstring& path, Handles& handles) {
|
||||
HANDLE handle = CreateFileW((L"\\\\?\\" + path).c_str(), FILE_READ_ATTRIBUTES,
|
||||
FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING,
|
||||
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, nullptr);
|
||||
if (handle == INVALID_HANDLE_VALUE) return GetLastError();
|
||||
handles.values.push_back(handle);
|
||||
BY_HANDLE_FILE_INFORMATION info{};
|
||||
if (!GetFileInformationByHandle(handle, &info)) return GetLastError();
|
||||
if (!(info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
|
||||
|| (info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)) return ERROR_ACCESS_DENIED;
|
||||
return ERROR_SUCCESS;
|
||||
}
|
||||
|
||||
inline DWORD RemoveTree(const std::wstring& path) {
|
||||
const std::wstring extended = L"\\\\?\\" + path;
|
||||
DWORD attributes = GetFileAttributesW(extended.c_str());
|
||||
if (attributes == INVALID_FILE_ATTRIBUTES) {
|
||||
DWORD error = GetLastError();
|
||||
return error == ERROR_FILE_NOT_FOUND || error == ERROR_PATH_NOT_FOUND ? ERROR_SUCCESS : error;
|
||||
}
|
||||
if (!(attributes & FILE_ATTRIBUTE_DIRECTORY)) {
|
||||
return DeleteFileW(extended.c_str()) ? ERROR_SUCCESS : GetLastError();
|
||||
}
|
||||
if (!(attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
|
||||
Handles pinned;
|
||||
DWORD error = Pin(path, pinned);
|
||||
if (error) return error;
|
||||
WIN32_FIND_DATAW entry{};
|
||||
HANDLE search = FindFirstFileW((extended + L"\\*").c_str(), &entry);
|
||||
if (search == INVALID_HANDLE_VALUE) {
|
||||
error = GetLastError();
|
||||
if (error != ERROR_FILE_NOT_FOUND) return error;
|
||||
} else {
|
||||
do {
|
||||
if (wcscmp(entry.cFileName, L".") == 0 || wcscmp(entry.cFileName, L"..") == 0) continue;
|
||||
error = RemoveTree(path + L"\\" + entry.cFileName);
|
||||
if (error) { FindClose(search); return error; }
|
||||
} while (FindNextFileW(search, &entry));
|
||||
error = GetLastError();
|
||||
FindClose(search);
|
||||
if (error != ERROR_NO_MORE_FILES) return error;
|
||||
}
|
||||
}
|
||||
return RemoveDirectoryW(extended.c_str()) ? ERROR_SUCCESS : GetLastError();
|
||||
}
|
||||
|
||||
// Never select a shell folder, its ancestor, Windows/Program Files descendants,
|
||||
// or a path overlapping the installation. Linked descendants are unlinked only.
|
||||
inline DWORD Remove(LPCWSTR input, LPCWSTR installation) {
|
||||
std::wstring path, install;
|
||||
if (!Normalize(input, path) || !Normalize(installation, install)) return ERROR_INVALID_NAME;
|
||||
if (Contains(path, install) || Contains(install, path)) return ERROR_ACCESS_DENIED;
|
||||
struct ComScope {
|
||||
HRESULT result = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
|
||||
~ComScope() { if (SUCCEEDED(result)) CoUninitialize(); }
|
||||
} com;
|
||||
if (FAILED(com.result) && com.result != RPC_E_CHANGED_MODE) return ERROR_ACCESS_DENIED;
|
||||
// This helper is x86; the x64 Program Files known-folder id is unavailable to it.
|
||||
WCHAR nativePrograms[32768];
|
||||
DWORD bytes = sizeof(nativePrograms);
|
||||
if (RegGetValueW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion", L"ProgramFilesDir",
|
||||
RRF_RT_REG_SZ | RRF_SUBKEY_WOW6464KEY, nullptr, nativePrograms, &bytes) != ERROR_SUCCESS) return ERROR_ACCESS_DENIED;
|
||||
std::wstring nativeFolder;
|
||||
if (!Normalize(nativePrograms, nativeFolder) || Contains(path, nativeFolder) || Contains(nativeFolder, path)) return ERROR_ACCESS_DENIED;
|
||||
const KNOWNFOLDERID* protectedFolders[] = {&FOLDERID_Profile, &FOLDERID_RoamingAppData,
|
||||
&FOLDERID_LocalAppData, &FOLDERID_Desktop, &FOLDERID_Documents, &FOLDERID_Downloads,
|
||||
&FOLDERID_Pictures, &FOLDERID_Music, &FOLDERID_Videos, &FOLDERID_Public, &FOLDERID_ProgramData,
|
||||
&FOLDERID_Windows, &FOLDERID_ProgramFiles, &FOLDERID_ProgramFilesX86};
|
||||
for (const KNOWNFOLDERID* id : protectedFolders) {
|
||||
PWSTR value = nullptr;
|
||||
HRESULT result = SHGetKnownFolderPath(*id, KF_FLAG_DONT_VERIFY, nullptr, &value);
|
||||
if (FAILED(result)) return ERROR_ACCESS_DENIED;
|
||||
const std::wstring folder(value);
|
||||
CoTaskMemFree(value);
|
||||
if (Contains(path, folder)) return ERROR_ACCESS_DENIED;
|
||||
if ((id == &FOLDERID_Windows || id == &FOLDERID_ProgramFiles || id == &FOLDERID_ProgramFilesX86)
|
||||
&& Contains(folder, path)) return ERROR_ACCESS_DENIED;
|
||||
}
|
||||
Handles parents;
|
||||
for (size_t end = path.find(L'\\', 3); end != std::wstring::npos; end = path.find(L'\\', end + 1)) {
|
||||
DWORD error = Pin(path.substr(0, end), parents);
|
||||
if (error == ERROR_FILE_NOT_FOUND || error == ERROR_PATH_NOT_FOUND) return ERROR_SUCCESS;
|
||||
if (error) return error;
|
||||
}
|
||||
// A selected root must be a real directory, even though links inside it may be removed.
|
||||
{
|
||||
Handles root;
|
||||
DWORD error = Pin(path, root);
|
||||
if (error == ERROR_FILE_NOT_FOUND || error == ERROR_PATH_NOT_FOUND) return ERROR_SUCCESS;
|
||||
if (error) return error;
|
||||
}
|
||||
return RemoveTree(path);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
; User data removal is opt-in and never runs for silent or upgrade uninstalls.
|
||||
!include nsDialogs.nsh
|
||||
!include WinMessages.nsh
|
||||
|
||||
Var UnLocal
|
||||
Var UnAll
|
||||
Var UnDesktop
|
||||
Var UnPreviousDesktop
|
||||
Var UnLocalControl
|
||||
Var UnAllControl
|
||||
Var UnDesktopControl
|
||||
|
||||
Function un.DataInit
|
||||
StrCpy $UnLocal 0
|
||||
StrCpy $UnAll 0
|
||||
StrCpy $UnDesktop 0
|
||||
StrCpy $UnPreviousDesktop 0
|
||||
StrCpy $UnHome "$PROFILE\.dsh"
|
||||
StrCpy $1 "$APPDATA\${PRODUCT_FILENAME}\uninstall.ini"
|
||||
!ifdef APP_PACKAGE_NAME
|
||||
${IfNot} ${FileExists} "$1"
|
||||
StrCpy $1 "$APPDATA\${APP_PACKAGE_NAME}\uninstall.ini"
|
||||
${EndIf}
|
||||
!endif
|
||||
ReadINIStr $0 "$1" "Harness" "Home"
|
||||
${If} $0 != ""
|
||||
StrCpy $UnHome $0
|
||||
ReadINIStr $2 "$1" "Harness" "HomeLength"
|
||||
StrLen $3 $UnHome
|
||||
${If} $2 != $3
|
||||
StrCpy $UnHome ""
|
||||
${EndIf}
|
||||
${ElseIf} ${FileExists} "$1"
|
||||
StrCpy $UnHome ""
|
||||
${EndIf}
|
||||
InitPluginsDir
|
||||
File "/oname=$PLUGINSDIR\window-frame.dll" "${INSTALLER_BUILD_DIR}\window-frame.dll"
|
||||
FunctionEnd
|
||||
|
||||
Function un.DataPage
|
||||
${If} ${isUpdated}
|
||||
Abort
|
||||
${EndIf}
|
||||
!insertmacro MUI_HEADER_TEXT "$(UNINSTALL_DATA_TITLE)" "$(UNINSTALL_DATA_SUBTITLE)"
|
||||
nsDialogs::Create 1018
|
||||
Pop $0
|
||||
${If} $0 == error
|
||||
Abort
|
||||
${EndIf}
|
||||
${NSD_CreateLabel} 0 0 100% 20u "$(UNINSTALL_DATA_INTRO)"
|
||||
Pop $0
|
||||
${NSD_CreateCheckbox} 0 26u 100% 14u "$(UNINSTALL_LOCAL)"
|
||||
Pop $UnLocalControl
|
||||
${NSD_SetState} $UnLocalControl $UnLocal
|
||||
${NSD_CreateLabel} 9u 39u 95% 20u "$(UNINSTALL_LOCAL_DETAIL)"
|
||||
Pop $0
|
||||
${NSD_CreateCheckbox} 0 66u 100% 14u "$(UNINSTALL_ALL)"
|
||||
Pop $UnAllControl
|
||||
${NSD_SetState} $UnAllControl $UnAll
|
||||
${NSD_OnClick} $UnAllControl un.AllDataChanged
|
||||
${NSD_CreateCheckbox} 14u 82u 95% 14u "$(UNINSTALL_DESKTOP)"
|
||||
Pop $UnDesktopControl
|
||||
${NSD_SetState} $UnDesktopControl $UnDesktop
|
||||
${If} $UnHome == ""
|
||||
EnableWindow $UnAllControl 0
|
||||
EnableWindow $UnDesktopControl 0
|
||||
${EndIf}
|
||||
${If} $UnAll == 1
|
||||
EnableWindow $UnDesktopControl 0
|
||||
${EndIf}
|
||||
${NSD_CreateLabel} 23u 95u 90% 25u "$(UNINSTALL_DESKTOP_DETAIL)"
|
||||
Pop $0
|
||||
nsDialogs::Show
|
||||
FunctionEnd
|
||||
|
||||
Function un.AllDataChanged
|
||||
Pop $0
|
||||
${NSD_GetState} $UnAllControl $UnAll
|
||||
${If} $UnAll == 1
|
||||
MessageBox MB_OKCANCEL|MB_ICONEXCLAMATION|MB_DEFBUTTON2 "$(UNINSTALL_ALL_WARNING)" /SD IDCANCEL IDOK confirmed
|
||||
StrCpy $UnAll 0
|
||||
${NSD_SetState} $UnAllControl 0
|
||||
Return
|
||||
confirmed:
|
||||
${NSD_GetState} $UnDesktopControl $UnPreviousDesktop
|
||||
StrCpy $UnDesktop 1
|
||||
${NSD_SetState} $UnDesktopControl 1
|
||||
EnableWindow $UnDesktopControl 0
|
||||
${Else}
|
||||
StrCpy $UnDesktop $UnPreviousDesktop
|
||||
${NSD_SetState} $UnDesktopControl $UnPreviousDesktop
|
||||
EnableWindow $UnDesktopControl 1
|
||||
${EndIf}
|
||||
FunctionEnd
|
||||
|
||||
Function un.DataPageLeave
|
||||
${NSD_GetState} $UnLocalControl $UnLocal
|
||||
${NSD_GetState} $UnAllControl $UnAll
|
||||
${NSD_GetState} $UnDesktopControl $UnDesktop
|
||||
FunctionEnd
|
||||
|
||||
; The helper refuses unsafe roots and never descends into reparse points.
|
||||
Function un.RemoveData
|
||||
System::Call '$PLUGINSDIR\window-frame.dll::UninstallRemoveData(w "$UnTarget", w "$INSTDIR") i.r0 ?c'
|
||||
${If} $0 != 0
|
||||
DetailPrint "$(UNINSTALL_DATA_FAILED)"
|
||||
MessageBox MB_OK|MB_ICONEXCLAMATION "$(UNINSTALL_DATA_FAILED)" /SD IDOK
|
||||
SetErrorLevel 2
|
||||
Abort
|
||||
${EndIf}
|
||||
FunctionEnd
|
||||
|
||||
Function un.CleanData
|
||||
${If} ${isUpdated}
|
||||
Return
|
||||
${EndIf}
|
||||
${If} $UnAll != 1
|
||||
StrCpy $UnTarget $INSTDIR
|
||||
Call un.PreserveHome
|
||||
${EndIf}
|
||||
${If} ${Silent}
|
||||
Return
|
||||
${EndIf}
|
||||
${If} $UnAll == 1
|
||||
StrCpy $UnTarget $UnHome
|
||||
Call un.RemoveData
|
||||
${ElseIf} $UnDesktop == 1
|
||||
StrCpy $UnTarget "$UnHome\profiles\desktop"
|
||||
Call un.RemoveData
|
||||
${EndIf}
|
||||
${If} $UnLocal == 1
|
||||
StrCpy $UnTarget "$APPDATA\${PRODUCT_FILENAME}"
|
||||
Call un.PreserveHome
|
||||
Call un.RemoveData
|
||||
!ifdef APP_PACKAGE_NAME
|
||||
StrCpy $UnTarget "$APPDATA\${APP_PACKAGE_NAME}"
|
||||
Call un.PreserveHome
|
||||
Call un.RemoveData
|
||||
!endif
|
||||
StrCpy $UnTarget "$LOCALAPPDATA\${DSH_UPDATER_CACHE_NAME}"
|
||||
Call un.PreserveHome
|
||||
Call un.RemoveData
|
||||
${EndIf}
|
||||
FunctionEnd
|
||||
|
||||
Function un.PreserveHome
|
||||
${If} $UnAll == 1
|
||||
Return
|
||||
${EndIf}
|
||||
System::Call '$PLUGINSDIR\window-frame.dll::UninstallPathsOverlap(w "$UnTarget", w "$UnHome") i.r0 ?c'
|
||||
${If} $0 != 0
|
||||
MessageBox MB_OK|MB_ICONEXCLAMATION "$(UNINSTALL_HOME_CONFLICT)" /SD IDOK
|
||||
SetErrorLevel 2
|
||||
Abort
|
||||
${EndIf}
|
||||
FunctionEnd
|
||||
@@ -12,9 +12,22 @@
|
||||
#include <algorithm>
|
||||
#include "progress.h"
|
||||
#include "extract.h"
|
||||
#include "uninstall-data.h"
|
||||
|
||||
using namespace Gdiplus;
|
||||
|
||||
// Returns a Win32 error code; no cleanup request may traverse a linked root.
|
||||
extern "C" __declspec(dllexport) DWORD __cdecl UninstallRemoveData(LPCWSTR path, LPCWSTR installation) {
|
||||
return uninstall_data::Remove(path, installation);
|
||||
}
|
||||
|
||||
// Invalid paths cannot establish separation from retained Harness data.
|
||||
extern "C" __declspec(dllexport) BOOL __cdecl UninstallPathsOverlap(LPCWSTR left, LPCWSTR right) {
|
||||
std::wstring a, b;
|
||||
return !uninstall_data::Normalize(left, a) || !uninstall_data::Normalize(right, b)
|
||||
|| uninstall_data::Contains(a, b) || uninstall_data::Contains(b, a);
|
||||
}
|
||||
|
||||
// Match the affected executable, not another user's or directory's same-named application.
|
||||
// Returns 0 while running, 1 when absent, and -1 if the process list cannot be read.
|
||||
extern "C" __declspec(dllexport) int __cdecl InstallerFindProcess(LPCWSTR executable) {
|
||||
|
||||
@@ -1,15 +1,27 @@
|
||||
!include "LogicLib.nsh"
|
||||
!define INSTALLER_SOURCE_DIR "${__FILEDIR__}\..\installer"
|
||||
!define /ifndef INSTALLER_BUILD_DIR "${__FILEDIR__}\..\.desktop-build\targets\win-x64\installer-ui"
|
||||
!ifdef BUILD_UNINSTALLER
|
||||
Var UnHome
|
||||
Var UnTarget
|
||||
!endif
|
||||
|
||||
ManifestDPIAware true
|
||||
!ifndef BUILD_UNINSTALLER
|
||||
ManifestDPIAware true
|
||||
!define MUI_CUSTOMFUNCTION_GUIINIT InstallerGuiInit
|
||||
!endif
|
||||
|
||||
!macro customHeader
|
||||
!define /ifndef INSTALLER_STRINGS_FILE "${INSTALLER_SOURCE_DIR}\strings.nsh"
|
||||
!include "${INSTALLER_STRINGS_FILE}"
|
||||
!ifdef BUILD_UNINSTALLER
|
||||
BrandingText " "
|
||||
SetFont "Segoe UI" 9
|
||||
!ifdef LANG_SIMPCHINESE
|
||||
SetFont /LANG=${LANG_SIMPCHINESE} "Microsoft YaHei UI" 9
|
||||
!endif
|
||||
!include "${INSTALLER_SOURCE_DIR}\uninstall.nsh"
|
||||
!endif
|
||||
!ifndef BUILD_UNINSTALLER
|
||||
!include "${INSTALLER_SOURCE_DIR}\theme.nsh"
|
||||
!include "${INSTALLER_SOURCE_DIR}\pages.nsh"
|
||||
@@ -74,6 +86,19 @@
|
||||
Page custom InstallerWelcome InstallerWelcomeLeave
|
||||
!macroend
|
||||
|
||||
!macro customUnWelcomePage
|
||||
!insertmacro MUI_UNPAGE_WELCOME
|
||||
UninstPage custom un.DataPage un.DataPageLeave
|
||||
!macroend
|
||||
|
||||
!macro customUnInit
|
||||
Call un.DataInit
|
||||
!macroend
|
||||
|
||||
!macro customUnInstall
|
||||
Call un.CleanData
|
||||
!macroend
|
||||
|
||||
!macro customPageAfterChangeDir
|
||||
!define MUI_PAGE_CUSTOMFUNCTION_PRE InstallerBeforeInstall
|
||||
!define MUI_PAGE_CUSTOMFUNCTION_SHOW InstallerProgressShow
|
||||
@@ -163,6 +188,8 @@
|
||||
${EndIf}
|
||||
!insertmacro InstallerPublishStage 4
|
||||
!insertmacro dshFinishDirectories
|
||||
; Explorer associates Start menu shortcuts with this entry only through InstallLocation; the upstream template records it elsewhere.
|
||||
WriteRegStr SHELL_CONTEXT "${UNINSTALL_REGISTRY_KEY}" InstallLocation "$INSTDIR"
|
||||
${If} $0 == 1
|
||||
SetErrors
|
||||
${Else}
|
||||
|
||||
@@ -14,11 +14,21 @@ $visualStudio = & $vswhere -latest -products '*' -requires Microsoft.VisualStudi
|
||||
if (-not $visualStudio) { throw 'Visual Studio C++ Build Tools are missing.' }
|
||||
$vcvars = Join-Path $visualStudio 'VC/Auxiliary/Build/vcvars32.bat'
|
||||
$compileScript = Join-Path $output 'compile-frame.cmd'
|
||||
$compileLines = @('@echo off', ('call "{0}" >nul' -f $vcvars), 'if errorlevel 1 exit /b %errorlevel%', ('cl /nologo /LD /MT /O1 /W4 /WX /EHsc "{0}" /Fo"{1}" /link /OUT:"{2}" /IMPLIB:"{3}" user32.lib comctl32.lib dwmapi.lib gdiplus.lib ole32.lib shell32.lib uuid.lib' -f $source, (Join-Path $output 'window-frame.obj'), $library, (Join-Path $output 'window-frame.lib')))
|
||||
$compileLines = @('@echo off', ('call "{0}" >nul' -f $vcvars), 'if errorlevel 1 exit /b %errorlevel%', ('cl /nologo /LD /MT /O1 /W4 /WX /EHsc "{0}" /Fo"{1}" /link /OUT:"{2}" /IMPLIB:"{3}" user32.lib comctl32.lib dwmapi.lib gdiplus.lib ole32.lib shell32.lib uuid.lib advapi32.lib' -f $source, (Join-Path $output 'window-frame.obj'), $library, (Join-Path $output 'window-frame.lib')))
|
||||
[IO.File]::WriteAllLines($compileScript, $compileLines, [Text.Encoding]::Default)
|
||||
& $env:ComSpec /d /c $compileScript
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Native installer helper compilation failed.' }
|
||||
if ($TestProgress -or $CompileProgressOnly) {
|
||||
$cleanupSource = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '../tests/windows-uninstall-data.cpp'))
|
||||
$cleanupExecutable = Join-Path $output 'uninstall-data-test.exe'
|
||||
$cleanupScript = Join-Path $output 'compile-uninstall-data-test.cmd'
|
||||
[IO.File]::WriteAllLines($cleanupScript, @('@echo off', ('call "{0}" >nul' -f $vcvars), 'if errorlevel 1 exit /b %errorlevel%', ('cl /nologo /MT /W4 /WX /EHsc "{0}" /Fo"{1}" /Fe"{2}" /link shell32.lib ole32.lib uuid.lib advapi32.lib' -f $cleanupSource, (Join-Path $output 'uninstall-data-test.obj'), $cleanupExecutable)), [Text.Encoding]::Default)
|
||||
& $env:ComSpec /d /c $cleanupScript
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Uninstall data test compilation failed.' }
|
||||
if ($TestProgress) {
|
||||
& $cleanupExecutable (Join-Path $output ('cleanup-' + [Guid]::NewGuid().ToString('N')))
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Uninstall data regression failed.' }
|
||||
}
|
||||
$testSource = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '../tests/windows-installer-progress.cpp'))
|
||||
$testExecutable = Join-Path $output 'progress-test.exe'
|
||||
$testScript = Join-Path $output 'compile-progress-test.cmd'
|
||||
|
||||
@@ -61,8 +61,10 @@ try {
|
||||
await sign({ path: join(output, 'ui', 'window-frame.dll'), hash: 'sha256', isNest: false })
|
||||
installWindowsNsisBootstrapSigner({ sign })
|
||||
}
|
||||
await execute(progressTest, [], childOptions)
|
||||
await execute(presentationTest, [], childOptions)
|
||||
if (!process.argv.includes('--uninstall-only')) {
|
||||
await execute(progressTest, [], childOptions)
|
||||
await execute(presentationTest, [], childOptions)
|
||||
}
|
||||
const payloadSource = join(output, 'payload.nsi')
|
||||
await writeFile(payloadSource, `Unicode true
|
||||
RequestExecutionLevel user
|
||||
@@ -81,12 +83,12 @@ SectionEnd
|
||||
await execute(compiler.path, ['/V2', payloadSource], { ...childOptions, env: { ...childOptions.env, ...compiler.env } })
|
||||
if (sign) await sign({ path: join(payload, `${productName}.exe`), hash: 'sha256', isNest: false })
|
||||
const sourceStrings = await readFile(join(appRoot, 'installer', 'strings.nsh'), 'utf8')
|
||||
const config = createElectronBuilderConfig()
|
||||
if (sign) {
|
||||
config.win.forceCodeSigning = true
|
||||
config.win.signtoolOptions.sign = sign
|
||||
}
|
||||
for (const language of ['en_US', 'zh_CN']) {
|
||||
const config = createElectronBuilderConfig()
|
||||
if (sign) {
|
||||
config.win.forceCodeSigning = true
|
||||
config.win.signtoolOptions.sign = sign
|
||||
}
|
||||
const languageOutput = join(output, language)
|
||||
await mkdir(languageOutput)
|
||||
const strings = join(languageOutput, 'strings.nsh')
|
||||
@@ -96,12 +98,16 @@ SectionEnd
|
||||
const include = join(languageOutput, 'include.nsh')
|
||||
await writeFile(include, `!define INSTALLER_BUILD_DIR "${join(output, 'ui')}"\n!define INSTALLER_STRINGS_FILE "${strings}"\n!include "${join(appRoot, 'scripts', 'installer.nsh')}"\n`)
|
||||
await build({ projectDir: appRoot, prepackaged: payload, targets: Platform.WINDOWS.createTarget(['nsis'], Arch.x64), publish: 'never',
|
||||
config: { ...config, productName, artifactName: 'installer-test.exe', directories: { output: languageOutput },
|
||||
config: { ...config, productName, extraMetadata: { ...config.extraMetadata, name: `harness-installer-test-${id}` },
|
||||
artifactName: 'installer-test.exe', directories: { output: languageOutput },
|
||||
nsis: { ...config.nsis, guid, include, installerLanguages: [language] }, beforeBuild: undefined, afterPack: undefined, afterSign: undefined, artifactBuildCompleted: undefined },
|
||||
})
|
||||
if (process.argv.includes('--compile-only')) continue
|
||||
const result = await execute('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File',
|
||||
join(appRoot, 'tests', 'windows-installer-smoke.ps1'), '-Installer', join(languageOutput, 'installer-test.exe'),
|
||||
'-ProductName', productName, '-RegistryKey', guid, '-OutputDirectory', languageOutput], childOptions)
|
||||
join(appRoot, 'tests', process.argv.includes('--uninstall-only') ? 'windows-uninstall-smoke.ps1' : 'windows-installer-smoke.ps1'),
|
||||
'-Installer', join(languageOutput, 'installer-test.exe'),
|
||||
'-ProductName', productName, '-RegistryKey', guid, '-OutputDirectory', languageOutput,
|
||||
...process.argv.includes('--uninstall-only') ? ['-Language', languageId, '-PackageName', `harness-installer-test-${id}`] : []], childOptions)
|
||||
process.stdout.write(`${language}\n${result.stdout}`)
|
||||
}
|
||||
succeeded = true
|
||||
|
||||
@@ -14,5 +14,12 @@ export function directoryInstallSection(source: string): string
|
||||
*/
|
||||
export function directoryInstallerExits(source: string): string
|
||||
|
||||
/**
|
||||
* Keep user-data removal exclusive to the interactive custom page.
|
||||
* @param source - Pinned upstream uninstaller source.
|
||||
* @returns Long-path uninstaller without implicit data removal.
|
||||
*/
|
||||
export function directoryUninstaller(source: string): string
|
||||
|
||||
/** Install the build-only adapter while retaining signed uninstaller generation. */
|
||||
export function installWindowsDirectoryInstaller(): void
|
||||
@@ -78,9 +78,20 @@ export function installWindowsDirectoryInstaller() {
|
||||
adapted = replaceOnce(adapted, `!include "${helper}"`, `!include "${path}"`)
|
||||
}
|
||||
const uninstaller = join(directory, 'uninstaller.nsh')
|
||||
await writeFile(uninstaller, replaceOnce(await readFile(join(templates, 'uninstaller.nsh'), 'utf8'),
|
||||
'RMDir /r $INSTDIR', 'RMDir /r "\\\\?\\$INSTDIR"'))
|
||||
await writeFile(uninstaller, directoryUninstaller(await readFile(join(templates, 'uninstaller.nsh'), 'utf8')))
|
||||
adapted = replaceOnce(adapted, '!include "uninstaller.nsh"', `!include "${uninstaller}"`)
|
||||
return `!define DSH_SEVENZIP_PATH "${tool}"\n!define DSH_SEVENZIP_LICENSE_DIR "${dirname(dirname(sourceTool))}"\n${await compute.call(this, adapted, ...args)}`
|
||||
return `!define DSH_UPDATER_CACHE_NAME "${this.packager.appInfo.updaterCacheDirName}"\n!define DSH_SEVENZIP_PATH "${tool}"\n!define DSH_SEVENZIP_LICENSE_DIR "${dirname(dirname(sourceTool))}"\n${await compute.call(this, adapted, ...args)}`
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep data removal in the opt-in custom UI, including for legacy command-line flags.
|
||||
* @param {string} source - Pinned upstream uninstaller source.
|
||||
* @returns Uninstaller with long-path application removal and no implicit data removal.
|
||||
*/
|
||||
export function directoryUninstaller(source) {
|
||||
const start = source.indexOf(' Var /GLOBAL isDeleteAppData\n')
|
||||
const end = source.indexOf(' DeleteRegKey SHELL_CONTEXT "${UNINSTALL_REGISTRY_KEY}"', start)
|
||||
if (start < 0 || end < 0) throw new Error('NSIS uninstaller data removal template changed')
|
||||
return replaceOnce(source.slice(0, start) + source.slice(end), 'RMDir /r $INSTDIR', 'RMDir /r "\\\\?\\$INSTDIR"')
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
type MenuItemConstructorOptions,
|
||||
} from 'electron'
|
||||
import { resolveDesktopPaths } from './paths.ts'
|
||||
import { recordUninstallLocation } from './uninstall-location.ts'
|
||||
import { DesktopProjectManager } from './project-manager.ts'
|
||||
import { DesktopHostProcess, DesktopHostUncleanExitError } from './host-process.ts'
|
||||
import { installDesktopDirectoryPicker } from './directory-picker.ts'
|
||||
@@ -234,6 +235,7 @@ async function main(): Promise<void> {
|
||||
const resources = runtimeResources()
|
||||
const paths = resolveDesktopPaths()
|
||||
const development = !app.isPackaged
|
||||
if (process.platform === 'win32' && !development) await recordUninstallLocation(app.getPath('userData'), paths.profile)
|
||||
const activeProject = paths.profile
|
||||
const manager = new DesktopProjectManager(paths, resources)
|
||||
let quitting = false
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
/** Records the active Harness home for the Windows uninstaller without loading plugins. */
|
||||
import { writeFile } from 'node:fs/promises'
|
||||
import { dirname, join } from 'node:path'
|
||||
|
||||
/**
|
||||
* Persist the home used by this Desktop launch in the existing Electron user-data directory.
|
||||
* @param userData - Electron's application data directory.
|
||||
* @param profile - Absolute reserved desktop profile directory.
|
||||
* @returns Completion of the UTF-16 INI write consumed by NSIS.
|
||||
*/
|
||||
export async function recordUninstallLocation(userData: string, profile: string): Promise<void> {
|
||||
const home = dirname(dirname(profile))
|
||||
if (/[\r\n\0]/.test(home)) throw new Error('Desktop uninstall location contains an unsupported character')
|
||||
await writeFile(join(userData, 'uninstall.ini'), `\uFEFF[Harness]\r\nHome=${home}\r\nHomeLength=${home.length}\r\n`, 'utf16le')
|
||||
}
|
||||
@@ -8,6 +8,7 @@
|
||||
"welcome-presented-on-first-show",
|
||||
"successful-install-paints-100-before-finish",
|
||||
"registered-directory-with-trailing-separators",
|
||||
"uninstall-entry-install-location",
|
||||
"registered-directory-and-checked-launch",
|
||||
"launch-failure-retry-and-prompt-dismissal",
|
||||
"progress-remains-monotonic-across-native-resets",
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"defaultCleanupState": 0,
|
||||
"cases": ["preserve", "desktop", "all", "local", "silent", "upgrade"]
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
/** The uninstaller reads the last launched home even when its environment differs. */
|
||||
import { mkdtemp, readFile, rm } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { expect, it } from 'vitest'
|
||||
import { recordUninstallLocation } from '../src/uninstall-location.ts'
|
||||
|
||||
it('records Unicode custom homes as a Windows-readable INI and replaces a previous launch', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'desktop-uninstall-'))
|
||||
try {
|
||||
await recordUninstallLocation(root, join(root, '旧目录', 'profiles', 'desktop'))
|
||||
const home = join(root, '新目录')
|
||||
await recordUninstallLocation(root, join(home, 'profiles', 'desktop'))
|
||||
expect(await readFile(join(root, 'uninstall.ini'), 'utf16le')).toBe(`\uFEFF[Harness]\r\nHome=${home}\r\nHomeLength=${home.length}\r\n`)
|
||||
await expect(recordUninstallLocation(root, join(root, 'bad\nHome=other', 'profiles', 'desktop'))).rejects.toThrow('unsupported character')
|
||||
expect(await readFile(join(root, 'uninstall.ini'), 'utf16le')).toContain(home)
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
@@ -3,12 +3,24 @@ import { readFileSync } from 'node:fs'
|
||||
import { createRequire } from 'node:module'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { expect, it } from 'vitest'
|
||||
import { directoryInstallerExits, directoryInstallSection } from '../scripts/windows-directory-installer.mjs'
|
||||
import { directoryInstallerExits, directoryInstallSection, directoryUninstaller } from '../scripts/windows-directory-installer.mjs'
|
||||
|
||||
const require = createRequire(import.meta.url)
|
||||
const section = readFileSync(join(dirname(require.resolve('app-builder-lib/package.json')),
|
||||
'templates/nsis/installSection.nsh'), 'utf8')
|
||||
|
||||
it('leaves data cleanup to the interactive page while retaining application removal and registration cleanup', () => {
|
||||
const source = readFileSync(join(dirname(require.resolve('app-builder-lib/package.json')), 'templates/nsis/uninstaller.nsh'), 'utf8')
|
||||
const adapted = directoryUninstaller(source)
|
||||
expect(adapted).not.toContain('--delete-app-data')
|
||||
expect(adapted).not.toContain('RMDir /r "$APPDATA')
|
||||
expect(adapted).toContain('!insertmacro customUnInstall')
|
||||
expect(adapted).toContain('DeleteRegKey SHELL_CONTEXT "${UNINSTALL_REGISTRY_KEY}"')
|
||||
expect(adapted).toContain('RMDir /r "\\\\?\\$INSTDIR"')
|
||||
expect(() => directoryUninstaller(source.replace(' Var /GLOBAL isDeleteAppData\n', ''))).toThrow('template changed')
|
||||
expect(() => directoryUninstaller(source.replace(' DeleteRegKey SHELL_CONTEXT "${UNINSTALL_REGISTRY_KEY}"', ''))).toThrow('template changed')
|
||||
})
|
||||
|
||||
it.each(['allowOnlyOneInstallerInstance.nsh', 'installUtil.nsh'])('cleans staged files before %s exits', (helper) => {
|
||||
const source = readFileSync(join(dirname(require.resolve('app-builder-lib/package.json')), 'templates/nsis/include', helper), 'utf8')
|
||||
const exits = source.match(/^\s*Quit\s*$/gm) ?? []
|
||||
|
||||
@@ -170,6 +170,9 @@ try {
|
||||
throw 'Trailing separators changed the registered installation directory'
|
||||
}
|
||||
$results.Add('registered-directory-with-trailing-separators')
|
||||
$uninstallEntry = Get-ItemProperty ('HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\' + $RegistryKey)
|
||||
if ($uninstallEntry.InstallLocation.TrimEnd('\') -ne $installPath) { throw 'Uninstall entry lacks the InstallLocation Explorer matches Start menu shortcuts against' }
|
||||
$results.Add('uninstall-entry-install-location')
|
||||
$timer = [Diagnostics.Stopwatch]::StartNew()
|
||||
do {
|
||||
$app = Get-Process -Name $ProductName -ErrorAction SilentlyContinue
|
||||
|
||||
@@ -197,8 +197,10 @@ public static class InstallerCapture {
|
||||
RedrawWindow(window, IntPtr.Zero, IntPtr.Zero, 0x181);
|
||||
}
|
||||
|
||||
public static string Save(IntPtr window, string path) {
|
||||
Reveal(window);
|
||||
public static string Save(IntPtr window, string path) { return SaveNative(window, path, true); }
|
||||
|
||||
public static string SaveNative(IntPtr window, string path, bool waitForInstaller) {
|
||||
if (waitForInstaller) Reveal(window);
|
||||
Rect rect;
|
||||
if (!GetWindowRect(window, out rect)) throw new InvalidOperationException("Could not read preview bounds");
|
||||
int width = rect.Right - rect.Left, height = rect.Bottom - rect.Top;
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
// Native cleanup regressions operate only in the caller's private test directory.
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#define NOMINMAX
|
||||
#define UNICODE
|
||||
#include <windows.h>
|
||||
#include <cassert>
|
||||
#include "../installer/uninstall-data.h"
|
||||
|
||||
static void File(const std::wstring& path) {
|
||||
HANDLE file = CreateFileW(path.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
assert(file != INVALID_HANDLE_VALUE);
|
||||
DWORD count;
|
||||
assert(WriteFile(file, "retained", 8, &count, nullptr));
|
||||
CloseHandle(file);
|
||||
}
|
||||
|
||||
int wmain(int argc, wchar_t** argv) {
|
||||
assert(argc == 2);
|
||||
const std::wstring root = argv[1];
|
||||
const std::wstring installation = root + L"\\application";
|
||||
const std::wstring home = root + L"\\home";
|
||||
assert(CreateDirectoryW(root.c_str(), nullptr));
|
||||
assert(CreateDirectoryW(installation.c_str(), nullptr));
|
||||
assert(CreateDirectoryW(home.c_str(), nullptr));
|
||||
assert(CreateDirectoryW((home + L"\\profiles").c_str(), nullptr));
|
||||
const std::wstring desktop = home + L"\\profiles\\desktop";
|
||||
assert(CreateDirectoryW(desktop.c_str(), nullptr));
|
||||
File(home + L"\\session.jsonl");
|
||||
File(desktop + L"\\plugin.json");
|
||||
assert(uninstall_data::Remove(root.c_str(), installation.c_str()) == ERROR_ACCESS_DENIED);
|
||||
assert(uninstall_data::Remove(L"C:\\", installation.c_str()) == ERROR_INVALID_NAME);
|
||||
assert(uninstall_data::Remove(L"relative", installation.c_str()) == ERROR_INVALID_NAME);
|
||||
assert(uninstall_data::Remove(L"C:\\bad*", installation.c_str()) == ERROR_INVALID_NAME);
|
||||
PWSTR profile = nullptr;
|
||||
assert(SUCCEEDED(SHGetKnownFolderPath(FOLDERID_Profile, 0, nullptr, &profile)));
|
||||
assert(uninstall_data::Remove(profile, installation.c_str()) == ERROR_ACCESS_DENIED);
|
||||
CoTaskMemFree(profile);
|
||||
HANDLE held = CreateFileW((desktop + L"\\plugin.json").c_str(), GENERIC_READ, FILE_SHARE_READ,
|
||||
nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
assert(held != INVALID_HANDLE_VALUE);
|
||||
assert(uninstall_data::Remove(desktop.c_str(), installation.c_str()) == ERROR_SHARING_VIOLATION);
|
||||
CloseHandle(held);
|
||||
assert(uninstall_data::Remove(desktop.c_str(), installation.c_str()) == ERROR_SUCCESS);
|
||||
assert(GetFileAttributesW((home + L"\\session.jsonl").c_str()) != INVALID_FILE_ATTRIBUTES);
|
||||
assert(uninstall_data::Remove(desktop.c_str(), installation.c_str()) == ERROR_SUCCESS);
|
||||
assert(uninstall_data::Remove(home.c_str(), installation.c_str()) == ERROR_SUCCESS);
|
||||
assert(GetFileAttributesW(home.c_str()) == INVALID_FILE_ATTRIBUTES);
|
||||
assert(RemoveDirectoryW(installation.c_str()));
|
||||
assert(RemoveDirectoryW(root.c_str()));
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
<# Production uninstaller checks with isolated application identity and seeded data. #>
|
||||
[CmdletBinding()]
|
||||
param([Parameter(Mandatory)][string]$Installer, [Parameter(Mandatory)][string]$ProductName,
|
||||
[Parameter(Mandatory)][string]$RegistryKey, [Parameter(Mandatory)][string]$OutputDirectory,
|
||||
[Parameter(Mandatory)][string]$Language, [Parameter(Mandatory)][string]$PackageName)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$OutputDirectory = [IO.Path]::GetFullPath($OutputDirectory)
|
||||
. (Join-Path $PSScriptRoot 'windows-installer-ui.ps1')
|
||||
[InstallerCapture]::Initialize()
|
||||
$copy = @{}
|
||||
$expected = Get-Content (Join-Path $PSScriptRoot 'expected/windows-uninstall.json') -Raw | ConvertFrom-Json
|
||||
Get-Content (Join-Path $PSScriptRoot '../installer/strings.nsh') -Encoding UTF8 | ForEach-Object {
|
||||
if ($_ -match ('^LangString (UNINSTALL_\w+) \$\{LANG_' + $Language + '\} "(.*)"$')) { $copy[$Matches[1]] = $Matches[2] }
|
||||
}
|
||||
$installPath = Join-Path $OutputDirectory 'Uninstall App'
|
||||
$homePath = Join-Path $OutputDirectory 'Harness Home'
|
||||
$desktopPath = Join-Path $homePath 'profiles/desktop'
|
||||
$externalPath = Join-Path $OutputDirectory 'External Project'
|
||||
$localPath = Join-Path ([Environment]::GetFolderPath('ApplicationData')) $ProductName
|
||||
$cachePath = Join-Path ([Environment]::GetFolderPath('LocalApplicationData')) ($PackageName + '-updater')
|
||||
$uninstaller = Join-Path $OutputDirectory 'uninstall-copy.exe'
|
||||
$process = $null
|
||||
function Wait-Text([string]$Text) {
|
||||
$timer = [Diagnostics.Stopwatch]::StartNew()
|
||||
do {
|
||||
$control = [InstallerCapture]::FindText($process.Id, $Text)
|
||||
if ($control -ne [IntPtr]::Zero) { return $control }
|
||||
if ($process.HasExited) { throw "Uninstaller exited: $($process.ExitCode)" }
|
||||
Start-Sleep -Milliseconds 25
|
||||
} while ($timer.Elapsed.TotalSeconds -lt 20)
|
||||
throw "Missing '$Text': $([InstallerCapture]::VisibleText($process.Id))"
|
||||
}
|
||||
function State([IntPtr]$Control) { return [InstallerCapture]::SendMessage($Control, 0xF0, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() }
|
||||
function Wait-State([IntPtr]$Control, [int]$Expected) {
|
||||
$timer = [Diagnostics.Stopwatch]::StartNew()
|
||||
while ((State $Control) -ne $Expected) {
|
||||
if ($timer.Elapsed.TotalSeconds -gt 10) { throw "Checkbox state did not become $Expected" }
|
||||
Start-Sleep -Milliseconds 25
|
||||
}
|
||||
}
|
||||
function Wait-Exit {
|
||||
if (-not $process.WaitForExit(30000)) { $process.Kill(); $process.WaitForExit(); throw 'Uninstaller timed out' }
|
||||
if ($process.ExitCode -ne 0) { throw "Uninstall failed: $($process.ExitCode)" }
|
||||
$process.Dispose()
|
||||
$script:process = $null
|
||||
}
|
||||
try {
|
||||
foreach ($mode in $expected.cases) {
|
||||
$setup = Start-Process -FilePath $Installer -ArgumentList ('/S /D=' + $installPath) -PassThru -WindowStyle Hidden
|
||||
try {
|
||||
if (-not $setup.WaitForExit(30000)) { $setup.Kill(); $setup.WaitForExit(); throw 'Setup timed out' }
|
||||
if ($setup.ExitCode -ne 0) { throw "Setup failed: $($setup.ExitCode)" }
|
||||
} finally { $setup.Dispose() }
|
||||
foreach ($path in @($desktopPath, $localPath, $cachePath, $externalPath)) { New-Item -ItemType Directory -Force -Path $path | Out-Null }
|
||||
[IO.File]::WriteAllText((Join-Path $externalPath 'keep.txt'), 'outside data root')
|
||||
if (-not (Test-Path -LiteralPath (Join-Path $desktopPath 'linked-project'))) {
|
||||
New-Item -ItemType Junction -Path (Join-Path $desktopPath 'linked-project') -Target $externalPath | Out-Null
|
||||
}
|
||||
[IO.File]::WriteAllText((Join-Path $homePath 'session.txt'), 'keep session')
|
||||
[IO.File]::WriteAllText((Join-Path $desktopPath 'plugin.txt'), 'desktop plugin')
|
||||
[IO.File]::WriteAllText((Join-Path $localPath 'draft.txt'), 'unsent draft')
|
||||
[IO.File]::WriteAllText((Join-Path $cachePath 'download.txt'), 'update')
|
||||
[IO.File]::WriteAllText((Join-Path $localPath 'uninstall.ini'), "[Harness]`r`nHome=$homePath`r`nHomeLength=$($homePath.Length)`r`n", [Text.Encoding]::Unicode)
|
||||
Copy-Item -LiteralPath (Join-Path $installPath ('Uninstall ' + $ProductName + '.exe')) -Destination $uninstaller -Force
|
||||
$arguments = '_?=' + $installPath
|
||||
if ($mode -eq 'silent') { $arguments = '/S --delete-app-data ' + $arguments }
|
||||
if ($mode -eq 'upgrade') { $arguments = '/S --updated ' + $arguments }
|
||||
$process = Start-Process -FilePath $uninstaller -ArgumentList $arguments -PassThru -WindowStyle Hidden
|
||||
if ($mode -notin @('silent', 'upgrade')) {
|
||||
$welcomeText = if ($Language -eq 'ENGLISH') { 'Welcome' } else { -join [char[]]@(0x6B22, 0x8FCE) }
|
||||
$welcome = Wait-Text $welcomeText
|
||||
$window = [InstallerCapture]::TopLevel($welcome)
|
||||
[void][InstallerCapture]::SaveNative($window, (Join-Path $OutputDirectory 'uninstall-welcome.png'), $false)
|
||||
[InstallerCapture]::Click([InstallerCapture]::GetDlgItem($window, 1))
|
||||
$all = Wait-Text $copy.UNINSTALL_ALL
|
||||
$desktop = Wait-Text $copy.UNINSTALL_DESKTOP
|
||||
$local = Wait-Text $copy.UNINSTALL_LOCAL
|
||||
if ((State $all) -ne $expected.defaultCleanupState -or (State $desktop) -ne $expected.defaultCleanupState -or (State $local) -ne $expected.defaultCleanupState) { throw 'Data removal defaults differ from the expected output' }
|
||||
[void][InstallerCapture]::SaveNative($window, (Join-Path $OutputDirectory 'uninstall-options.png'), $false)
|
||||
if ($mode -eq 'desktop' -or $mode -eq 'all') {
|
||||
[InstallerCapture]::Click($desktop)
|
||||
Wait-State $desktop 1
|
||||
[InstallerCapture]::Click($all)
|
||||
$warning = Wait-Text ($copy.UNINSTALL_ALL_WARNING.Split('$')[0])
|
||||
$dialog = [InstallerCapture]::TopLevel($warning)
|
||||
[void][InstallerCapture]::SaveNative($dialog, (Join-Path $OutputDirectory 'uninstall-warning.png'), $false)
|
||||
# Rejecting all-data cleanup must preserve the independently selected child.
|
||||
[InstallerCapture]::Click([InstallerCapture]::GetDlgItem($dialog, 2))
|
||||
Wait-State $all 0
|
||||
if ((State $desktop) -ne 1) { throw 'Cancel changed the independent desktop selection' }
|
||||
if ($mode -eq 'all') {
|
||||
[InstallerCapture]::Click($all)
|
||||
$warning = Wait-Text ($copy.UNINSTALL_ALL_WARNING.Split('$')[0])
|
||||
$dialog = [InstallerCapture]::TopLevel($warning)
|
||||
[InstallerCapture]::Click([InstallerCapture]::GetDlgItem($dialog, 1))
|
||||
Wait-State $desktop 1
|
||||
}
|
||||
}
|
||||
if ($mode -eq 'local') { [InstallerCapture]::Click($local); Wait-State $local 1 }
|
||||
[InstallerCapture]::Click([InstallerCapture]::GetDlgItem($window, 1))
|
||||
$finishedText = if ($Language -eq 'ENGLISH') { 'has been uninstalled' } else { -join [char[]]@(0x5DF2, 0x7ECF, 0x4ECE) }
|
||||
[void](Wait-Text $finishedText)
|
||||
[InstallerCapture]::Click([InstallerCapture]::GetDlgItem($window, 1))
|
||||
}
|
||||
Wait-Exit
|
||||
if (Test-Path -LiteralPath $installPath) { throw 'Application directory remained' }
|
||||
if ([IO.File]::ReadAllText((Join-Path $externalPath 'keep.txt')) -ne 'outside data root') { throw 'Cleanup followed a junction into a project' }
|
||||
if ((Test-Path (Join-Path $homePath 'session.txt')) -ne ($mode -ne 'all')) { throw "Session retention failed: $mode" }
|
||||
if ((Test-Path (Join-Path $desktopPath 'plugin.txt')) -ne ($mode -notin @('all', 'desktop'))) { throw "Profile retention failed: $mode" }
|
||||
if ((Test-Path (Join-Path $localPath 'draft.txt')) -ne ($mode -ne 'local')) { throw "Local data retention failed: $mode" }
|
||||
if ((Test-Path (Join-Path $cachePath 'download.txt')) -ne ($mode -ne 'local')) { throw "Update cache retention failed: $mode" }
|
||||
Write-Output "passed: $mode"
|
||||
}
|
||||
} finally {
|
||||
if ($process) { if (-not $process.HasExited) { $process.Kill(); $process.WaitForExit() }; $process.Dispose() }
|
||||
# Only unique test identities below known application-data parents are removed.
|
||||
foreach ($pair in @(@($localPath, [Environment]::GetFolderPath('ApplicationData')), @($cachePath, [Environment]::GetFolderPath('LocalApplicationData')))) {
|
||||
$target = [IO.Path]::GetFullPath($pair[0])
|
||||
if ([IO.Path]::GetDirectoryName($target) -ne $pair[1] -or -not ([IO.Path]::GetFileName($target).StartsWith('Harness Installer Test ') -or [IO.Path]::GetFileName($target).StartsWith('harness-installer-test-'))) { throw 'Unexpected fixture cleanup path' }
|
||||
if (Test-Path -LiteralPath $target) { Remove-Item -LiteralPath $target -Recurse -Force }
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user