diff --git a/script/link.ps1 b/script/link.ps1 index ed95166..c43ce39 100644 --- a/script/link.ps1 +++ b/script/link.ps1 @@ -25,12 +25,22 @@ param( [switch]$Apply, [string]$HomeDir = $HOME, - [string]$RepoRoot = (Split-Path -Parent $PSScriptRoot) + [string]$RepoRoot = '' ) Set-StrictMode -Version Latest $ErrorActionPreference = 'Stop' +# Windows PowerShell 5.1 does not populate $PSScriptRoot while the param block +# is evaluated, so a default value that uses it fails there with +# "Split-Path: cannot bind argument to parameter 'Path' because it is an empty +# string". The repository root is resolved after the param block instead, which +# works on both Windows PowerShell 5.1 and PowerShell 7. An explicit +# -RepoRoot still wins (rebuildup/dotfiles#260). +if (-not $RepoRoot) { + $RepoRoot = Split-Path -Parent $PSScriptRoot +} + if ([System.Environment]::OSVersion.Platform -ne [System.PlatformID]::Win32NT) { [Console]::Error.WriteLine('link.ps1 targets Windows; use script/link on POSIX hosts.') exit 2 diff --git a/script/link.windows.test.ts b/script/link.windows.test.ts index f5eadc6..4394c98 100644 --- a/script/link.windows.test.ts +++ b/script/link.windows.test.ts @@ -207,4 +207,26 @@ describeWin("link.ps1 (Windows adoption adapter)", () => { expect(readFileSync(target, "utf8")).toContain("managed"); }); }); + + test("runs under Windows PowerShell 5.1 without an explicit repository root", () => { + withTemp((root) => { + const repo = makeRepo(root, { initSubmodule: true }); + const home = join(root, "home"); + mkdirSync(home); + // Windows PowerShell 5.1 does not populate $PSScriptRoot while the param + // block is evaluated, so a default value that uses it fails there. The + // repository root has to be resolved in the script body instead + // (rebuildup/dotfiles#260). The script is copied into the fixture repo so + // that the resolved root is the fixture and nothing outside the temp + // directory is read. + const scriptDir = join(repo, "script"); + mkdirSync(scriptDir, { recursive: true }); + const script = join(scriptDir, "link.ps1"); + writeFileSync(script, readFileSync(LINK_PS1)); + const r = run(["powershell.exe", "-NoProfile", "-File", script, "-HomeDir", home]); + expect(r.err).not.toContain("Split-Path"); + expect(r.code).toBe(0); + expect(r.out).toContain("would-link .gitconfig"); + }); + }); });