-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemo
More file actions
executable file
·92 lines (77 loc) · 2.25 KB
/
memo
File metadata and controls
executable file
·92 lines (77 loc) · 2.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#!/usr/bin/env bash
# memo - Memoize command output with cache lifetime
# Usage: memo [OPTIONS] COMMAND [ARGS...]
# Example: memo curl example.com | jq '.data'
set -euo pipefail
# Default cache TTL in seconds (1 hour)
DEFAULT_TTL=3600
CACHE_DIR="${XDG_CACHE_HOME:-$HOME/.cache}/memo"
show_help() {
cat <<EOF
memo - Memoize command output with cache lifetime
Usage: memo [OPTIONS] COMMAND [ARGS...]
Options:
--ttl SECONDS Cache lifetime in seconds (default: $DEFAULT_TTL)
-f, --force Force recreation of cache, ignoring existing cached value
-h, --help Show this help message
Examples:
memo curl example.com # Cache curl output for 1 hour
memo --ttl 60 curl example.com # Cache for 60 seconds
memo -f curl example.com # Force refresh, ignore cache
EOF
exit 0
}
# Parse options
TTL="$DEFAULT_TTL"
FORCE=false
while [[ $# -gt 0 ]]; do
case "$1" in
-h|--help)
show_help
;;
--ttl)
TTL="$2"
shift 2
;;
-f|--force)
FORCE=true
shift
;;
*)
break
;;
esac
done
# Check if command provided
if [[ $# -eq 0 ]]; then
echo "Usage: memo [OPTIONS] COMMAND [ARGS...]" >&2
echo "Try 'memo --help' for more information." >&2
exit 1
fi
# Create cache directory
mkdir -p "$CACHE_DIR"
# Clean up old cache files (older than DEFAULT_TTL)
find "$CACHE_DIR" -type f -mtime +$((DEFAULT_TTL / 86400)) -delete 2>/dev/null || true
# Generate cache key from command and arguments
CACHE_KEY=$(echo -n "$*" | shasum -a 256 | cut -d' ' -f1)
CACHE_FILE="$CACHE_DIR/$CACHE_KEY"
# Check if cache exists and is fresh (unless force is set)
if [[ "$FORCE" == false && -f "$CACHE_FILE" ]]; then
# Get cache file age in seconds
if [[ "$(uname)" == "Darwin" ]]; then
# macOS
CACHE_MTIME=$(stat -f %m "$CACHE_FILE")
else
# Linux
CACHE_MTIME=$(stat -c %Y "$CACHE_FILE")
fi
CURRENT_TIME=$(date +%s)
CACHE_AGE=$((CURRENT_TIME - CACHE_MTIME))
if [[ $CACHE_AGE -lt $TTL ]]; then
# Cache is fresh, return it
cat "$CACHE_FILE"
exit 0
fi
fi
# Cache miss or expired - run command and cache output
"$@" | tee "$CACHE_FILE"