# Startup helpers: output caching and slow-start logging. zmodload zsh/datetime zmodload -F zsh/stat b:zstat # Cache a command's output; regenerate when a dependency's resolved path or # mtime changes (brew upgrades swap Cellar paths but keep old mtimes). # Usage: _zsh_cached [dep...] -- ; sets REPLY to the cache file. _zsh_cached() { local file=${ZDOTDIR:-$HOME}/.cache/zsh/$1 stamp old local -a mt shift while [[ $# -gt 0 && $1 != -- ]]; do mt=(); zstat -A mt +mtime -- $1 2>/dev/null stamp+="${1:A}@${mt[1]:-none};" shift done shift [[ -r $file.stamp ]] && read -r old < $file.stamp if [[ ! -s $file || $old != $stamp ]]; then local tmp=$file.$$.tmp if "$@" >| $tmp 2>/dev/null && [[ -s $tmp ]]; then command mv -f $tmp $file print -r -- $stamp >| $file.stamp else command rm -f $tmp [[ -s $file ]] || return 1 fi fi REPLY=$file } # Slow-start log: per-step ms, written only if startup (until the first prompt) # exceeds ZSH_STARTUP_LOG_MS. Diagnostic for cold starts; remove once resolved. typeset -gF _zst_t0=$EPOCHREALTIME _zst_last=$EPOCHREALTIME typeset -ga _zst_steps _zst_mark() { local ms printf -v ms '%s=%.0f' $1 $(( (EPOCHREALTIME - _zst_last) * 1000 )) _zst_steps+=($ms) _zst_last=$EPOCHREALTIME } _zst_report() { add-zsh-hook -d precmd _zst_report _zst_mark precmd local total=$(( (EPOCHREALTIME - _zst_t0) * 1000 )) (( total >= ${ZSH_STARTUP_LOG_MS:-1000} )) || return 0 local ts login=0 strftime -s ts '%Y-%m-%dT%H:%M:%S' $EPOCHSECONDS [[ -o login ]] && login=1 printf '%s total=%.0f tmux=%d login=%d | %s\n' $ts $total ${+TMUX} $login "$_zst_steps" \ >> ${ZDOTDIR:-$HOME}/.cache/zsh/startup-slow.log }