Created
January 19, 2025 13:30
-
-
Save nicolasparada/89522927fbb070642991866b8c0834d4 to your computer and use it in GitHub Desktop.
Add this snippet at the end of your .zshrc to show your current username from gh CLI in the prompt (right side)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 1) Function to update the cached GitHub username: | |
function refresh_github_user() { | |
GITHUB_USER_CACHED="$( | |
gh auth status --active 2>/dev/null \ | |
| sed -nE 's/.* account ([^ ]+).*/\1/p' | |
)" | |
} | |
# 2) Function to display the cached GitHub user if in a Git repo: | |
function _gh_user_prompt() { | |
if git rev-parse --is-inside-work-tree &>/dev/null; then | |
if [[ -n "$GITHUB_USER_CACHED" ]]; then | |
echo "($GITHUB_USER_CACHED)" | |
fi | |
fi | |
} | |
# 3) Initialize the cache once at shell startup: | |
refresh_github_user | |
# 4) Right prompt (RPROMPT): show cached user in yellow: | |
RPROMPT='%{$fg[yellow]%}$(_gh_user_prompt)%{$reset_color%}' | |
# 5) Track last command in preexec(), and refresh in precmd() if it was "gh auth switch" or "gh auth login". | |
autoload -Uz add-zsh-hook | |
# This variable will hold the last command entered. | |
LAST_COMMAND="" | |
function _gh_preexec_capture() { | |
LAST_COMMAND="$1" | |
} | |
function _gh_precmd_refresh() { | |
# If the last command was "gh auth switch" or "gh auth login", refresh now. | |
if [[ "$LAST_COMMAND" == gh\ auth\ switch* || "$LAST_COMMAND" == gh\ auth\ login* ]]; then | |
refresh_github_user | |
fi | |
} | |
add-zsh-hook preexec _gh_preexec_capture | |
add-zsh-hook precmd _gh_precmd_refresh |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment