fix(shell/cached-eval): find usable md5 command and improve reliability

This commit is contained in:
2024-05-18 23:34:52 +01:00
parent 43be9196eb
commit 3a6e6a5256
2 changed files with 20 additions and 16 deletions

32
zshenv
View File

@@ -85,8 +85,7 @@ source-if-exists() {
# $1 - source_file: The path to the source file that the command depends on.
# If this file is newer than the cache, the command is
# re-executed and the cache is updated.
# $2 - cmd: The command to execute.
# $@ - args: Additional arguments to pass to the command.
# $@ - script: The command to execute and cache the output of.
#
# Example usage:
#
@@ -98,25 +97,30 @@ source-if-exists() {
# command is re-executed and cache is updated.
cached-eval() {
local source_file="$1"
local cmd="$2"
shift 2
local args="$@"
local full_cmd="$cmd $args"
shift 1
local script="$@"
local cache_dir="${ZSH_CACHED_EVAL_DIR:-$HOME/.local/share/zsh/cached-eval}"
if [[ -z "$(command -v "$cmd")" ]]; then
echo "cached-eval: Command not found: $cmd" >&2
if [[ ! -f "$source_file" ]]; then
echo "cached-eval: Source file not found: $source_file" >&2
return 1
fi
local cache_hash="$(echo -n "$full_cmd" | md5sum | awk '{print $1}')"
local cache_file="${cache_dir}/$(basename "$cmd")_${cache_hash}.zsh"
local md5_cmd="$(command -v md5 || command -v md5sum)"
local cache_hash="$(echo -n "$script" | "$md5_cmd" | awk '{print $1}')"
local cache_file="${cache_dir}/${cache_hash}.cache.zsh"
if [ -z "$cache_hash" ]; then
echo "cached-eval: Failed to compute cache hash for: $script" >&2
return 1
fi
if [[ ! -f "$cache_file" || "$source_file" -nt "$cache_file" ]]; then
mkdir -p "$cache_dir"
echo "cached-eval: Updating cache for: $full_cmd --> $cache_file" >&2
echo -e "#\n# Generated by cached-eval: $full_cmd\n#\n" >| "$cache_file"
eval "$full_cmd" >>| "$cache_file"
echo "cached-eval: Updating cache for: $script --> $cache_file" >&2
echo -e "#\n# Generated by cached-eval: $script\n#\n" >| "$cache_file"
eval "$script" >>| "$cache_file"
fi
source "$cache_file"
@@ -178,7 +182,7 @@ fi
# Homebrew on Apple Silicon
if [ -f "/opt/homebrew/bin/brew" ]; then
cached-eval /opt/homebrew/bin/brew /opt/homebrew/bin/brew shellenv
cached-eval "/opt/homebrew/bin/brew" /opt/homebrew/bin/brew shellenv
fi
if command-exists brew; then