Skip to content

docs: 📝 Update wiki powershell-snippet #1542

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

Merged
merged 2 commits into from
Mar 6, 2025

Conversation

FallenDeity
Copy link
Contributor

Update powershell-snippet in wiki to play nice with zoxide, yazi etc

With reference to #1467 @spenserblack

Update powershell-snippet in wiki to play nice with zoxide, yazi etc
Copy link
Collaborator

@spenserblack spenserblack left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! Let me know what you think of this feedback.

@spenserblack
Copy link
Collaborator

BTW, I don't have zoxide installed, would you mind posting the output of zoxide init powershell? I'd just like to look into the hook and maybe figure out why z requires the output encoding workaround.

Set global encoding confing for zoxide and simplify Set-Location function
@FallenDeity
Copy link
Contributor Author

I ran a few variations of the experiment so basically if I do z into some git repo while the function gets triggered onefetch doesn't display anything in console unless, I explicitly pipe it to Write-Host but if I do this Set-Location -LiteralPath ".\VsCodeProjects\profile\" it works as expected without piping.

image

image

This leads me to believe this silencing behavior might have something to do with zoxide's command when changing directories.

 zoxide init powershell
# =============================================================================
#
# Utility functions for zoxide.
#

# Call zoxide binary, returning the output as UTF-8.
function global:__zoxide_bin {
    $encoding = [Console]::OutputEncoding
    try {
        [Console]::OutputEncoding = [System.Text.Utf8Encoding]::new()
        $result = zoxide @args
        return $result
    } finally {
        [Console]::OutputEncoding = $encoding
    }
}

# pwd based on zoxide's format.
function global:__zoxide_pwd {
    $cwd = Get-Location
    if ($cwd.Provider.Name -eq "FileSystem") {
        $cwd.ProviderPath
    }
}

# cd + custom logic based on the value of _ZO_ECHO.
function global:__zoxide_cd($dir, $literal) {
    $dir = if ($literal) {
        Set-Location -LiteralPath $dir -Passthru -ErrorAction Stop
    } else {
        if ($dir -eq '-' -and ($PSVersionTable.PSVersion -lt 6.1)) {
            Write-Error "cd - is not supported below PowerShell 6.1. Please upgrade your version of PowerShell."
        }
        elseif ($dir -eq '+' -and ($PSVersionTable.PSVersion -lt 6.2)) {
            Write-Error "cd + is not supported below PowerShell 6.2. Please upgrade your version of PowerShell."
        }
        else {
            Set-Location -Path $dir -Passthru -ErrorAction Stop
        }
    }
}

# =============================================================================
#
# Hook configuration for zoxide.
#

# Hook to add new entries to the database.
$global:__zoxide_oldpwd = __zoxide_pwd
function global:__zoxide_hook {
    $result = __zoxide_pwd
    if ($result -ne $global:__zoxide_oldpwd) {
        if ($null -ne $result) {
            zoxide add -- $result
        }
        $global:__zoxide_oldpwd = $result
    }
}

# Initialize hook.
$global:__zoxide_hooked = (Get-Variable __zoxide_hooked -ErrorAction SilentlyContinue -ValueOnly)
if ($global:__zoxide_hooked -ne 1) {
    $global:__zoxide_hooked = 1
    $global:__zoxide_prompt_old = $function:prompt

    function global:prompt {
        if ($null -ne $__zoxide_prompt_old) {
            & $__zoxide_prompt_old
        }
        $null = __zoxide_hook
    }
}

# =============================================================================
#
# When using zoxide with --no-cmd, alias these internal functions as desired.
#

# Jump to a directory using only keywords.
function global:__zoxide_z {
    if ($args.Length -eq 0) {
        __zoxide_cd ~ $true
    }
    elseif ($args.Length -eq 1 -and ($args[0] -eq '-' -or $args[0] -eq '+')) {
        __zoxide_cd $args[0] $false
    }
    elseif ($args.Length -eq 1 -and (Test-Path $args[0] -PathType Container)) {
        __zoxide_cd $args[0] $true
    }
    else {
        $result = __zoxide_pwd
        if ($null -ne $result) {
            $result = __zoxide_bin query --exclude $result -- @args
        }
        else {
            $result = __zoxide_bin query -- @args
        }
        if ($LASTEXITCODE -eq 0) {
            __zoxide_cd $result $true
        }
    }
}

# Jump to a directory using interactive search.
function global:__zoxide_zi {
    $result = __zoxide_bin query -i -- @args
    if ($LASTEXITCODE -eq 0) {
        __zoxide_cd $result $true
    }
}

# =============================================================================
#
# Commands for zoxide. Disable these using --no-cmd.
#

Set-Alias -Name z -Value __zoxide_z -Option AllScope -Scope Global -Force
Set-Alias -Name zi -Value __zoxide_zi -Option AllScope -Scope Global -Force

# =============================================================================
#
# To initialize zoxide, add this to your configuration (find it by running
# `echo $profile` in PowerShell):
#
# Invoke-Expression (& { (zoxide init powershell | Out-String) })

@FallenDeity
Copy link
Contributor Author

Edit: I played around with zoxide's script a bit and fixed both issues

  • Reason for no output was because they were reassigning any output from Set-Location to a variable $dir and not returning it.
function global:__zoxide_cd($dir, $literal) {
    $dir = if ($literal) {
        Set-Location -LiteralPath $dir -Passthru -ErrorAction Stop
    } else {
        if ($dir -eq '-' -and ($PSVersionTable.PSVersion -lt 6.1)) {
            Write-Error "cd - is not supported below PowerShell 6.1. Please upgrade your version of PowerShell."
        }
        elseif ($dir -eq '+' -and ($PSVersionTable.PSVersion -lt 6.2)) {
            Write-Error "cd + is not supported below PowerShell 6.2. Please upgrade your version of PowerShell."
        }
        else {
            Set-Location -Path $dir -Passthru -ErrorAction Stop
        }
    }
    #  This fixes it
    return $dir
}
  • Reason for garbled characters, they are changing the default console output encoding in the finally block back from utf-8
function global:__zoxide_bin {
    # default encoding utf-8
    $encoding = [System.Text.Encoding]::UTF8
    try {
        [Console]::OutputEncoding = [System.Text.Utf8Encoding]::new()
        $result = zoxide @args
        return $result
    } finally {
        [Console]::OutputEncoding = $encoding
    }
}

onefetch setup

$global:lastRepository = $null

function Check-DirectoryForNewRepository {
    $currentRepository = git rev-parse --show-toplevel 2>$null
    if ($currentRepository -and ($currentRepository -ne $global:lastRepository)) {
        onefetch
    }
    $global:lastRepository = $currentRepository
}

function Set-Location {
    Microsoft.PowerShell.Management\Set-Location @args  
    Check-DirectoryForNewRepository
}

image

I believe they silence the output because -PassThru they use returns a dictionary which they don't really wanna log, so maybe a sort of configurable option there would be nice

So to summarize the current stuff not printing is more of a zoxide issue 😔 and the this pr fixes the path not changing issue due to other required params not being propagated through the Set-Location, and adds a workaround to prevent unintentional silencing by other scripts

Copy link
Collaborator

@spenserblack spenserblack left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe they silence the output because -PassThru they use returns a dictionary which they don't really wanna log, so maybe a sort of configurable option there would be nice

Without looking more into it, I'm not really sure why zoxide is using -PassThru at all. If they don't want output, simply excluding -PassThru can achieve that. Discarding the output of -PassThru is like doing some-tool --verbose > /dev/null 😅

Maybe -PassThru behaves differently on older versions of PowerShell 🤷

@spenserblack spenserblack enabled auto-merge (squash) March 5, 2025 20:49
@spenserblack
Copy link
Collaborator

🤔 Also, as a workaround when onefetch is wrapped by a tool/function/alias that might consume output (like z), it might make sense to redirect onefetch's output to stderr. This is a somewhat common practice to separate text meant for humans from text meant for machines.

@FallenDeity
Copy link
Contributor Author

I don't think it would be a good idea to redirect onefetch's output to stderr in case of powershell

onefetch | Write-Error
onefetch | Write-Error : TSXTSXTSXTSXTSXTSXTSXTSXTSXTSXTSXTSXTSX   FallenDeity ~ git version 2.48.1.windows.1
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException

onefetch | Write-Error : TSXTSXTSXTSXTSXTSXTSXTSXTSXTSXTSXTSXTSX   ------------------------------------------
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException

wouldnt want this 😭, also afaik piping to stderr might mess with onefetch styles since a lot of terminals/or terminal config frameworks apply custom ansi styles to error text for theming

@spenserblack
Copy link
Collaborator

Alright, that makes sense, then I think your PR is good as it is 👍

@spenserblack spenserblack disabled auto-merge March 6, 2025 02:27
@spenserblack
Copy link
Collaborator

@o2sh This will need an admin to merge because the required CI jobs won't run with the ignored paths.

@o2sh o2sh merged commit f560ddc into o2sh:main Mar 6, 2025
1 check passed
tmeijn pushed a commit to tmeijn/dotfiles that referenced this pull request May 10, 2025
This MR contains the following updates:

| Package | Update | Change |
|---|---|---|
| [o2sh/onefetch](https://github.com/o2sh/onefetch) | minor | `2.23.1` -> `2.24.0` |

MR created with the help of [el-capitano/tools/renovate-bot](https://gitlab.com/el-capitano/tools/renovate-bot).

**Proposed changes to behavior should be submitted there as MRs.**

---

### Release Notes

<details>
<summary>o2sh/onefetch (o2sh/onefetch)</summary>

### [`v2.24.0`](https://github.com/o2sh/onefetch/blob/HEAD/CHANGELOG.md#2240-2025-04-12)

[Compare Source](o2sh/onefetch@2.23.1...2.24.0)

##### New Features

-   add language support for Lean by [@&#8203;foxyseta](https://github.com/foxyseta) in o2sh/onefetch#1509
-   add language support for Typst by [@&#8203;foxyseta](https://github.com/foxyseta) in o2sh/onefetch#1508
-   add language support for Razor by [@&#8203;SrS2225a](https://github.com/SrS2225a) in o2sh/onefetch#1521

##### Chores

-   more idiomatic way to fetch HEAD refs by [@&#8203;o2sh](https://github.com/o2sh) in o2sh/onefetch#1515
-   more idiomatic way to fetch repository remote URL by [@&#8203;o2sh](https://github.com/o2sh) in o2sh/onefetch#1516
-   update holyc language logo by [@&#8203;o2sh](https://github.com/o2sh) in o2sh/onefetch#1543
-   update wiki powershell-snippet by [@&#8203;FallenDeity](https://github.com/FallenDeity) in o2sh/onefetch#1542
-   add nix local setup [@&#8203;Sk7Str1p3](https://github.com/Sk7Str1p3) in o2sh/onefetch#1549

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever MR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this MR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this MR, check this box

---

This MR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC4xMS4yIiwidXBkYXRlZEluVmVyIjoiNDAuMTEuMiIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiUmVub3ZhdGUgQm90Il19-->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants