Turn any website into a lightweight desktop app with one command, on macOS, Windows and Linux.
Rust chatgptclaudeclidesktopdesktop-appelectron-alternativegeminilinuxmacosnativefierno-electronrusttauriweb-to-desktopwebsite-to-appwebviewwindowsyoutube
feat: add an opt-in GNU/MinGW toolchain for Windows builds (#1383)
Paragon1fe55a88b835
diff --git a/bin/builders/BaseBuilder.ts b/bin/builders/BaseBuilder.tsindex 5495f905..0cdd695c 100644--- a/bin/builders/BaseBuilder.ts+++ b/bin/builders/BaseBuilder.ts@@ -4,7 +4,13 @@ import chalk from 'chalk';import prompts from 'prompts';import { PakeAppOptions } from '@/types';-import { checkRustInstalled, ensureRustEnv, installRust } from '@/helpers/rust';+import {+ checkRustInstalled,+ ensureRustEnv,+ hasWindowsGnuToolchain,+ hasWindowsMsvcBuildTools,+ installRust,+} from '@/helpers/rust';import { mergeConfig } from '@/helpers/merge';import tauriConfig from '@/helpers/tauriConfig';import {@@ -18,7 +24,7 @@ import { BuildArtifact, isInteractive } from '@/utils/output';import { shellExec, type ShellCommand } from '@/utils/shell';import { hasReadyTauriCli } from '@/utils/tauri-cli';import { CN_MIRROR_ENV, isCnMirrorEnabled } from '@/utils/mirror';-import { IS_MAC } from '@/utils/platform';+import { IS_MAC, IS_WIN } from '@/utils/platform';import logger from '@/options/logger';import {configureCargoRegistry,@@ -27,6 +33,7 @@ import {getBuildTimeout,getInstallCommand,getInstallTimeout,+ getWindowsGnuBuildEnvironment,} from './env';// Appended to the error when a Linux AppImage build fails for good. linuxdeploy's// diagnostics stream to the terminal (stdio: 'inherit') and never reach@@ -133,6 +140,20 @@ export default abstract class BaseBuilder {ensureRustEnv();+ if (+ IS_WIN &&+ this.options.windowsToolchain !== 'gnu' &&+ !hasWindowsMsvcBuildTools() &&+ hasWindowsGnuToolchain()+ ) {+ logger.warn(+ '✼ No Visual Studio Build Tools detected, but a MinGW/GNU toolchain (gcc) is available.',+ );+ logger.warn(+ '✼ If the build fails to link, retry with --windows-toolchain gnu.',+ );+ }+if (!checkRustInstalled()) {if (!isInteractive()) {throw new PakeError('Rust required to package your webapp.', {@@ -266,8 +287,11 @@ export default abstract class BaseBuilder {logger.info('✸ Building app...');const baseEnv = getBuildEnvironment();+ const isWindowsGnuBuild =+ process.platform === 'win32' && this.options.windowsToolchain === 'gnu';let buildEnv: Record<string, string> = {...(baseEnv ?? {}),+ ...(isWindowsGnuBuild ? getWindowsGnuBuildEnvironment() : {}),...(process.env.NO_STRIP ? { NO_STRIP: process.env.NO_STRIP } : {}),};diff --git a/bin/builders/WinBuilder.ts b/bin/builders/WinBuilder.tsindex a3b668d4..7ffc03f1 100644--- a/bin/builders/WinBuilder.ts+++ b/bin/builders/WinBuilder.ts@@ -7,6 +7,14 @@ import type { ShellCommand } from '@/utils/shell';export default class WinBuilder extends BaseBuilder {private buildFormat: string = 'msi';private buildArch: string;+ private toolchain: 'msvc' | 'gnu';++ // MSYS2/MinGW only ships an x86_64 GCC toolchain, so gnu is x64-only;+ // arm64 falls through to getTauriTarget returning null, which the+ // existing call sites already turn into "Unsupported architecture".+ private static readonly GNU_ARCH_MAPPINGS: Record<string, string> = {+ x64: 'x86_64-pc-windows-gnu',+ };constructor(options: PakeAppOptions) {super(options);@@ -14,6 +22,7 @@ export default class WinBuilder extends BaseBuilder {this.buildArch = validArchs.includes(options.targets || '')? this.resolveTargetArch(options.targets): this.resolveTargetArch('auto');+ this.toolchain = options.windowsToolchain === 'gnu' ? 'gnu' : 'msvc';this.options.targets = this.buildFormat;}@@ -21,6 +30,16 @@ export default class WinBuilder extends BaseBuilder {return this.buildArch;}+ protected getTauriTarget(+ arch: string,+ platform: NodeJS.Platform = 'win32',+ ): string | null {+ if (this.toolchain === 'gnu') {+ return WinBuilder.GNU_ARCH_MAPPINGS[arch] || null;+ }+ return super.getTauriTarget(arch, platform);+ }+getFileName(): string {const { name } = this.options;const language = this.options.installerLanguage;diff --git a/bin/builders/env.ts b/bin/builders/env.tsindex f14845d2..3e011387 100644--- a/bin/builders/env.ts+++ b/bin/builders/env.ts@@ -31,6 +31,29 @@ export function getBuildEnvironment(): Record<string, string> | undefined {};}+/**+ * Build scripts and proc-macros compile for the rustup *host* toolchain, not+ * the `--target` triple, even when cross-compiling. Pake's own+ * rust-toolchain.toml pins a bare channel (no host), which rustup resolves+ * against the machine's configured default host — msvc on most Windows+ * installs, regardless of whether MSVC is actually present. Without this,+ * a gnu `--target` build still shells out to the (possibly missing) MSVC+ * `link.exe` for every build script. RUSTUP_TOOLCHAIN is rustup's documented+ * per-invocation override (read by the cargo/rustc proxies it installs) and+ * only affects this build subprocess. Left alone if the user already set it.+ */+export function getWindowsGnuBuildEnvironment(): Record<string, string> {+ const excludeAllSymbols = '-C link-args=-Wl,--exclude-all-symbols';+ const existingRustflags = process.env.RUSTFLAGS;+ return {+ RUSTFLAGS: existingRustflags+ ? `${existingRustflags} ${excludeAllSymbols}`+ : excludeAllSymbols,+ RUSTUP_TOOLCHAIN:+ process.env.RUSTUP_TOOLCHAIN || 'stable-x86_64-pc-windows-gnu',+ };+}+/*** Windows needs more time due to native compilation and antivirus scanning.*/diff --git a/bin/helpers/cli-program.ts b/bin/helpers/cli-program.tsindex 24a11c70..09cc1aea 100644--- a/bin/helpers/cli-program.ts+++ b/bin/helpers/cli-program.ts@@ -111,6 +111,12 @@ ${green('|_| \\__,_|_|\\_\\___| can turn any webpage into a desktop app with'Build target format for your system',).default(DEFAULT.targets),)+ .addOption(+ new Option(+ '--windows-toolchain <toolchain>',+ 'Windows Rust toolchain: msvc (default, requires Visual Studio Build Tools) or gnu (MinGW/MSYS2, for machines without them)',+ ).choices(['msvc', 'gnu']),+ ).addOption(new Option('--app-version <string>',diff --git a/bin/helpers/rust.ts b/bin/helpers/rust.tsindex 804fd340..00d8a0b9 100644--- a/bin/helpers/rust.ts+++ b/bin/helpers/rust.ts@@ -132,3 +132,52 @@ export function checkRustInstalled() {return false;}}++function getVsWherePath(): string {+ const programFilesX86 =+ process.env['ProgramFiles(x86)'] || 'C:\\Program Files (x86)';+ return path.join(+ programFilesX86,+ 'Microsoft Visual Studio',+ 'Installer',+ 'vswhere.exe',+ );+}++/**+ * Detects Visual Studio Build Tools the way rustc itself does: via the VS+ * installer's vswhere.exe, not PATH. cl.exe/link.exe are normally absent+ * from PATH even on a fully working MSVC setup (rustc locates them through+ * the same registry vswhere reads), so checking PATH directly would warn on+ * most MSVC machines.+ */+export function hasWindowsMsvcBuildTools(): boolean {+ const vswhere = getVsWherePath();+ if (!fsExtra.pathExistsSync(vswhere)) return false;+ try {+ const { stdout } = execaSync(vswhere, [+ '-products',+ '*',+ '-requires',+ 'Microsoft.VisualStudio.Component.VC.Tools.x86.x64',+ '-property',+ 'installationPath',+ ]);+ return stdout.trim().length > 0;+ } catch {+ return false;+ }+}++/**+ * MinGW/MSYS2's gcc drives the GNU Windows target directly off PATH (no+ * registry lookup involved), so a PATH check is the correct signal here.+ */+export function hasWindowsGnuToolchain(): boolean {+ try {+ execaSync('gcc', ['--version'], { stdio: 'ignore' });+ return true;+ } catch {+ return false;+ }+}diff --git a/bin/types.ts b/bin/types.tsindex d1770ecb..8a790fa8 100644--- a/bin/types.ts+++ b/bin/types.ts@@ -69,6 +69,11 @@ export interface PakeCliOptions {// Linux: "deb", "appimage", "rpm", "zst" and "*-arm64" variants; Windows: "x64", "arm64"; macOS: "intel", "apple", "universal"targets: string;+ // Windows Rust toolchain: 'msvc' (default, Tauri's recommended toolchain)+ // or 'gnu' (MinGW/MSYS2, for machines without Visual Studio Build Tools).+ // Undefined keeps today's msvc-only behavior. Windows only; ignored elsewhere.+ windowsToolchain?: 'msvc' | 'gnu';+// Debug mode, outputs more logsdebug: boolean;diff --git a/dist/cli.js b/dist/cli.jsindex d1889efe..7b0e7afb 100644--- a/dist/cli.js+++ b/dist/cli.js@@ -787,6 +787,49 @@ function checkRustInstalled() {return false;}}+function getVsWherePath() {+ const programFilesX86 = process.env['ProgramFiles(x86)'] || 'C:\\Program Files (x86)';+ return path.join(programFilesX86, 'Microsoft Visual Studio', 'Installer', 'vswhere.exe');+}+/**+ * Detects Visual Studio Build Tools the way rustc itself does: via the VS+ * installer's vswhere.exe, not PATH. cl.exe/link.exe are normally absent+ * from PATH even on a fully working MSVC setup (rustc locates them through+ * the same registry vswhere reads), so checking PATH directly would warn on+ * most MSVC machines.+ */+function hasWindowsMsvcBuildTools() {+ const vswhere = getVsWherePath();+ if (!fsExtra.pathExistsSync(vswhere))+ return false;+ try {+ const { stdout } = execaSync(vswhere, [+ '-products',+ '*',+ '-requires',+ 'Microsoft.VisualStudio.Component.VC.Tools.x86.x64',+ '-property',+ 'installationPath',+ ]);+ return stdout.trim().length > 0;+ }+ catch {+ return false;+ }+}+/**+ * MinGW/MSYS2's gcc drives the GNU Windows target directly off PATH (no+ * registry lookup involved), so a PATH check is the correct signal here.+ */+function hasWindowsGnuToolchain() {+ try {+ execaSync('gcc', ['--version'], { stdio: 'ignore' });+ return true;+ }+ catch {+ return false;+ }+}async function combineFiles(files, output) {const contents = await Promise.all(files.map(async (file) => {@@ -1361,6 +1404,27 @@ function getBuildEnvironment() {PATH: buildPath,};}+/**+ * Build scripts and proc-macros compile for the rustup *host* toolchain, not+ * the `--target` triple, even when cross-compiling. Pake's own+ * rust-toolchain.toml pins a bare channel (no host), which rustup resolves+ * against the machine's configured default host — msvc on most Windows+ * installs, regardless of whether MSVC is actually present. Without this,+ * a gnu `--target` build still shells out to the (possibly missing) MSVC+ * `link.exe` for every build script. RUSTUP_TOOLCHAIN is rustup's documented+ * per-invocation override (read by the cargo/rustc proxies it installs) and+ * only affects this build subprocess. Left alone if the user already set it.+ */+function getWindowsGnuBuildEnvironment() {+ const excludeAllSymbols = '-C link-args=-Wl,--exclude-all-symbols';+ const existingRustflags = process.env.RUSTFLAGS;+ return {+ RUSTFLAGS: existingRustflags+ ? `${existingRustflags} ${excludeAllSymbols}`+ : excludeAllSymbols,+ RUSTUP_TOOLCHAIN: process.env.RUSTUP_TOOLCHAIN || 'stable-x86_64-pc-windows-gnu',+ };+}/*** Windows needs more time due to native compilation and antivirus scanning.*/@@ -1575,6 +1639,13 @@ class BaseBuilder {logger.warn('✼ See more in https://tauri.app/start/prerequisites/.');}ensureRustEnv();+ if (IS_WIN &&+ this.options.windowsToolchain !== 'gnu' &&+ !hasWindowsMsvcBuildTools() &&+ hasWindowsGnuToolchain()) {+ logger.warn('✼ No Visual Studio Build Tools detected, but a MinGW/GNU toolchain (gcc) is available.');+ logger.warn('✼ If the build fails to link, retry with --windows-toolchain gnu.');+ }if (!checkRustInstalled()) {if (!isInteractive()) {throw new PakeError('Rust required to package your webapp.', {@@ -1675,8 +1746,10 @@ class BaseBuilder {// entries feed the --json warnings array and this is a status line.logger.info('✸ Building app...');const baseEnv = getBuildEnvironment();+ const isWindowsGnuBuild = process.platform === 'win32' && this.options.windowsToolchain === 'gnu';let buildEnv = {...(baseEnv ?? {}),+ ...(isWindowsGnuBuild ? getWindowsGnuBuildEnvironment() : {}),...(process.env.NO_STRIP ? { NO_STRIP: process.env.NO_STRIP } : {}),};const resolveExecEnv = () => Object.keys(buildEnv).length > 0 ? buildEnv : undefined;@@ -2038,11 +2111,18 @@ class WinBuilder extends BaseBuilder {this.buildArch = validArchs.includes(options.targets || '')? this.resolveTargetArch(options.targets): this.resolveTargetArch('auto');+ this.toolchain = options.windowsToolchain === 'gnu' ? 'gnu' : 'msvc';this.options.targets = this.buildFormat;}getReportArch() {return this.buildArch;}+ getTauriTarget(arch, platform = 'win32') {+ if (this.toolchain === 'gnu') {+ return WinBuilder.GNU_ARCH_MAPPINGS[arch] || null;+ }+ return super.getTauriTarget(arch, platform);+ }getFileName() {const { name } = this.options;const language = this.options.installerLanguage;@@ -2082,6 +2162,12 @@ class WinBuilder extends BaseBuilder {return `pake-${generateIdentifierSafeName(appName)}.exe`;}}+// MSYS2/MinGW only ships an x86_64 GCC toolchain, so gnu is x64-only;+// arm64 falls through to getTauriTarget returning null, which the+// existing call sites already turn into "Unsupported architecture".+WinBuilder.GNU_ARCH_MAPPINGS = {+ x64: 'x86_64-pc-windows-gnu',+};class LinuxBuilder extends BaseBuilder {constructor(options) {@@ -3537,6 +3623,7 @@ ${green('|_| \\__,_|_|\\_\\___| can turn any webpage into a desktop app with.default(DEFAULT_PAKE_OPTIONS.userAgent).hideHelp()).addOption(new Option('--targets <string>', 'Build target format for your system').default(DEFAULT_PAKE_OPTIONS.targets))+ .addOption(new Option('--windows-toolchain <toolchain>', 'Windows Rust toolchain: msvc (default, requires Visual Studio Build Tools) or gnu (MinGW/MSYS2, for machines without them)').choices(['msvc', 'gnu'])).addOption(new Option('--app-version <string>', 'App version, the same as package.json version').default(DEFAULT_PAKE_OPTIONS.appVersion).hideHelp())diff --git a/docs/cli-usage.md b/docs/cli-usage.mdindex 248d2706..ab123e2a 100644--- a/docs/cli-usage.md+++ b/docs/cli-usage.md@@ -359,6 +359,22 @@ Specify the build target architecture or format:- Use `--target appimage-arm64` for portable ARM64 applications that work across different ARM64 Linux distributions.- Use `--targets zst` on Arch Linux based distributions to produce a `.pkg.tar.zst` package directly. Pake follows Tauri's AUR packaging guidance by building the Linux package payload first, then emitting Arch package metadata and zstd-compressed output. Requires `binutils` (for `ar`) and `libarchive` (for `bsdtar`).+#### [windows-toolchain]++Select the Rust toolchain used for Windows builds. Windows only; ignored on other platforms.++- `msvc` (default): Tauri's recommended toolchain. Requires [Visual Studio Build Tools](https://tauri.app/start/prerequisites/#windows) with the "Desktop development with C++" workload.+- `gnu`: builds against a MinGW/MSYS2 toolchain instead, for machines that have Rust and a GNU toolchain (e.g. via [MSYS2](https://www.msys2.org/)) but not Visual Studio Build Tools. Only `x64` is supported (MSYS2 does not ship an ARM64 GCC toolchain for this target). Requires `gcc`, `ld` and `dlltool` on `PATH`.++```shell+--windows-toolchain <msvc|gnu>++# Example: build with MinGW/MSYS2 instead of MSVC+--windows-toolchain gnu+```++If no MSVC Build Tools are detected and a GNU toolchain is available, Pake logs a hint to retry with `--windows-toolchain gnu` rather than failing deep in the build with an unexplained linker error. Requesting `gnu` does not change your default Rust toolchain or any global `rustup`/environment settings — it only affects the current build subprocess.+#### [no-bundle]Skip packaging and output only the compiled executable. Linux only. Useful on RPM-based distros (Fedora, RHEL, Oracle Linux, etc.) where the native bundler can abort during the packaging stage, so you still get a runnable binary.diff --git a/docs/cli-usage_CN.md b/docs/cli-usage_CN.mdindex 92c24ab9..c1dba6a2 100644--- a/docs/cli-usage_CN.md+++ b/docs/cli-usage_CN.md@@ -357,6 +357,22 @@ pake https://github.com --name GitHub- 使用 `--target appimage-arm64` 可以创建便携式 ARM64 应用,在不同的 ARM64 Linux 发行版上运行。- 在基于 Arch Linux 的发行版上使用 `--targets zst` 可直接生成 `.pkg.tar.zst` 包。Pake 会按 Tauri 的 AUR 打包说明先生成 Linux 包内容,再写入 Arch 包元数据并输出 zstd 压缩包。需要预先安装 `binutils`(提供 `ar`)和 `libarchive`(提供 `bsdtar`)。+#### [windows-toolchain]++选择 Windows 构建使用的 Rust 工具链。仅适用于 Windows,其他平台忽略此选项。++- `msvc`(默认):Tauri 推荐的工具链,需要安装 [Visual Studio Build Tools](https://tauri.app/start/prerequisites/#windows)(勾选“使用 C++ 的桌面开发”工作负载)。+- `gnu`:改用 MinGW/MSYS2 工具链构建,适合已安装 Rust 和 GNU 工具链(例如通过 [MSYS2](https://www.msys2.org/))但没有安装 Visual Studio Build Tools 的机器。仅支持 `x64`(MSYS2 未提供该目标的 ARM64 GCC 工具链)。需要 `PATH` 中包含 `gcc`、`ld` 和 `dlltool`。++```shell+--windows-toolchain <msvc|gnu>++# 示例:使用 MinGW/MSYS2 而非 MSVC 构建+--windows-toolchain gnu+```++如果未检测到 MSVC Build Tools 但检测到可用的 GNU 工具链,Pake 会提示可以改用 `--windows-toolchain gnu` 重试,而不是让构建在链接阶段以难以理解的错误失败。使用 `gnu` 不会更改你的默认 Rust 工具链或任何全局 `rustup`/环境设置,仅影响当次构建子进程。+#### [no-bundle]跳过打包,只输出编译好的可执行文件。仅 Linux 可用。适用于 Fedora、RHEL、Oracle Linux 等 RPM 系发行版,这些系统上原生打包器可能在打包阶段中止,用此选项仍能拿到可运行的二进制。diff --git a/schema/pake.schema.json b/schema/pake.schema.jsonindex 1c8c4286..12cd50e6 100644--- a/schema/pake.schema.json+++ b/schema/pake.schema.json@@ -105,6 +105,11 @@"type": "string","description": "Build target format. Linux: deb/appimage/rpm/zst and *-arm64 variants (comma-separated allowed); Windows: x64/arm64; macOS: intel/apple/universal/app/dmg. Defaults to the platform installer format."},+ "windowsToolchain": {+ "type": "string",+ "enum": ["msvc", "gnu"],+ "description": "Windows Rust toolchain: msvc (default, requires Visual Studio Build Tools) or gnu (MinGW/MSYS2, for machines without them). Windows only; ignored elsewhere."+ },"appVersion": {"type": "string","description": "App version written into the bundle.",diff --git a/tests/unit/windows-toolchain-detection.test.ts b/tests/unit/windows-toolchain-detection.test.tsnew file mode 100644index 00000000..49ca6d34--- /dev/null+++ b/tests/unit/windows-toolchain-detection.test.ts@@ -0,0 +1,77 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++const execaSyncMock = vi.hoisted(() => vi.fn());+const pathExistsSyncMock = vi.hoisted(() => vi.fn());++vi.mock('execa', () => ({ execaSync: execaSyncMock }));+vi.mock('fs-extra', () => ({+ default: { pathExistsSync: pathExistsSyncMock },+}));++import {+ hasWindowsGnuToolchain,+ hasWindowsMsvcBuildTools,+} from '@/helpers/rust';++describe('hasWindowsMsvcBuildTools', () => {+ afterEach(() => {+ execaSyncMock.mockReset();+ pathExistsSyncMock.mockReset();+ delete process.env['ProgramFiles(x86)'];+ });++ it('returns false when vswhere.exe is not present', () => {+ pathExistsSyncMock.mockReturnValue(false);++ expect(hasWindowsMsvcBuildTools()).toBe(false);+ expect(execaSyncMock).not.toHaveBeenCalled();+ });++ it('returns true when vswhere reports an installation with the VC tools component', () => {+ pathExistsSyncMock.mockReturnValue(true);+ execaSyncMock.mockReturnValue({+ stdout: 'C:\\Program Files\\Microsoft Visual Studio\\2022\\Community',+ });++ expect(hasWindowsMsvcBuildTools()).toBe(true);+ });++ it('returns false when vswhere finds no matching installation', () => {+ pathExistsSyncMock.mockReturnValue(true);+ execaSyncMock.mockReturnValue({ stdout: ' ' });++ expect(hasWindowsMsvcBuildTools()).toBe(false);+ });++ it('returns false when vswhere itself fails', () => {+ pathExistsSyncMock.mockReturnValue(true);+ execaSyncMock.mockImplementation(() => {+ throw new Error('vswhere crashed');+ });++ expect(hasWindowsMsvcBuildTools()).toBe(false);+ });+});++describe('hasWindowsGnuToolchain', () => {+ afterEach(() => {+ execaSyncMock.mockReset();+ });++ it('returns true when gcc is on PATH', () => {+ execaSyncMock.mockReturnValue({ stdout: '' });++ expect(hasWindowsGnuToolchain()).toBe(true);+ expect(execaSyncMock).toHaveBeenCalledWith('gcc', ['--version'], {+ stdio: 'ignore',+ });+ });++ it('returns false when gcc is not found', () => {+ execaSyncMock.mockImplementation(() => {+ throw new Error('not found');+ });++ expect(hasWindowsGnuToolchain()).toBe(false);+ });+});diff --git a/tests/unit/windows-toolchain-warning.test.ts b/tests/unit/windows-toolchain-warning.test.tsnew file mode 100644index 00000000..d1107e5e--- /dev/null+++ b/tests/unit/windows-toolchain-warning.test.ts@@ -0,0 +1,98 @@+import path from 'path';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++vi.mock('@/utils/dir', () => ({+ npmDirectory: process.cwd(),+ tauriConfigDirectory: path.join(process.cwd(), 'src-tauri', '.pake'),+}));+vi.mock('@/utils/tauri-cli', () => ({+ hasReadyTauriCli: vi.fn(async () => true),+}));+const rustHelperMocks = vi.hoisted(() => ({+ checkRustInstalled: vi.fn(() => true),+ ensureRustEnv: vi.fn(),+ installRust: vi.fn(),+ hasWindowsMsvcBuildTools: vi.fn(() => false),+ hasWindowsGnuToolchain: vi.fn(() => false),+}));+vi.mock('@/helpers/rust', () => rustHelperMocks);+vi.mock('@/utils/platform', async (original) => ({+ ...(await original<object>()),+ IS_MAC: false,+ IS_WIN: true,+ IS_LINUX: false,+}));++import BaseBuilder from '@/builders/BaseBuilder';+import logger from '@/options/logger';++class TestBuilder extends BaseBuilder {+ getFileName(): string {+ return 'test-app';+ }+}++describe('BaseBuilder.prepare() Windows toolchain hint', () => {+ const realProcess = process;++ beforeEach(() => {+ vi.stubGlobal('process', { ...realProcess, platform: 'win32' });+ rustHelperMocks.checkRustInstalled.mockReturnValue(true);+ rustHelperMocks.hasWindowsMsvcBuildTools.mockReturnValue(false);+ rustHelperMocks.hasWindowsGnuToolchain.mockReturnValue(false);+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ });++ it('warns when MSVC is missing, gnu is available, and no toolchain was requested', async () => {+ rustHelperMocks.hasWindowsGnuToolchain.mockReturnValue(true);+ const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(() => {});+ const builder = new TestBuilder({} as any);++ await builder.prepare();++ expect(warnSpy).toHaveBeenCalledWith(+ expect.stringContaining('--windows-toolchain gnu'),+ );+ });++ it('does not warn when the user already requested gnu explicitly', async () => {+ rustHelperMocks.hasWindowsGnuToolchain.mockReturnValue(true);+ const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(() => {});+ const builder = new TestBuilder({ windowsToolchain: 'gnu' } as any);++ await builder.prepare();++ expect(warnSpy).not.toHaveBeenCalledWith(+ expect.stringContaining('--windows-toolchain gnu'),+ );+ });++ it('does not warn when no gnu toolchain is available either', async () => {+ rustHelperMocks.hasWindowsGnuToolchain.mockReturnValue(false);+ const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(() => {});+ const builder = new TestBuilder({} as any);++ await builder.prepare();++ expect(warnSpy).not.toHaveBeenCalledWith(+ expect.stringContaining('--windows-toolchain gnu'),+ );+ });++ it('does not warn when MSVC Build Tools are present', async () => {+ rustHelperMocks.hasWindowsMsvcBuildTools.mockReturnValue(true);+ rustHelperMocks.hasWindowsGnuToolchain.mockReturnValue(true);+ const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(() => {});+ const builder = new TestBuilder({} as any);++ await builder.prepare();++ expect(warnSpy).not.toHaveBeenCalledWith(+ expect.stringContaining('--windows-toolchain gnu'),+ );+ });+});diff --git a/tests/unit/windows-toolchain.test.ts b/tests/unit/windows-toolchain.test.tsnew file mode 100644index 00000000..4fac4b6b--- /dev/null+++ b/tests/unit/windows-toolchain.test.ts@@ -0,0 +1,187 @@+import path from 'path';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++vi.mock('@/utils/dir', () => ({+ npmDirectory: process.cwd(),+ tauriConfigDirectory: path.join(process.cwd(), 'src-tauri', '.pake'),+}));+vi.mock('@/utils/shell', () => ({ shellExec: vi.fn() }));+vi.mock('@/utils/platform', async (original) => ({+ ...(await original<object>()),+ IS_MAC: false,+ IS_WIN: true,+ IS_LINUX: false,+}));++import BaseBuilder from '@/builders/BaseBuilder';+import WinBuilder from '@/builders/WinBuilder';+import { getWindowsGnuBuildEnvironment } from '@/builders/env';+import { shellExec } from '@/utils/shell';+import { PakeAppOptions } from '@/types';++const makeWinBuilder = (targets: string, windowsToolchain?: 'msvc' | 'gnu') =>+ new WinBuilder({+ name: 'Demo',+ appVersion: '1.0.0',+ installerLanguage: 'en-US',+ targets,+ windowsToolchain,+ } as PakeAppOptions);++describe('WinBuilder toolchain target selection', () => {+ it('keeps the default msvc triples when windowsToolchain is not set', () => {+ expect((makeWinBuilder('x64') as any).getTauriTarget('x64')).toBe(+ 'x86_64-pc-windows-msvc',+ );+ expect((makeWinBuilder('arm64') as any).getTauriTarget('arm64')).toBe(+ 'aarch64-pc-windows-msvc',+ );+ });++ it('keeps the msvc triples when windowsToolchain is explicitly msvc', () => {+ expect(+ (makeWinBuilder('x64', 'msvc') as any).getTauriTarget('x64'),+ ).toBe('x86_64-pc-windows-msvc');+ });++ it('maps x64 to the gnu triple when windowsToolchain is gnu', () => {+ const builder = makeWinBuilder('x64', 'gnu');+ expect((builder as any).getTauriTarget('x64')).toBe(+ 'x86_64-pc-windows-gnu',+ );+ });++ it('has no gnu mapping for arm64, matching MSYS2/MinGW only shipping x86_64', () => {+ const builder = makeWinBuilder('arm64', 'gnu');+ expect((builder as any).getTauriTarget('arm64')).toBeNull();+ });++ it('throws the existing unsupported-architecture error for arm64+gnu', () => {+ const builder = makeWinBuilder('arm64', 'gnu');+ expect(() => (builder as any).getBuildCommand('pnpm')).toThrow(+ 'Unsupported architecture: arm64 for Windows',+ );+ });++ it('routes the gnu triple through the real build command and bundle path', () => {+ const builder = makeWinBuilder('x64', 'gnu');+ const command = (builder as any).getBuildCommand('pnpm');+ expect(command.args).toContain('x86_64-pc-windows-gnu');++ const basePath = (builder as any).getBasePath();+ expect(basePath.split(path.sep)).toContain('x86_64-pc-windows-gnu');+ });+});++describe('getWindowsGnuBuildEnvironment', () => {+ const originalRustflags = process.env.RUSTFLAGS;+ const originalRustupToolchain = process.env.RUSTUP_TOOLCHAIN;++ afterEach(() => {+ if (originalRustflags === undefined) {+ delete process.env.RUSTFLAGS;+ } else {+ process.env.RUSTFLAGS = originalRustflags;+ }+ if (originalRustupToolchain === undefined) {+ delete process.env.RUSTUP_TOOLCHAIN;+ } else {+ process.env.RUSTUP_TOOLCHAIN = originalRustupToolchain;+ }+ });++ it('sets the exclude-all-symbols flag and the gnu host toolchain when unset', () => {+ delete process.env.RUSTFLAGS;+ delete process.env.RUSTUP_TOOLCHAIN;+ expect(getWindowsGnuBuildEnvironment()).toEqual({+ RUSTFLAGS: '-C link-args=-Wl,--exclude-all-symbols',+ RUSTUP_TOOLCHAIN: 'stable-x86_64-pc-windows-gnu',+ });+ });++ it('appends to an existing RUSTFLAGS instead of overwriting it', () => {+ process.env.RUSTFLAGS = '-C target-cpu=native';+ delete process.env.RUSTUP_TOOLCHAIN;+ expect(getWindowsGnuBuildEnvironment()).toEqual({+ RUSTFLAGS:+ '-C target-cpu=native -C link-args=-Wl,--exclude-all-symbols',+ RUSTUP_TOOLCHAIN: 'stable-x86_64-pc-windows-gnu',+ });+ });++ it('keeps an explicit RUSTUP_TOOLCHAIN the user already set', () => {+ delete process.env.RUSTFLAGS;+ process.env.RUSTUP_TOOLCHAIN = '1.95.0-x86_64-pc-windows-gnu';+ expect(getWindowsGnuBuildEnvironment()).toEqual({+ RUSTFLAGS: '-C link-args=-Wl,--exclude-all-symbols',+ RUSTUP_TOOLCHAIN: '1.95.0-x86_64-pc-windows-gnu',+ });+ });+});++class TestBuilder extends BaseBuilder {+ getFileName(): string {+ return 'test-app';+ }+}++describe('BaseBuilder.runBuildCommand Windows GNU RUSTFLAGS injection', () => {+ const realProcess = process;++ beforeEach(() => {+ vi.mocked(shellExec).mockReset().mockResolvedValue(0);+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ });++ it('injects the exclude-all-symbols RUSTFLAGS on win32 when windowsToolchain is gnu', async () => {+ vi.stubGlobal('process', { ...realProcess, platform: 'win32' });+ delete process.env.RUSTFLAGS;+ const builder = new TestBuilder({+ debug: true,+ windowsToolchain: 'gnu',+ } as any);++ await (builder as any).runBuildCommand(+ { executable: 'pnpm', args: ['run', 'build:debug'] },+ 'msi',+ );++ const env = vi.mocked(shellExec).mock.calls[0][2];+ expect(env).toMatchObject({+ RUSTFLAGS: '-C link-args=-Wl,--exclude-all-symbols',+ });+ });++ it('does not inject RUSTFLAGS when windowsToolchain is msvc (default)', async () => {+ vi.stubGlobal('process', { ...realProcess, platform: 'win32' });+ const builder = new TestBuilder({ debug: true } as any);++ await (builder as any).runBuildCommand(+ { executable: 'pnpm', args: ['run', 'build:debug'] },+ 'msi',+ );++ const env = vi.mocked(shellExec).mock.calls[0][2];+ expect(env?.RUSTFLAGS).toBeUndefined();+ });++ it('does not inject RUSTFLAGS on other platforms even if windowsToolchain is gnu', async () => {+ vi.stubGlobal('process', { ...realProcess, platform: 'linux' });+ const builder = new TestBuilder({+ debug: true,+ windowsToolchain: 'gnu',+ } as any);++ await (builder as any).runBuildCommand(+ { executable: 'pnpm', args: ['run', 'build:debug'] },+ 'deb',+ );++ const env = vi.mocked(shellExec).mock.calls[0][2];+ expect(env?.RUSTFLAGS).toBeUndefined();+ });+});