Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use existing cd alias in the script that fnm env --shell powershell --use-on-cd emits #1350

Open
ravindUwU opened this issue Dec 25, 2024 · 0 comments

Comments

@ravindUwU
Copy link

ravindUwU commented Dec 25, 2024

Problem

On PowerShell, fnm env currently emits the following 👇, which alises cd to Set-LocationWithFnm:

# environment variables set with $env:... = ...
function global:Set-FnmOnLoad { fnm use --silent-if-unchanged }
function global:Set-LocationWithFnm { param($path); if ($path -eq $null) {Set-Location} else {Set-Location $path}; Set-FnmOnLoad }
Set-Alias -Scope global cd_with_fnm Set-LocationWithFnm
Set-Alias -Option AllScope -Scope global cd Set-LocationWithFnm
Set-FnmOnLoad

Consequently, if cd is already aliased to a different command (e.g., as part of one's dotfiles, or a different command that similarly "patches" cd), fnm env | iex "drops" the current alias and resets it back to Set-Location.

For example,

  1. cd is aliased to print out the path being navigated to, as a contrived example:

    function global:customCd {
    	param ($path)
    	Write-Host "customCd: $path"
    	Set-Location $path
    }
    Set-Alias 'cd' 'customCd' -Option AllScope -Scope Global

    ...which has the following effect:

    PS ~> cd Projects
    customCd: Projects
    PS ~/Projects>
    
  2. FNM is loaded with fnm env --shell powershell --use-on-cd | Out-String | Invoke-Expression.

  3. cd now prints:

    PS ~> cd Projects/jsProject
    Using Node v22.12.0
    PS ~/Projects/jsProject>
    

    ...and global:customCd from step 1 is no longer invoked.

Proposed Solution

Thoughts on emitting a script like 👇? I've only included the cd-related bits; Set-FnmOnLoad and Set-LocationWithFnm are unchanged and omitted for brevity.

$global:cdBeforeFnm = (Get-Alias 'cd' -Scope Global -ErrorAction Ignore).ReferencedCommand
if ($null -eq $global:cdBeforeFnm) { $global:cdBeforeFnm = Get-Command Set-Location }

function global:cdWithFnm {
	param ($path)
	if ($null -eq $path) { & $global:cdBeforeFnm } else { & $global:cdBeforeFnm $path }
	global:Set-FnmOnLoad
}

Set-Alias 'cd' 'global:cdWithFnm' -Option AllScope -Scope Global

...which uses the command that cd references at the time FNM is loaded, instead of always using Set-Location, thereby also invoking global:customCd:

PS ~> cd Projects/jsProject
customCd: Projects/jsProject
Using Node v22.12.0
PS ~/Projects/jsProject>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant