Reputation: 40271
I'm trying to generate git status in my fish shell prompt. The problem I'm having is that getting git status is a little bit slow. So, I would like to keep the current git status in a global variable, and only update it when the user runs certain commands (e.g. "cd" and "git"). I'm trying to get the last command the user executed using the "history" command, but I'm getting mixed results. Here is my code:
function update_git_status --description 'Calculate new git current branch based on location and set __git_status'
set -g __git_status (python ~/.oh-my-fish/themes/oneself/gitstatus.py)
end
function fish_right_prompt
set -l git_color (set_color red)
set -l normal (set_color normal)
# Update git current branch when certain commands are run
switch $history[1]
case 'git *' 'cd *' 'cd'
update_git_status
end
# Git status
echo "$git_color$__git_status$normal"
end
The main problem with this code is that history doesn't always return the last command right away from some reason. If I run a command other the "cd" or "git" and then cd into a git dir, it takes another command execution to update the git_status to the right string.
Is there some other way to get the command executed just before the prompt needs to be generated?
[UPDATE]
Here's the terminal output to try and show the problem in action:
~> history --clear
Are you sure you want to clear history ? (y/n)
read> y
History cleared!
~> echo $history[1]
~> ls
documents etc bin downloads Desktop media notes
~> echo $history[1]
ls
~> cd ~/.oh-my-fish/
~/oh-my-fish> echo $history[1]
cd ~/.oh-my-fish/
~/oh-my-fish> master⚡
When I cd into a git dir (in this case .oh-my-fish), the branch name should appear right away. However, it's only after I execute another command that it finally appears. I think that "echo $history[1]" returns the right value on the command line, but not when run from within the prompt method.
By the way, here's a link to my github repo which holds all of this code: https://github.com/oneself/oh-my-fish
Upvotes: 1
Views: 2575
Reputation: 193
I found it's a known issue, not fixed yet.
https://github.com/fish-shell/fish-shell/issues/984
The actual problem is that adding item to history is done in a thread, which is executed after fish_prompt
Upvotes: 2
Reputation: 246807
You can get the previous command from history with echo $history[1]
You might want to check the __terlar_git_prompt
function in /usr/share/fish/functions
You can collapse your switch cases:
switch $__last_command
case 'git *' 'cd *' 'cd'
update_git_status
end
I suspect you're hitting a timing issue. Without looking into it, it's possible that the prompt is processed before the $history array is updated. However, consider using functions that come with fish:
$ function fish_prompt; printf "%s%s> " (prompt_pwd) (__terlar_git_prompt); end
~> cd src/glennj/skel
~/s/g/skel|master✓>
Upvotes: 0