[ZSH] Extract shared startup modules

Keep the server entrypoint focused on server policy while moving update checks, Antidote loading, interactive defaults, and prompt sourcing into reusable modules.
This commit is contained in:
Fabian Ising
2026-07-27 10:57:11 +02:00
committed by Fabian Ising
parent 7ccb268cfb
commit 81deaa75a4
5 changed files with 142 additions and 197 deletions
+18 -192
View File
@@ -1,210 +1,51 @@
# Enable Powerlevel10k instant prompt. Should stay close to the top of ~/.zshrc.
# Initialization code that may require console input (password prompts, [y/n]
# confirmations, etc.) must go above this block; everything else may go below.
# Powerlevel10k instant prompt and machine-local layers must remain first.
[[ -f ~/.zsh/.powerline_config ]] && source ~/.zsh/.powerline_config
[[ -f ~/.zsh/.user_config ]] && source ~/.zsh/.user_config
[[ -f ~/.zsh/.virtual_env_config.zsh ]] && source ~/.zsh/.virtual_env_config.zsh
[[ -f ~/.zsh/.local_config ]] && source ~/.zsh/.local_config
# On shell start, bring ~/dotfiles up to date by fast-forwarding the CURRENT
# branch to its upstream only. Never rebase or stash in the background: if the
# branch diverged or local edits block it, warn and leave it for a manual pull.
# Per-branch, so `server` on each device fast-forwards to origin/server.
update_dotfiles() {
local repo="$HOME/dotfiles"
local cache_dir="${ZDOTDIR:-$HOME}/.cache/zsh"
local notice_file="$cache_dir/dotfiles-update-notice"
local notice_tmp="$notice_file.$$.tmp"
# Bound the network call so a stalled fetch can't wedge this backgrounded
# (&!) job into a days-long orphan holding unreaped children. `timeout` is
# absent on macOS, so only use it when present. Disable ssh multiplexing so
# no daemonized mux master can inherit and keep our fds open past git's exit.
local -a TO; (( $+commands[timeout] )) && TO=(timeout -k 5 15)
GIT_SSH_COMMAND='ssh -o BatchMode=yes -o ConnectTimeout=5 -o ControlMaster=no -o ControlPath=none' \
$TO git -C "$repo" fetch --quiet </dev/null 2>/dev/null || return
git -C "$repo" rev-parse --abbrev-ref '@{u}' >/dev/null 2>&1 || return # no upstream
git -C "$repo" merge-base --is-ancestor '@{u}' HEAD 2>/dev/null && return # already current
git -C "$repo" merge --ff-only --quiet '@{u}' 2>/dev/null && return
local notice="⚠ dotfiles: $(git -C "$repo" symbolic-ref --short HEAD) can't fast-forward to @{u} — run: git -C ~/dotfiles pull"
mkdir -p "$cache_dir" || return
print -r -- "$notice" >| "$notice_tmp" || return
mv -f "$notice_tmp" "$notice_file"
}
update_dotfiles &!
# On shell start, check the security tools repo for upstream updates and queue a
# one-line notice if the checkout is behind. A precmd hook prints it between
# commands, rather than letting this background job write across other startup
# output or a prompt that is already being edited. Notify only (never auto-pull).
# The check stays read-only so it works even in root-owned /opt/tools:
# - `safe.directory=*` sidesteps git's "dubious ownership" refusal on a repo
# owned by root, which would otherwise fail every git command.
# - `ls-remote` queries the remote without writing into .git (a normal user
# can't write a root-owned .git, so `fetch` would fail there).
# Uses the first candidate that is a git checkout; covers global and per-user layouts.
check_tools_repo() {
local repo branch remote mergeref remote_sha local_sha cmd notice
local cache_dir="${ZDOTDIR:-$HOME}/.cache/zsh"
local notice_file="$cache_dir/tools-update-notice"
local notice_tmp="$notice_file.$$.tmp"
# See update_dotfiles: bound the network probe (timeout, absent on macOS) and
# disable ssh multiplexing so a stalled ls-remote can't orphan this &! job.
local -a TO; (( $+commands[timeout] )) && TO=(timeout -k 5 10)
for repo in /opt/tools "$HOME/tools" "$HOME/tools/tools-repo"; do
local -a g=(git -c 'safe.directory=*' -C "$repo")
$g rev-parse --is-inside-work-tree >/dev/null 2>&1 || continue
branch=$($g symbolic-ref --short HEAD 2>/dev/null) || return
remote=$($g config "branch.$branch.remote" 2>/dev/null) || return # no upstream
mergeref=$($g config "branch.$branch.merge" 2>/dev/null) || return
remote_sha=$(GIT_SSH_COMMAND='ssh -o BatchMode=yes -o ConnectTimeout=5 -o ControlMaster=no -o ControlPath=none' \
$TO $g ls-remote "$remote" "$mergeref" </dev/null 2>/dev/null | awk '{print $1}')
local_sha=$($g rev-parse HEAD 2>/dev/null)
[[ -n "$remote_sha" && -n "$local_sha" ]] || return # remote unreachable
[[ "$remote_sha" == "$local_sha" ]] && return # already current
$g merge-base --is-ancestor "$remote_sha" HEAD 2>/dev/null && return # remote is an ancestor: ahead/equal (also true if we lack the object -> falls through to "behind")
[[ -w "$repo/.git" ]] && cmd="git -C $repo pull" || cmd="sudo git -C $repo pull"
notice="⬆ tools: updates available in $repo — run: $cmd"
mkdir -p "$cache_dir" || return
print -r -- "$notice" >| "$notice_tmp" || return
mv -f "$notice_tmp" "$notice_file"
return
done
}
check_tools_repo &!
show_update_notices() {
local cache_dir="${ZDOTDIR:-$HOME}/.cache/zsh"
local notice_file claimed_notice
for notice_file in "$cache_dir"/{dotfiles,tools}-update-notice; do
[[ -s "$notice_file" ]] || continue
claimed_notice="$notice_file.$$.show"
mv "$notice_file" "$claimed_notice" 2>/dev/null || continue
command cat "$claimed_notice"
command rm -f "$claimed_notice"
done
}
autoload -Uz add-zsh-hook
add-zsh-hook precmd show_update_notices
source "${ZDOTDIR:-$HOME}/.zsh/lib/updates.zsh"
export LC_OSC52=1
# Load Antidote
mkdir -p ${ZDOTDIR:-~}/.cache/zsh
static_file=${ZDOTDIR:-~}/.cache/zsh/.zsh_plugins.zsh
plugins_txt=${ZDOTDIR:-~}/.zsh/.zsh_plugins.txt
# clone antidote if necessary
if ! [[ -e ${ZDOTDIR:-~}/.antidote ]]; then
git clone https://github.com/mattmc3/antidote.git ${ZDOTDIR:-~}/.antidote
fi
plugins_txt=${ZDOTDIR:-$HOME}/.zsh/.zsh_plugins.txt
static_file=${ZDOTDIR:-$HOME}/.cache/zsh/.zsh_plugins.zsh
source "${ZDOTDIR:-$HOME}/.zsh/lib/antidote.zsh"
source "${ZDOTDIR:-$HOME}/.zsh/lib/interactive.zsh"
zstyle ':completion:*:ssh:*' hosts off
zstyle ':completion:*:scp:*' hosts off
# Run rehash for external commands
zstyle ":completion:*:commands" rehash 1
# source antidote and load plugins from `${ZDOTDIR:-~}/.zsh_plugins.txt`
source ${ZDOTDIR:-~}/.antidote/antidote.zsh
antidote load ${plugins_txt} ${static_file}
setopt interactivecomments
# History options
HISTSIZE=100000 # Set the amount of lines you want saved
SAVEHIST=100000 # This is required to actually save them, needs to match with HISTSIZE
setopt EXTENDED_HISTORY # Write the history file in the ":start:elapsed;command" format.
setopt INC_APPEND_HISTORY # Write to the history file immediately, not when the shell exits.
setopt SHARE_HISTORY # Share history between all sessions.
setopt HIST_EXPIRE_DUPS_FIRST # Expire duplicate entries first when trimming history.
setopt HIST_IGNORE_DUPS # Don\'t record an entry that was just recorded again.
setopt HIST_IGNORE_ALL_DUPS # Delete old recorded entry if new entry is a duplicate.
setopt HIST_FIND_NO_DUPS # Do not display a line previously found.
setopt HIST_IGNORE_SPACE # Don\'t record an entry starting with a space.
setopt HIST_SAVE_NO_DUPS # Don\'t write duplicate entries in the history file.
setopt HIST_REDUCE_BLANKS # Remove superfluous blanks before recording entry.
# Clear screen by ctrl+q
bindkey '^q' clear-screen
# Bind Ctrl-W to kill-region
bindkey "^w" kill-region
bindkey '^w' kill-region
bindkey -v
VI_MODE_SET_CURSOR=true
(( $+commands[nvim] )) && alias vim=nvim
alias sudo='sudo '
(( $+commands[nvim] )) && export EDITOR='nvim'
(( $+commands[nvim] )) && export VISUAL='nvim'
alias ls="ls --color=always"
alias cgrep="grep --color=always"
alias cdiff="git diff --color-words --no-index"
delzip() {
unzip -Z -1 "$@" | xargs -I{} rm -rf {}
}
# mitmproxy
export MITMPROXY_SSLKEYLOGFILE="~/.mitmproxy/sslkeylogfile.txt"
[[ -f ~/.zsh/.mac_config.zsh ]] && source ~/.zsh/.mac_config.zsh
if (( $+commands[go] )); then
export GOPATH="$(go env GOPATH 2>/dev/null)"
[[ -n "$GOPATH" ]] && path+=("$GOPATH/bin")
fi
# Use safecp/safemv from the tools-repo when available (after ~/.local/bin is on PATH)
# Use safe wrappers after ~/.local/bin has been added to PATH.
(( $+commands[safecp] )) && alias cp=safecp
(( $+commands[safemv] )) && alias mv=safemv
(( $+commands[safescp] )) && alias scp=safescp
if [[ -f ~/.ssh/sudo_key ]]; then
[[ -e /tmp/sudo-agent.sock ]] || ssh-agent -a /tmp/sudo-agent.sock &>/dev/null
SSH_AUTH_SOCK=/tmp/sudo-agent.sock ssh-add -l | grep -q `ssh-keygen -lf ~/.ssh/sudo_key | awk '{print $2}'` || SSH_AUTH_SOCK=/tmp/sudo-agent.sock ssh-add ~/.ssh/sudo_key
SSH_AUTH_SOCK=/tmp/sudo-agent.sock ssh-add -l |
grep -q "$(ssh-keygen -lf ~/.ssh/sudo_key | awk '{print $2}')" ||
SSH_AUTH_SOCK=/tmp/sudo-agent.sock ssh-add ~/.ssh/sudo_key
fi
# Sudo workaround for neovim
export SUDO_ASKPASS=$(command -v ssh-askpass)
# Workaround for async issues https://github.com/romkatv/powerlevel10k/issues/1554
unset ZSH_AUTOSUGGEST_USE_ASYNC
# Fixate language
export LANG="en_US.UTF-8"
export LC_CTYPE="en_US.UTF-8"
export TIME_STYLE="long-iso"
# Powerlevel 10k
# Remove padding on right side
ZLE_RPROMPT_INDENT=0
# To customize prompt, run `p10k configure` or edit ~/dotfiles/zsh/.p10k.zsh.
function load_p10k() {
if test -f ~/dotfiles/zsh/.p10k.mac.zsh; then
source ~/dotfiles/zsh/.p10k.mac.zsh
if [[ -f ~/dotfiles/zsh/.p10k.mac.zsh ]]; then
p10k_config=~/dotfiles/zsh/.p10k.mac.zsh
else
[[ ! -f ~/dotfiles/zsh/.p10k.zsh ]] || source ~/dotfiles/zsh/.p10k.zsh
p10k_config=~/dotfiles/zsh/.p10k.zsh
fi
}
load_p10k
source "${ZDOTDIR:-$HOME}/.zsh/lib/prompt.zsh"
alias screenshot_mode='powerlevel10k_plugin_unload; export PS1="$ "; python3 ~/.config/alacritty/screenshot_mode.py on'
alias screenshot_mode_off='prompt_powerlevel9k_setup; python3 ~/.config/alacritty/screenshot_mode.py off'
antidote update &>/dev/null &|
# This speeds up pasting w/ autosuggest
# https://github.com/zsh-users/zsh-autosuggestions/issues/238
pasteinit() {
OLD_SELF_INSERT=${${(s.:.)widgets[self-insert]}[2,3]}
zle -N self-insert url-quote-magic # I wonder if you'd need `.url-quote-magic`?
}
pastefinish() {
zle -N self-insert $OLD_SELF_INSERT
}
zstyle :bracketed-paste-magic paste-init pasteinit
zstyle :bracketed-paste-magic paste-finish pastefinish
# https://github.com/zsh-users/zsh-autosuggestions/issues/351
ZSH_AUTOSUGGEST_CLEAR_WIDGETS+=(bracketed-paste)
[[ -d "$HOME/.lmstudio/bin" ]] && path+=("$HOME/.lmstudio/bin")
[[ -d "$HOME/.runai/bin" ]] && path+=("$HOME/.runai/bin")
runai_bin="$HOME/.runai/bin/runai"
@@ -221,25 +62,10 @@ if [[ -x "$runai_bin" ]]; then
[[ -s "$runai_completion" ]] && source "$runai_completion"
fi
# Re-activate an inherited virtualenv — MUST be the last PATH-affecting line.
#
# When VIRTUAL_ENV is present in the environment (a tmux pane split carries it
# in via `-e VIRTUAL_ENV=...`, see .tmux.conf) we source the venv's activate
# script here rather than in .virtual_env_config.zsh. activate snapshots the
# current PATH into _OLD_VIRTUAL_PATH and restores it on `deactivate`; if we
# activated earlier (before .mac_config.zsh, Go, Run:AI, and LM Studio mutate
# PATH) that snapshot would be incomplete and `deactivate` would strip
# ~/.local/bin & friends — dropping claude and co. off PATH. Keeping this last
# guarantees the snapshot is the fully-built PATH.
#
# ANY new PATH mutation must go ABOVE this block.
#
# A new tmux window clears the var to empty (`bind c ... -e VIRTUAL_ENV=`) to
# force the base environment; drop that empty value so nothing sees a bogus venv.
# Keep this last: activate must snapshot the fully built PATH for deactivate.
typeset -U path PATH
[ -z "${VIRTUAL_ENV:-}" ] && unset VIRTUAL_ENV
if [ -n "$VIRTUAL_ENV" ] && [ -f "$VIRTUAL_ENV/bin/activate" ]; then
# Guard against double-activation on a manual `source ~/.zshrc`.
[[ -z "${VIRTUAL_ENV:-}" ]] && unset VIRTUAL_ENV
if [[ -n "$VIRTUAL_ENV" && -f "$VIRTUAL_ENV/bin/activate" ]]; then
if [[ ":$PATH:" != *":$VIRTUAL_ENV/bin:"* ]]; then
source "$VIRTUAL_ENV/bin/activate"
fi
+12
View File
@@ -0,0 +1,12 @@
# Callers set plugins_txt and static_file before sourcing this module.
mkdir -p "${static_file:h}"
if [[ ! -e ${ZDOTDIR:-$HOME}/.antidote ]]; then
git clone https://github.com/mattmc3/antidote.git "${ZDOTDIR:-$HOME}/.antidote"
fi
zstyle ':completion:*:ssh:*' hosts off
zstyle ':completion:*:scp:*' hosts off
zstyle ':completion:*:commands' rehash 1
source "${ZDOTDIR:-$HOME}/.antidote/antidote.zsh"
antidote load "$plugins_txt" "$static_file"
+43
View File
@@ -0,0 +1,43 @@
setopt interactivecomments
HISTSIZE=100000
SAVEHIST=100000
setopt EXTENDED_HISTORY
setopt INC_APPEND_HISTORY
setopt SHARE_HISTORY
setopt HIST_EXPIRE_DUPS_FIRST
setopt HIST_IGNORE_DUPS
setopt HIST_IGNORE_ALL_DUPS
setopt HIST_FIND_NO_DUPS
setopt HIST_IGNORE_SPACE
setopt HIST_SAVE_NO_DUPS
setopt HIST_REDUCE_BLANKS
bindkey '^q' clear-screen
(( $+commands[nvim] )) && alias vim=nvim
(( $+commands[nvim] )) && export EDITOR=nvim VISUAL=nvim
alias sudo='sudo '
alias ls='ls --color=always'
alias cgrep='grep --color=always'
alias cdiff='git diff --color-words --no-index'
delzip() {
unzip -Z -1 "$@" | xargs -I{} rm -rf {}
}
export MITMPROXY_SSLKEYLOGFILE='~/.mitmproxy/sslkeylogfile.txt'
unset ZSH_AUTOSUGGEST_USE_ASYNC
export LANG='en_US.UTF-8'
export LC_CTYPE='en_US.UTF-8'
export TIME_STYLE='long-iso'
pasteinit() {
OLD_SELF_INSERT=${${(s.:.)widgets[self-insert]}[2,3]}
zle -N self-insert url-quote-magic
}
pastefinish() {
zle -N self-insert "$OLD_SELF_INSERT"
}
zstyle :bracketed-paste-magic paste-init pasteinit
zstyle :bracketed-paste-magic paste-finish pastefinish
ZSH_AUTOSUGGEST_CLEAR_WIDGETS+=(bracketed-paste)
+3
View File
@@ -0,0 +1,3 @@
# Callers select p10k_config before sourcing this module.
ZLE_RPROMPT_INDENT=0
[[ -z "$p10k_config" || ! -f "$p10k_config" ]] || source "$p10k_config"
+61
View File
@@ -0,0 +1,61 @@
# Background repository maintenance shared by desktop and server shells.
update_dotfiles() {
local repo="$HOME/dotfiles"
local cache_dir="${ZDOTDIR:-$HOME}/.cache/zsh"
local notice_file="$cache_dir/dotfiles-update-notice"
local notice_tmp="$notice_file.$$.tmp"
local -a TO; (( $+commands[timeout] )) && TO=(timeout -k 5 15)
GIT_SSH_COMMAND='ssh -o BatchMode=yes -o ConnectTimeout=5 -o ControlMaster=no -o ControlPath=none' \
$TO git -C "$repo" fetch --quiet </dev/null 2>/dev/null || return
git -C "$repo" rev-parse --abbrev-ref '@{u}' >/dev/null 2>&1 || return
git -C "$repo" merge-base --is-ancestor '@{u}' HEAD 2>/dev/null && return
git -C "$repo" merge --ff-only --quiet '@{u}' 2>/dev/null && return
local notice="⚠ dotfiles: $(git -C "$repo" symbolic-ref --short HEAD) can't fast-forward to @{u} — run: git -C ~/dotfiles pull"
mkdir -p "$cache_dir" || return
print -r -- "$notice" >| "$notice_tmp" || return
mv -f "$notice_tmp" "$notice_file"
}
update_dotfiles &!
check_tools_repo() {
local repo branch remote mergeref remote_sha local_sha cmd notice
local cache_dir="${ZDOTDIR:-$HOME}/.cache/zsh"
local notice_file="$cache_dir/tools-update-notice"
local notice_tmp="$notice_file.$$.tmp"
local -a TO; (( $+commands[timeout] )) && TO=(timeout -k 5 10)
for repo in /opt/tools "$HOME/tools" "$HOME/tools/tools-repo"; do
local -a g=(git -c 'safe.directory=*' -C "$repo")
$g rev-parse --is-inside-work-tree >/dev/null 2>&1 || continue
branch=$($g symbolic-ref --short HEAD 2>/dev/null) || return
remote=$($g config "branch.$branch.remote" 2>/dev/null) || return
mergeref=$($g config "branch.$branch.merge" 2>/dev/null) || return
remote_sha=$(GIT_SSH_COMMAND='ssh -o BatchMode=yes -o ConnectTimeout=5 -o ControlMaster=no -o ControlPath=none' \
$TO $g ls-remote "$remote" "$mergeref" </dev/null 2>/dev/null | awk '{print $1}')
local_sha=$($g rev-parse HEAD 2>/dev/null)
[[ -n "$remote_sha" && -n "$local_sha" ]] || return
[[ "$remote_sha" == "$local_sha" ]] && return
$g merge-base --is-ancestor "$remote_sha" HEAD 2>/dev/null && return
[[ -w "$repo/.git" ]] && cmd="git -C $repo pull" || cmd="sudo git -C $repo pull"
notice="⬆ tools: updates available in $repo — run: $cmd"
mkdir -p "$cache_dir" || return
print -r -- "$notice" >| "$notice_tmp" || return
mv -f "$notice_tmp" "$notice_file"
return
done
}
check_tools_repo &!
show_update_notices() {
local cache_dir="${ZDOTDIR:-$HOME}/.cache/zsh"
local notice_file claimed_notice
for notice_file in "$cache_dir"/{dotfiles,tools}-update-notice; do
[[ -s "$notice_file" ]] || continue
claimed_notice="$notice_file.$$.show"
mv "$notice_file" "$claimed_notice" 2>/dev/null || continue
command cat "$claimed_notice"
command rm -f "$claimed_notice"
done
}
autoload -Uz add-zsh-hook
add-zsh-hook precmd show_update_notices