Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
scripts/shell/switch-pathman text eol=lf
scripts/shell/switch-pathman.cmd text eol=crlf
4 changes: 4 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
22 changes: 21 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 分钟后助手退出。取消授权会保留编辑内容。
Expand Down Expand Up @@ -252,7 +273,6 @@ git push origin v1.0.0-beta.1
## 开发计划

- PATH 变量卡片视图。
- PowerShell 模块与 CMD 脚本,用于切换当前终端的临时环境变量版本。

## 许可证

Expand Down
3 changes: 3 additions & 0 deletions packaging/PathMan.nsi
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
1 change: 1 addition & 0 deletions scripts/build-matrix.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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'))) {
Expand Down
4 changes: 3 additions & 1 deletion scripts/package.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down
99 changes: 99 additions & 0 deletions scripts/shell/Switch-PathMan.ps1
Original file line number Diff line number Diff line change
@@ -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
}
35 changes: 35 additions & 0 deletions scripts/shell/switch-pathman
Original file line number Diff line number Diff line change
@@ -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
67 changes: 67 additions & 0 deletions scripts/shell/switch-pathman.cmd
Original file line number Diff line number Diff line change
@@ -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
2 changes: 1 addition & 1 deletion scripts/test.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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})
Expand Down
3 changes: 3 additions & 0 deletions src/Pathman.Cli/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
5 changes: 5 additions & 0 deletions src/Pathman.Cli/VersionCommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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}));
}
}
2 changes: 2 additions & 0 deletions tests/cli-versions.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down
3 changes: 2 additions & 1 deletion tests/installer-acceptance.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down
Loading