diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..33455b9 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +scripts/shell/switch-pathman text eol=lf +scripts/shell/switch-pathman.cmd text eol=crlf diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 0021087..9b9b5a1 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -91,6 +91,10 @@ jobs: ./tests/release-metadata.ps1 ./tests/public-build-counter.ps1 ./tests/local-build.ps1 + - name: Test shell switching + if: matrix.arch == 'x64' + shell: pwsh -NoProfile -ExecutionPolicy Bypass -File {0} + run: ./tests/shell-switch.ps1 - name: Build baseline installers if: ${{ !env.ACT }} run: ./build.ps1 -Arch $env:PATHMAN_ARCH -VersionName '0.0.0' -VersionNumber '0.0.0' -ReleaseType official diff --git a/README.md b/README.md index a491fe4..bc35721 100644 --- a/README.md +++ b/README.md @@ -152,6 +152,27 @@ pathman delete java 8 CLI 使用调用者权限。修改系统变量需在管理员终端运行,或自行使用 `sudo.exe`;权限不足时命令报错退出。 +### 终端切换脚本 + +CLI 目录同时提供三个脚本。`name`、`version` 支持命名参数或位置参数,`scope` 默认为 `shell`:`reg` 只修改注册表,`shell` 只修改当前终端,`all` 同时修改两者。当前终端切换会更新目标变量及 PATH 中对应旧版本的路径,保留其余条目。 + +```powershell +Switch-PathMan -Name java -Version 25 -Scope reg +Switch-PathMan java 25 +``` + +```cmd +switch-pathman /n node /v 24 +switch-pathman node 24 /s all +``` + +```bash +. switch-pathman --name python --version 3.12 --scope all +. switch-pathman python 3.12 +``` + +Git Bash 必须用 `.` 在当前 shell 中执行。批处理脚本内使用 CMD 版本时需用 `call switch-pathman ...`。CMD 的延迟展开需关闭,且单个变量赋值不能超过 8000 个字符或包含换行;不满足时切换报错,不截断内容。 + ## 权限与数据 桌面界面首次修改系统变量时请求 UAC,后续操作复用管理员助手。关闭窗口或闲置 15 分钟后助手退出。取消授权会保留编辑内容。 @@ -252,7 +273,6 @@ git push origin v1.0.0-beta.1 ## 开发计划 - PATH 变量卡片视图。 -- PowerShell 模块与 CMD 脚本,用于切换当前终端的临时环境变量版本。 ## 许可证 diff --git a/packaging/PathMan.nsi b/packaging/PathMan.nsi index 2d69cbb..e56af42 100644 --- a/packaging/PathMan.nsi +++ b/packaging/PathMan.nsi @@ -769,6 +769,9 @@ Section "Uninstall" !insertmacro DeleteInstalledFile "THIRD-PARTY-NOTICES.txt" !insertmacro DeleteInstalledFile "licenses\dotnet-THIRD-PARTY-NOTICES.txt" !insertmacro DeleteInstalledFile "bin\pathman.exe" + !insertmacro DeleteInstalledFile "bin\Switch-PathMan.ps1" + !insertmacro DeleteInstalledFile "bin\switch-pathman.cmd" + !insertmacro DeleteInstalledFile "bin\switch-pathman" !insertmacro DeleteInstalledFile "internal\PathMan.Service.exe" System::Call '$Helper::RemoveShim(w "$INSTDIR") i.r0' !insertmacro DeleteInstalledFile "internal\PathMan.SetupActions.dll" diff --git a/scripts/build-matrix.ps1 b/scripts/build-matrix.ps1 index 11048ab..999c605 100644 --- a/scripts/build-matrix.ps1 +++ b/scripts/build-matrix.ps1 @@ -89,6 +89,7 @@ foreach ($cpu in $Arch) { Copy-Item -LiteralPath (Join-Path $projectRoot 'LICENSE') -Destination $output Copy-Item -LiteralPath (Join-Path $projectRoot 'THIRD-PARTY-NOTICES.txt') -Destination $output Copy-Item -LiteralPath (Join-Path $projectRoot 'licenses') -Destination $output -Recurse + Copy-Item -LiteralPath (Join-Path $projectRoot 'scripts/shell/Switch-PathMan.ps1'),(Join-Path $projectRoot 'scripts/shell/switch-pathman.cmd'),(Join-Path $projectRoot 'scripts/shell/switch-pathman') -Destination (Join-Path $output 'bin') Write-ReleaseManifest $versionInfo (Join-Path $output 'release.json') $hostArch = [Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString().ToLowerInvariant() if ($Test -and ($cpu -eq $hostArch -or ($cpu -eq 'x86' -and $hostArch -eq 'x64'))) { diff --git a/scripts/package.ps1 b/scripts/package.ps1 index 9d23ad7..77daa56 100644 --- a/scripts/package.ps1 +++ b/scripts/package.ps1 @@ -52,7 +52,9 @@ foreach ($cpu in @($Arch | Select-Object -Unique)) { foreach ($file in @('PathMan.exe','bin/pathman.exe','internal/PathMan.Service.exe','internal/PathMan.Shim.exe','LICENSE')) { if (!(Test-Path -LiteralPath (Join-Path $publish $file))) { throw "Missing payload: $publish/$file. Run build.ps1 first." } } - if (@(Get-ChildItem -LiteralPath (Join-Path $publish 'bin') -File).Count -ne 1) { throw 'bin must contain only pathman.exe.' } + $cliFiles=@('pathman.exe','Switch-PathMan.ps1','switch-pathman.cmd','switch-pathman') + $actual=@(Get-ChildItem -LiteralPath (Join-Path $publish 'bin') -File|ForEach-Object Name) + if(@(Compare-Object $cliFiles $actual).Count){throw 'bin must contain the CLI and its three shell scripts.'} $identity=Get-Content (Join-Path $publish 'release.json') -Raw|ConvertFrom-Json if($identity.versionName -ne $Version -or $identity.versionNumber -ne $versionInfo.VersionNumber -or $identity.type -ne $versionInfo.Type){throw 'Published payload identity does not match the requested installer identity.'} & $compiler /V2 /INPUTCHARSET UTF8 "/DARCH=$cpu" "/DPACKAGE_TYPE=$kind" "/DVERSION=$Version" "/DVERSION_NUMERIC=$($versionInfo.Numeric)" "/DPUBLISH_DIR=$publish" "/DHELPER_DLL=$helper" "/DOUTPUT_FILE=$output" (Join-Path $projectRoot 'packaging/PathMan.nsi') diff --git a/scripts/shell/Switch-PathMan.ps1 b/scripts/shell/Switch-PathMan.ps1 new file mode 100644 index 0000000..1fc0862 --- /dev/null +++ b/scripts/shell/Switch-PathMan.ps1 @@ -0,0 +1,99 @@ +[CmdletBinding(PositionalBinding=$false)] +param( + [Parameter(Mandatory,Position=0)][Alias('n')][string]$Name, + [Parameter(Mandatory,Position=1)][Alias('v')][string]$Version, + [Alias('s')][ValidateSet('reg','shell','all')][string]$Scope='shell', + [ValidateSet('PowerShell','Cmd','Bash')][string]$OutputFormat='PowerShell', + [string]$OutputFile +) +$ErrorActionPreference='Stop' +function Invoke-PathMan([string[]]$Arguments,[string]$FailureMessage){ + $start=[Diagnostics.ProcessStartInfo]::new($cli) + $start.UseShellExecute=$false + $start.CreateNoWindow=$true + $start.RedirectStandardOutput=$true + $start.RedirectStandardError=$true + $start.StandardOutputEncoding=[Text.UTF8Encoding]::new($false) + $start.StandardErrorEncoding=[Text.UTF8Encoding]::new($false) + $start.Arguments=(@(foreach($argument in $Arguments){ + '"'+[regex]::Replace($argument,'(\\*)("|$)',{param($match) + $slashes=$match.Groups[1].Value + $slashes+$slashes+$(if($match.Groups[2].Value){'\"'}) + })+'"' + }) -join ' ') + $process=[Diagnostics.Process]::Start($start) + try{ + $stdout=$process.StandardOutput.ReadToEndAsync() + $stderr=$process.StandardError.ReadToEndAsync() + $process.WaitForExit() + $output=$stdout.GetAwaiter().GetResult() + $errorText=$stderr.GetAwaiter().GetResult() + if($process.ExitCode){throw ($FailureMessage+' '+$errorText).Trim()} + return $output + }finally{$process.Dispose()} +} +try { + $cli=Join-Path $PSScriptRoot 'pathman.exe' + if(!(Test-Path -LiteralPath $cli)){$cli=(Get-Command pathman.exe -ErrorAction Stop).Source} + $json=Invoke-PathMan @('switch',$Name,$Version,'--resolve') 'PathMan could not resolve the requested version.' + $target=$json|ConvertFrom-Json + $updates=[ordered]@{} + if($Scope -ne 'reg'){ + $old=[Environment]::GetEnvironmentVariable($target.Name,'Process') + $values=@{} + foreach($entry in [Environment]::GetEnvironmentVariables().GetEnumerator()){$values[$entry.Key]=$entry.Value} + $values[$target.Name]=[string]$target.Value + $expand={param([string]$text,[string[]]$seen) + [regex]::Replace($text,'%([^%]+)%',{param($match) + $key=$match.Groups[1].Value + if($seen -contains $key -or $seen.Count -ge 32){throw 'Circular or excessively nested environment reference.'} + if(!$values.ContainsKey($key)){throw "Undefined environment variable: $key"} + & $expand ([string]$values[$key]) @($seen+$key) + }) + } + $value=& $expand ([string]$target.Value) @($target.Name) + $updates[$target.Name]=$value + $oldRoot=if($old){$old.TrimEnd('\','/')}else{''} + $paths=foreach($part in ([string][Environment]::GetEnvironmentVariable('Path','Process')).Split(';')){ + if($oldRoot -and ($part.Equals($oldRoot,[StringComparison]::OrdinalIgnoreCase) -or $part.StartsWith($oldRoot+'\',[StringComparison]::OrdinalIgnoreCase) -or $part.StartsWith($oldRoot+'/',[StringComparison]::OrdinalIgnoreCase))){$value.TrimEnd('\','/')+$part.Substring($oldRoot.Length)} + elseif($part -match ('(?i)%'+[regex]::Escape($target.Name)+'%')){& $expand $part @()} + else{$part} + } + $updates['PATH']=$paths -join ';' + } + foreach($key in $updates.Keys){ + if(([string]$updates[$key]).Length -gt 32767){throw "Expanded value is too long: $key"} + if($OutputFormat -eq 'Bash' -and $key -cnotmatch '^[A-Za-z_][A-Za-z0-9_]*$'){throw "Not a Bash variable name: $key"} + if($OutputFormat -eq 'Cmd' -and (($key+'='+$updates[$key]).Length -gt 8000 -or ($key+'='+$updates[$key]) -match "[`r`n]")){throw 'CMD cannot represent this value without truncation.'} + } + if($OutputFormat -eq 'Cmd' -and !$OutputFile){throw 'An output file is required for CMD.'} + if($Scope -ne 'shell'){ + $null=Invoke-PathMan @('switch',$Name,$Version) 'PathMan could not write the environment variable.' + } + if($OutputFormat -eq 'Cmd'){ + $lines=@(foreach($key in $updates.Keys){$key+'='+$updates[$key]}) + $originalCodePage=[Console]::OutputEncoding.CodePage + $fileCodePage=$originalCodePage + $encoding=if($fileCodePage -eq 65001){[Text.UTF8Encoding]::new($false,$true)}else{[Text.Encoding]::GetEncoding($fileCodePage,[Text.EncoderFallback]::ExceptionFallback,[Text.DecoderFallback]::ExceptionFallback)} + $useUtf8=$false + try{foreach($line in $lines){if($encoding.GetString($encoding.GetBytes($line)) -cne $line){$useUtf8=$true;break}}}catch [Text.EncoderFallbackException]{$useUtf8=$true} + if($useUtf8){ + $fileCodePage=65001 + $encoding=[Text.UTF8Encoding]::new($false) + } + [IO.File]::WriteAllLines($OutputFile,$lines,$encoding) + [IO.File]::WriteAllText($OutputFile+'.cp',"$originalCodePage $fileCodePage",[Text.Encoding]::ASCII) + }elseif($OutputFormat -eq 'Bash'){ + $writer=[IO.StreamWriter]::new([Console]::OpenStandardOutput(),[Text.UTF8Encoding]::new($false),1024,$true) + try{foreach($key in $updates.Keys){ + $quoted="'"+([string]$updates[$key]).Replace("'","'\''")+"'" + if($key -eq 'PATH'){$writer.WriteLine('export PATH="$(cygpath -u -p -- '+$quoted+')"')}else{$writer.WriteLine('export '+$key+'='+$quoted)} + }}finally{$writer.Dispose()} + }else{ + foreach($key in $updates.Keys){[Environment]::SetEnvironmentVariable($key,$updates[$key],'Process')} + } +}catch{ + if($OutputFormat -eq 'PowerShell'){throw} + [Console]::Error.WriteLine($_.Exception.Message) + exit 1 +} diff --git a/scripts/shell/switch-pathman b/scripts/shell/switch-pathman new file mode 100644 index 0000000..2b323f9 --- /dev/null +++ b/scripts/shell/switch-pathman @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +if [[ ${BASH_SOURCE[0]} == "$0" ]]; then + printf '%s\n' 'Source this script: . switch-pathman name version [--scope reg|shell|all]' >&2 + exit 1 +fi +_pathman_switch() { + local name='' version='' scope='' option code script + while (($#)); do + case $1 in + --name|-n|--version|-v|--scope|-s) + option=$1; shift + (($#)) || { printf '%s\n' 'Missing option value.' >&2; return 1; } + case $option in + --name|-n) [[ -z $name ]] || return 1; name=$1;; + --version|-v) [[ -z $version ]] || return 1; version=$1;; + --scope|-s) [[ -z $scope && -n $1 ]] || return 1; scope=$1;; + esac;; + -*) printf 'Unknown option: %s\n' "$1" >&2; return 1;; + *) if [[ -z $name ]]; then name=$1; elif [[ -z $version ]]; then version=$1; else return 1; fi;; + esac + shift + done + scope=${scope:-shell} + [[ -n $name && -n $version && $scope =~ ^(reg|shell|all)$ ]] || { printf '%s\n' 'Name, version and a valid scope (reg, shell or all) are required.' >&2; return 1; } + script=$(cygpath -w -- "$(dirname -- "${BASH_SOURCE[0]}")/Switch-PathMan.ps1") || return + code=$(powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File "$script" -Name "$name" -Version "$version" -Scope "$scope" -OutputFormat Bash) || return + eval "$code" +} +if _pathman_switch "$@"; then + unset -f _pathman_switch + return 0 +else + unset -f _pathman_switch + return 1 +fi diff --git a/scripts/shell/switch-pathman.cmd b/scripts/shell/switch-pathman.cmd new file mode 100644 index 0000000..fab61f2 --- /dev/null +++ b/scripts/shell/switch-pathman.cmd @@ -0,0 +1,67 @@ +@echo off +if "!"=="" (echo PathMan: disable delayed expansion before switching. 1>&2 & exit /b 1) +set "_PATHMAN_DIR=%~dp0" +set "_PATHMAN_TMP=" +set "_PATHMAN_NAME=" +set "_PATHMAN_VERSION=" +set "_PATHMAN_SCOPE=" +set "_PATHMAN_CP=" +set "_PATHMAN_TARGET_CP=" +:parse +if "%~1"=="" goto run +if /i "%~1"=="/n" goto name +if /i "%~1"=="/v" goto version +if /i "%~1"=="/s" goto scope +if not defined _PATHMAN_NAME (set "_PATHMAN_NAME=%~1") else if not defined _PATHMAN_VERSION (set "_PATHMAN_VERSION=%~1") else goto usage +shift +goto parse +:name +if defined _PATHMAN_NAME goto usage +shift +set "_PATHMAN_NAME=%~1" +goto next +:version +if defined _PATHMAN_VERSION goto usage +shift +set "_PATHMAN_VERSION=%~1" +goto next +:scope +if defined _PATHMAN_SCOPE goto usage +shift +set "_PATHMAN_SCOPE=%~1" +:next +if "%~1"=="" goto usage +shift +goto parse +:run +if not defined _PATHMAN_NAME goto usage +if not defined _PATHMAN_VERSION goto usage +if not defined _PATHMAN_SCOPE set "_PATHMAN_SCOPE=shell" +set "_PATHMAN_TMP=%TEMP%\PathMan-%RANDOM%-%RANDOM%.env" +powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File "%_PATHMAN_DIR%Switch-PathMan.ps1" -Name "%_PATHMAN_NAME%" -Version "%_PATHMAN_VERSION%" -Scope "%_PATHMAN_SCOPE%" -OutputFormat Cmd -OutputFile "%_PATHMAN_TMP%" >nul +if not "%errorlevel%"=="0" goto failed +for /f "usebackq tokens=1,2" %%C in ("%_PATHMAN_TMP%.cp") do ( + set "_PATHMAN_CP=%%C" + set "_PATHMAN_TARGET_CP=%%D" +) +if not "%_PATHMAN_CP%"=="%_PATHMAN_TARGET_CP%" chcp %_PATHMAN_TARGET_CP% >nul +for /f "usebackq delims=" %%E in ("%_PATHMAN_TMP%") do set "%%E" +if not "%_PATHMAN_CP%"=="%_PATHMAN_TARGET_CP%" chcp %_PATHMAN_CP% >nul +del /q "%_PATHMAN_TMP%" "%_PATHMAN_TMP%.cp" >nul 2>&1 +call :cleanup +exit /b 0 +:usage +echo Usage: switch-pathman [/n] name [/v] version [/s reg^|shell^|all] 1>&2 +:failed +if defined _PATHMAN_TMP del /q "%_PATHMAN_TMP%" "%_PATHMAN_TMP%.cp" >nul 2>&1 +call :cleanup +exit /b 1 +:cleanup +set "_PATHMAN_NAME=" +set "_PATHMAN_VERSION=" +set "_PATHMAN_SCOPE=" +set "_PATHMAN_TMP=" +set "_PATHMAN_CP=" +set "_PATHMAN_TARGET_CP=" +set "_PATHMAN_DIR=" +exit /b diff --git a/scripts/test.ps1 b/scripts/test.ps1 index 4486314..0197004 100644 --- a/scripts/test.ps1 +++ b/scripts/test.ps1 @@ -67,7 +67,7 @@ function Assert-Rejected([scriptblock]$Action) { try { New-Item -ItemType Directory -Path $installation -Force | Out-Null Copy-Item -Path (Join-Path $PublishDirectory '*') -Destination $installation -Recurse - Assert (@(Get-ChildItem -LiteralPath (Join-Path $installation 'bin')).Count -eq 1) 'bin must contain only the CLI EXE.' + Assert (@(Compare-Object @('pathman.exe','Switch-PathMan.ps1','switch-pathman.cmd','switch-pathman') @(Get-ChildItem -LiteralPath (Join-Path $installation 'bin')|ForEach-Object Name)).Count -eq 0) 'bin contains the CLI and three shell scripts.' Assert (@(Get-ChildItem -LiteralPath $installation -Recurse -Filter '*.exe').Count -eq 4) 'Exactly four production EXEs are required.' $help=Invoke-Cli @('--help') $commands=@([regex]::Matches($help.Out,'(?m)^\s+pathman (\w+)') | ForEach-Object {$_.Groups[1].Value}) diff --git a/src/Pathman.Cli/Program.cs b/src/Pathman.Cli/Program.cs index 6a37662..b88dca3 100644 --- a/src/Pathman.Cli/Program.cs +++ b/src/Pathman.Cli/Program.cs @@ -19,6 +19,9 @@ case ["delete", var project,var version]: VersionCommands.Delete(layout,project,version); return 0; + case ["switch", var project,var version,"--resolve"]: + VersionCommands.Resolve(layout,project,version); + return 0; case ["switch", var project,var version]: VersionCommands.Switch(layout,project,version); return 0; diff --git a/src/Pathman.Cli/VersionCommands.cs b/src/Pathman.Cli/VersionCommands.cs index 1076426..1cf4d0c 100644 --- a/src/Pathman.Cli/VersionCommands.cs +++ b/src/Pathman.Cli/VersionCommands.cs @@ -65,4 +65,9 @@ public static void Switch(PathmanLayout layout,string project,string version) WindowsEnvironmentVariableEditor.Apply(mutation,store); Console.WriteLine(L.Format("已切换 {0} → {1}:{2}={3}",project,version,mutation.Name,Display(mutation.Value!))); } + public static void Resolve(PathmanLayout layout,string project,string version) + { + var mutation=VersionCatalog.PrepareSwitch(EnabledState(layout),project,version,EnvironmentMonitor.ReadAll()); + Console.WriteLine(System.Text.Json.JsonSerializer.Serialize(new {Name=mutation.Name,Value=mutation.Value})); + } } diff --git a/tests/cli-versions.ps1 b/tests/cli-versions.ps1 index 7168373..a83e4b4 100644 --- a/tests/cli-versions.ps1 +++ b/tests/cli-versions.ps1 @@ -32,6 +32,8 @@ try{ Assert ($true) 'Legacy commands, data-root overrides and the old CLI elevation worker are rejected' $null=RunCli @('add','cli-user','25','D:/SDK/User25','--variable','PATHMAN_CLI_USER','--type','User');$null=RunCli @('add','cli-user','lts','D:/SDK/User25') Assert ((Raw 'PATHMAN_CLI_USER') -eq 'user-before') 'Registering versions only saves metadata' + $resolved=(RunCli @('switch','cli-user','25','--resolve'))|ConvertFrom-Json + Assert ($resolved.Name -eq 'PATHMAN_CLI_USER' -and $resolved.Value -eq 'D:/SDK/User25' -and (Raw 'PATHMAN_CLI_USER') -eq 'user-before') 'Shell resolution validates the version without writing the registry' $null=RunCli @('switch','cli-user','25');$listing=RunCli @('list','cli-user') Assert ((Raw 'PATHMAN_CLI_USER') -eq 'D:/SDK/User25' -and $listing.Contains('(25, lts)') -and $listing.Contains('Type: User')) 'User switching and shared current-version labels still work' $null=RunCli @('delete','cli-user','25');$null=RunCli @('delete','cli-user') diff --git a/tests/installer-acceptance.ps1 b/tests/installer-acceptance.ps1 index 754900e..9146b69 100644 --- a/tests/installer-acceptance.ps1 +++ b/tests/installer-acceptance.ps1 @@ -56,6 +56,7 @@ try { Assert ((MachineType (Join-Path $directory 'PathMan.exe')) -eq $expectedMachine) "$label GUI has the requested PE architecture" Assert ((MachineType (Join-Path $directory 'bin/pathman.exe')) -eq $expectedMachine) "$label CLI has the requested PE architecture" Run (Join-Path $directory 'bin/pathman.exe') '--help' + foreach($script in 'Switch-PathMan.ps1','switch-pathman.cmd','switch-pathman'){Assert (Test-Path (Join-Path $directory "bin/$script")) "$label installs $script"} Run (Join-Path $directory 'bin/pathman.exe') 'list' 1 $gui=Start-Process (Join-Path $directory 'PathMan.exe') -PassThru try { @@ -92,7 +93,7 @@ try { Assert ((Get-FileHash (Join-Path $directory 'PathMan.exe')).Hash -eq $hash) "$label downgrade is rejected before changing files" Run $uninstaller "/S $scope _?=$directory\internal" Assert (!(Registered $machine)) "$label uninstall removes registration" - foreach($relative in 'PathMan.exe','bin/pathman.exe','internal/PathMan.Service.exe','internal/PathMan.Shim.exe','release.json','THIRD-PARTY-NOTICES.txt','licenses/dotnet-THIRD-PARTY-NOTICES.txt') {Assert (!(Test-Path (Join-Path $directory $relative))) "$label uninstall removes $relative"} + foreach($relative in 'PathMan.exe','bin/pathman.exe','bin/Switch-PathMan.ps1','bin/switch-pathman.cmd','bin/switch-pathman','internal/PathMan.Service.exe','internal/PathMan.Shim.exe','release.json','THIRD-PARTY-NOTICES.txt','licenses/dotnet-THIRD-PARTY-NOTICES.txt') {Assert (!(Test-Path (Join-Path $directory $relative))) "$label uninstall removes $relative"} Assert ((PathValue $machine) -ceq $originalPath) "$label uninstall restores the original PATH" Assert ((Get-FileHash $data).Hash -eq $configHash) "$label uninstall retains user configuration" }finally { diff --git a/tests/shell-console-probe.cs b/tests/shell-console-probe.cs new file mode 100644 index 0000000..493aa1f --- /dev/null +++ b/tests/shell-console-probe.cs @@ -0,0 +1,72 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Runtime.InteropServices; +using System.Text; + +class ConsoleProbe +{ + [StructLayout(LayoutKind.Sequential)] + struct Coord { public short X, Y; } + + [DllImport("kernel32.dll")] static extern uint GetConsoleCP(); + [DllImport("kernel32.dll")] static extern uint GetConsoleOutputCP(); + [DllImport("kernel32.dll")] static extern bool SetConsoleCP(uint codePage); + [DllImport("kernel32.dll")] static extern bool SetConsoleOutputCP(uint codePage); + [DllImport("kernel32.dll")] static extern IntPtr GetStdHandle(int handle); + [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] + static extern bool ReadConsoleOutputCharacter(IntPtr handle, StringBuilder text, uint length, Coord position, out uint read); + + static string ReadScreen() + { + var text = new StringBuilder(8000); + uint read; + if (!ReadConsoleOutputCharacter(GetStdHandle(-11), text, 8000, new Coord(), out read)) + throw new IOException("The console screen buffer could not be read."); + return text.ToString(); + } + + static string CodePages() { return GetConsoleCP() + "/" + GetConsoleOutputCP(); } + + static int Main(string[] args) + { + uint inputCodePage = uint.Parse(args[2]); + uint outputCodePage = uint.Parse(args[3]); + if (!SetConsoleCP(inputCodePage) || !SetConsoleOutputCP(outputCodePage)) + throw new IOException("The probe requires its own console."); + Console.Clear(); + const string marker = "PATHMAN-CONSOLE-HISTORY-MUST-SURVIVE"; + Console.WriteLine(marker); + bool before = ReadScreen().Contains(marker); + var changes = new List(); + changes.Add(CodePages()); + var start = new ProcessStartInfo(Environment.GetEnvironmentVariable("ComSpec")); + start.UseShellExecute = false; + start.Arguments = "/d /v:off /c \"\"" + args[0] + "\"\""; + var process = Process.Start(start); + try + { + var timer = Stopwatch.StartNew(); + while (!process.WaitForExit(1)) + { + string current = CodePages(); + if (current != changes[changes.Count - 1]) changes.Add(current); + if (timer.ElapsedMilliseconds > 15000) + { + process.Kill(); + throw new IOException("The shell switch timed out."); + } + } + string final = CodePages(); + if (final != changes[changes.Count - 1]) changes.Add(final); + bool history = before && ReadScreen().Contains(marker); + string json = "{\"ExitCode\":" + process.ExitCode + + ",\"HistoryPreserved\":" + history.ToString().ToLowerInvariant() + + ",\"CodePages\":[\"" + string.Join("\",\"", changes.ToArray()) + "\"]}"; + File.WriteAllText(args[1], json, new UTF8Encoding(false)); + return process.ExitCode; + } + finally { process.Dispose(); } + } +} diff --git a/tests/shell-switch.ps1 b/tests/shell-switch.ps1 new file mode 100644 index 0000000..00b9233 --- /dev/null +++ b/tests/shell-switch.ps1 @@ -0,0 +1,95 @@ +$ErrorActionPreference='Stop' +$root=Split-Path -Parent $PSScriptRoot +$csc=Join-Path $env:WINDIR 'Microsoft.NET/Framework64/v4.0.30319/csc.exe' +if(!(Test-Path -LiteralPath $csc)){throw "Windows .NET Framework C# compiler is required: $csc"} +$git=Get-Command git.exe -ErrorAction Stop +$bash=Join-Path (Split-Path (Split-Path $git.Source)) 'bin/bash.exe' +if(!(Test-Path -LiteralPath $bash)){throw "Git Bash is required for shell integration tests: $bash"} +$fixture=Join-Path $root ('artifacts/shell-tests/space '+[guid]::NewGuid().ToString('N')) +New-Item -ItemType Directory -Force -Path $fixture|Out-Null +Copy-Item (Join-Path $root 'scripts/shell/*') $fixture +$source=@' +using System;using System.IO;using System.Text; +class Fixture {static int Main(string[] args){try{Console.OutputEncoding=new UTF8Encoding(false);}catch(IOException){Console.SetOut(new StreamWriter(Console.OpenStandardOutput(),new UTF8Encoding(false)){AutoFlush=true});}if(Environment.GetEnvironmentVariable("PATHMAN_TEST_DELAY")=="1")System.Threading.Thread.Sleep(200);if(args.Length==4&&args[3]=="--resolve"){Console.WriteLine(Environment.GetEnvironmentVariable("PATHMAN_TEST_JSON"));return 0;}if(Environment.GetEnvironmentVariable("PATHMAN_TEST_FAIL")=="1")return 1;File.AppendAllText(Environment.GetEnvironmentVariable("PATHMAN_TEST_RECORD"),"reg\n");return 0;}} +'@ +[IO.File]::WriteAllText((Join-Path $fixture 'fixture.cs'),$source) +& $csc /nologo "/out:$fixture\pathman.exe" (Join-Path $fixture 'fixture.cs') +if($LASTEXITCODE){throw 'Fixture compilation failed'} +& $csc /nologo "/out:$fixture\console-probe.exe" (Join-Path $PSScriptRoot 'shell-console-probe.cs') +if($LASTEXITCODE){throw 'Console probe compilation failed'} +$saved=@{} +foreach($name in 'PATH','PATHMAN_TEST_HOME','PATHMAN_TEST_JSON','PATHMAN_TEST_RECORD','PATHMAN_TEST_FAIL','PATHMAN_TEST_DELAY'){$saved[$name]=[Environment]::GetEnvironmentVariable($name)} +function Assert($value,[string]$message){if(!$value){throw $message}} +try{ + $env:PATHMAN_TEST_RECORD=Join-Path $fixture 'writes.txt' + $value='D:\工具 & !literal% ^ "quoted" ''apostrophe'' $(printf INJECTED)' + $env:PATHMAN_TEST_JSON=@{Name='PATHMAN_TEST_HOME';Value=$value}|ConvertTo-Json -Compress + foreach($invokeSwitch in @( + {& (Join-Path $fixture 'Switch-PathMan.ps1') java 25}, + {& (Join-Path $fixture 'Switch-PathMan.ps1') -Name java -Version 25}, + {& (Join-Path $fixture 'Switch-PathMan.ps1') java 25 -Scope shell} + )){ + $env:PATHMAN_TEST_HOME='C:\old';$env:PATH='C:\old\bin;'+$saved.PATH + & $invokeSwitch + Assert ($env:PATHMAN_TEST_HOME -ceq $value -and $env:PATH.StartsWith($value+'\bin;')) 'PowerShell default and explicit shell scope update the current process and PATH' + Assert (!(Test-Path $env:PATHMAN_TEST_RECORD)) 'PowerShell default and explicit shell scope never persist the variable' + } + $env:PATHMAN_TEST_HOME='C:\old';$env:PATH='C:\old\bin;'+$saved.PATH + & (Join-Path $fixture 'Switch-PathMan.ps1') -Name java -Version 25 -Scope reg + Assert ((Get-Content $env:PATHMAN_TEST_RECORD).Count -eq 1 -and $env:PATHMAN_TEST_HOME -eq 'C:\old') 'Registry scope delegates exactly once and leaves the caller unchanged' + $env:PATHMAN_TEST_HOME='C:\old';$env:PATH='C:\old\bin;'+$saved.PATH + $env:PATHMAN_TEST_FAIL='1' + $failed=$false;try{& (Join-Path $fixture 'Switch-PathMan.ps1') java 25 -Scope all}catch{$failed=$true} + Assert ($failed -and $env:PATHMAN_TEST_HOME -eq 'C:\old') 'Failed persistent writes leave the current shell unchanged' + $env:PATHMAN_TEST_FAIL='' + & (Join-Path $fixture 'Switch-PathMan.ps1') java 25 -Scope all + Assert ($env:PATHMAN_TEST_HOME -ceq $value -and (Get-Content $env:PATHMAN_TEST_RECORD).Count -eq 2) 'All scope changes both targets' + $env:PATHMAN_TEST_OUTPUT=Join-Path $fixture 'cmd.txt' + foreach($cmdArguments in 'java 25','/n java /v 25','/n java /v 25 /s shell'){ + $env:PATHMAN_TEST_HOME='C:\old';$env:PATH='C:\old\bin;'+$saved.PATH + $cmd="@echo off`r`ncall `"$fixture\switch-pathman.cmd`" $cmdArguments`r`nif errorlevel 1 exit /b 1`r`npowershell.exe -NoProfile -Command `"[IO.File]::WriteAllText(`$env:PATHMAN_TEST_OUTPUT,(`$env:PATHMAN_TEST_HOME+[char]10+`$env:PATH))`"`r`n" + [IO.File]::WriteAllText((Join-Path $fixture 'run.cmd'),$cmd,[Text.Encoding]::ASCII) + & $env:ComSpec /d /v:off /c (Join-Path $fixture 'run.cmd') + $observed=[IO.File]::ReadAllText($env:PATHMAN_TEST_OUTPUT).Split("`n",2) + Assert ($LASTEXITCODE -eq 0 -and $observed[0] -ceq $value -and $observed[1].StartsWith($value+'\bin;')) 'CMD default and explicit shell scope update the caller and PATH with literal special characters' + Assert ((Get-Content $env:PATHMAN_TEST_RECORD).Count -eq 2) 'CMD default and explicit shell scope never persist the variable' + } + $env:PATHMAN_TEST_DELAY='1' + foreach($consoleCodePages in @(@(936,936),@(65001,65001),@(437,437),@(936,65001),@(65001,936))){ + $env:PATHMAN_TEST_HOME='C:\old';$env:PATH='C:\old\bin;'+$saved.PATH + $consoleCase=$consoleCodePages -join '-' + $consoleResult=Join-Path $fixture "console-result-$consoleCase.json" + $console=Start-Process -FilePath (Join-Path $fixture 'console-probe.exe') -ArgumentList ('"'+(Join-Path $fixture 'run.cmd')+'" "'+$consoleResult+'" '+($consoleCodePages -join ' ')) -WindowStyle Hidden -PassThru -Wait + try{Assert ($console.ExitCode -eq 0) 'CMD console probe succeeds'}finally{$console.Dispose()} + $observedConsole=Get-Content -LiteralPath $consoleResult -Raw|ConvertFrom-Json + $expectedCodePages=$consoleCodePages -join '/' + Assert ($observedConsole.HistoryPreserved -and $observedConsole.CodePages[-1] -eq $expectedCodePages) "CMD preserves screen history and returns the $expectedCodePages code pages" + if($consoleCodePages[1] -ne 437){Assert ($observedConsole.CodePages.Count -eq 1) "CMD never changes the shared $expectedCodePages code pages when they can represent the value"} + $observed=[IO.File]::ReadAllText($env:PATHMAN_TEST_OUTPUT).Split("`n",2) + Assert ($observed[0] -ceq $value -and $observed[1].StartsWith($value+'\bin;')) "CMD preserves Unicode and literal values with code pages $expectedCodePages" + } + $env:PATHMAN_TEST_DELAY='' + $env:PATHMAN_TEST_SCRIPT=Join-Path $fixture 'switch-pathman' + $env:PATHMAN_TEST_OUTPUT=Join-Path $fixture 'bash.txt' + foreach($bashArguments in 'java 25','--name java --version 25','--name java --version 25 --scope shell'){ + $env:PATHMAN_TEST_HOME='C:\old';$env:PATH='C:\old\bin;'+$saved.PATH + $bashCommand='. "$(cygpath -u "$PATHMAN_TEST_SCRIPT")" '+$bashArguments+' || exit 1; expected=$(cygpath -u -- "$PATHMAN_TEST_HOME")/bin; [[ ":$PATH:" == *":$expected:"* && ":$PATH:" != *":/c/old/bin:"* ]] || exit 1; printf "%s" "$PATHMAN_TEST_HOME" > "$(cygpath -u "$PATHMAN_TEST_OUTPUT")"' + & $bash -c $bashCommand + Assert ($LASTEXITCODE -eq 0 -and [IO.File]::ReadAllText($env:PATHMAN_TEST_OUTPUT) -ceq $value) 'Sourced Git Bash default and explicit shell scope update the caller and PATH with literal special characters' + Assert ((Get-Content $env:PATHMAN_TEST_RECORD).Count -eq 2) 'Git Bash default and explicit shell scope never persist the variable' + } + foreach($scope in 'reg','all'){ + $env:PATHMAN_TEST_HOME='C:\old';$env:PATHMAN_TEST_SCOPE=$scope + $command="@echo off`r`ncall `"$fixture\switch-pathman.cmd`" java 25 /s $scope`r`nif errorlevel 1 exit /b 1`r`npowershell.exe -NoProfile -Command `"[IO.File]::WriteAllText(`$env:PATHMAN_TEST_OUTPUT,`$env:PATHMAN_TEST_HOME)`"`r`n" + [IO.File]::WriteAllText((Join-Path $fixture 'run.cmd'),$command,[Text.Encoding]::ASCII) + & $env:ComSpec /d /v:off /c (Join-Path $fixture 'run.cmd') + $expected=if($scope -eq 'reg'){'C:\old'}else{$value} + Assert ($LASTEXITCODE -eq 0 -and [IO.File]::ReadAllText($env:PATHMAN_TEST_OUTPUT) -ceq $expected) "CMD positional arguments and $scope scope" + & $bash -c '. "$(cygpath -u "$PATHMAN_TEST_SCRIPT")" java 25 -s "$PATHMAN_TEST_SCOPE" || exit; printf "%s" "$PATHMAN_TEST_HOME" > "$(cygpath -u "$PATHMAN_TEST_OUTPUT")"' + Assert ($LASTEXITCODE -eq 0 -and [IO.File]::ReadAllText($env:PATHMAN_TEST_OUTPUT) -ceq $expected) "Bash positional arguments and $scope scope" + } + Write-Host 'PASS: PowerShell, CMD and sourced Git Bash default/explicit scopes, positional/named arguments, PATH updates, literal values and CMD console history/code-page preservation.' +}finally{ + foreach($name in $saved.Keys){[Environment]::SetEnvironmentVariable($name,$saved[$name])} + Remove-Item Env:PATHMAN_TEST_OUTPUT,Env:PATHMAN_TEST_SCRIPT,Env:PATHMAN_TEST_SCOPE -ErrorAction SilentlyContinue +}