#!/usr/bin/env zsh
# ── functions.zsh : git helpers, hash toolkit, palette, cheat, OMZ reimpls ──
# Ported from ~/.zshrc; pentest funcs live in pentest-tools.zsh.
# ── portable shims (BSD/macOS vs GNU/Linux) ─────────────────────────────────
# The hash toolkit below was written against macOS coreutils. `md5`, `stat -f`
# and `date -r <epoch>` are BSD spellings; GNU uses `md5sum`, `stat -c` and
# `date -d @<epoch>`. GNU's `date -r` means "this FILE's mtime", and GNU's
# `stat -f` means --file-system, so the BSD forms do not merely differ -- they
# fail. These wrappers keep both platforms working.
_pf_md5() { # file arg or stdin -> bare hex digest
if (( $+commands[md5] )); then
if [[ -n $1 ]]; then _pf_md5 "$1"; else md5 -q; fi
else
if [[ -n $1 ]]; then md5sum "$1" | awk '{print $1}'; else md5sum | awk '{print $1}'; fi
fi
}
_pf_size() { stat -c%s "$1" 2>/dev/null || stat -f%z "$1" 2>/dev/null; }
_pf_mtime() { stat -c%y "$1" 2>/dev/null || stat -f%Sm "$1" 2>/dev/null; }
_pf_perm() { stat -c%A "$1" 2>/dev/null || stat -f%Sp "$1" 2>/dev/null; }
_pf_epoch() { date -d "@$1" "$2" 2>/dev/null || date -r "$1" "$2" 2>/dev/null; }
# ── git date helpers + comprehensive hash toolkit ──
# Git date helpers
gcommitdate() {
local msg="$*"
if [ -z "$msg" ]; then
echo "Usage: gcommitdate <message>"
return 1
fi
git commit -m "$(date '+%Y-%m-%d %H:%M:%S') - $msg"
}
glastupdate() {
local ts
ts=$(git log -1 --format=%ct 2>/dev/null) || return 1
if [ -z "$ts" ]; then
echo "Not a git repo"
return 1
fi
_pf_epoch "$ts" '+%Y-%m-%d %H:%M:%S'
}
# ============================================
# COMPREHENSIVE HASH TOOLKIT
# File & Directory Hashing with Timestamps
# ============================================
# Hash output directory (default: current dir, can override)
export HASH_OUTPUT_DIR="${HASH_OUTPUT_DIR:-$PWD}"
# ──────────────────────────────────────────
# BASIC FILE HASHING (with timestamps)
# ──────────────────────────────────────────
# hf: Hash single file - all algorithms with timestamp
hf() {
local file="$1"
if [ -z "$file" ] || [ ! -f "$file" ]; then
echo "Usage: hf <file>"
return 1
fi
local ts=$(date '+%Y-%m-%d %H:%M:%S')
local fname=$(basename "$file")
local fpath=$(realpath "$file")
local fsize=$(_pf_size "$file")
echo "══════════════════════════════════════════════════════════════"
echo "FILE: $fname"
echo "PATH: $fpath"
echo "SIZE: $fsize bytes ($(numfmt --to=iec $fsize 2>/dev/null || echo "$fsize bytes"))"
echo "HASHED: $ts"
echo "──────────────────────────────────────────────────────────────"
echo "MD5: $(_pf_md5 "$file")"
echo "SHA1: $(shasum -a 1 "$file" | awk '{print $1}')"
echo "SHA256: $(shasum -a 256 "$file" | awk '{print $1}')"
echo "SHA512: $(shasum -a 512 "$file" | awk '{print $1}')"
echo "══════════════════════════════════════════════════════════════"
}
# hfq: Quick hash (MD5 + SHA256 only)
hfq() {
local file="$1"
[ -z "$file" ] || [ ! -f "$file" ] && { echo "Usage: hfq <file>"; return 1; }
echo "$(date '+%H:%M:%S') | MD5: $(_pf_md5 "$file") | SHA256: $(shasum -a 256 "$file" | awk '{print $1}') | $file"
}
# Individual algorithm aliases
alias hmd5='function _hmd5() { echo "$(date +%H:%M:%S) | MD5: $(_pf_md5 "$1") | $1"; }; _hmd5'
alias hsha1='function _hsha1() { echo "$(date +%H:%M:%S) | SHA1: $(shasum -a 1 "$1" | awk "{print \$1}") | $1"; }; _hsha1'
alias hsha256='function _hsha256() { echo "$(date +%H:%M:%S) | SHA256: $(shasum -a 256 "$1" | awk "{print \$1}") | $1"; }; _hsha256'
alias hsha512='function _hsha512() { echo "$(date +%H:%M:%S) | SHA512: $(shasum -a 512 "$1" | awk "{print \$1}") | $1"; }; _hsha512'
# ──────────────────────────────────────────
# DIRECTORY HASHING
# ──────────────────────────────────────────
# hdir: Hash all files in directory (non-recursive)
hdir() {
local dir="${1:-.}"
local outfile="hashes_$(basename "$dir")_$(date +%Y%m%d_%H%M%S).txt"
[ ! -d "$dir" ] && { echo "Error: '$dir' is not a directory"; return 1; }
{
echo "═══════════════════════════════════════════════════════════════════"
echo "DIRECTORY HASH REPORT"
echo "Directory: $(realpath "$dir")"
echo "Generated: $(date '+%Y-%m-%d %H:%M:%S %Z')"
echo "Scope: Non-recursive (top-level files only)"
echo "═══════════════════════════════════════════════════════════════════"
echo ""
} > "$outfile"
local count=0
for file in "$dir"/*; do
[ -f "$file" ] || continue
((count++))
echo "[$count] Hashing: $(basename "$file")"
{
echo "FILE: $(basename "$file")"
echo "PATH: $(realpath "$file")"
echo "SIZE: $(_pf_size "$file") bytes"
echo "TIME: $(date '+%Y-%m-%d %H:%M:%S')"
echo "MD5: $(_pf_md5 "$file")"
echo "SHA256: $(shasum -a 256 "$file" | awk '{print $1}')"
echo "───────────────────────────────────────────────────────────────────"
} >> "$outfile"
done
echo "" >> "$outfile"
echo "TOTAL FILES: $count" >> "$outfile"
echo "✅ Hashed $count files -> $outfile"
}
# hdirr: Hash directory recursively (all subdirectories)
hdirr() {
local dir="${1:-.}"
local outfile="hashes_recursive_$(basename "$dir")_$(date +%Y%m%d_%H%M%S).txt"
[ ! -d "$dir" ] && { echo "Error: '$dir' is not a directory"; return 1; }
{
echo "═══════════════════════════════════════════════════════════════════"
echo "RECURSIVE DIRECTORY HASH REPORT"
echo "Directory: $(realpath "$dir")"
echo "Generated: $(date '+%Y-%m-%d %H:%M:%S %Z')"
echo "Scope: Recursive (all subdirectories)"
echo "═══════════════════════════════════════════════════════════════════"
echo ""
} > "$outfile"
local count=0
while IFS= read -r -d '' file; do
((count++))
echo "[$count] $(basename "$file")"
{
echo "FILE: $(basename "$file")"
echo "PATH: $file"
echo "SIZE: $(_pf_size "$file") bytes"
echo "TIME: $(date '+%Y-%m-%d %H:%M:%S')"
echo "MD5: $(_pf_md5 "$file")"
echo "SHA256: $(shasum -a 256 "$file" | awk '{print $1}')"
echo "───────────────────────────────────────────────────────────────────"
} >> "$outfile"
done < <(find "$dir" -type f -print0 2>/dev/null)
echo "" >> "$outfile"
echo "TOTAL FILES: $count" >> "$outfile"
echo "✅ Recursively hashed $count files -> $outfile"
}
# ──────────────────────────────────────────
# HASH WITH LOGGING TO FILE
# ──────────────────────────────────────────
# hlog: Hash file and append to persistent log
hlog() {
local file="$1"
local logfile="${2:-$HOME/.hash_log.txt}"
[ -z "$file" ] || [ ! -f "$file" ] && { echo "Usage: hlog <file> [logfile]"; return 1; }
local entry="$(date '+%Y-%m-%d %H:%M:%S') | $(realpath "$file") | SIZE:$(_pf_size "$file") | MD5:$(_pf_md5 "$file") | SHA256:$(shasum -a 256 "$file" | awk '{print $1}')"
echo "$entry" | tee -a "$logfile"
echo "✅ Logged to: $logfile"
}
# hlogview: View hash log
alias hlogview='cat $HOME/.hash_log.txt 2>/dev/null || echo "No hash log found"'
alias hlogclear='rm -i $HOME/.hash_log.txt'
# ──────────────────────────────────────────
# OUTPUT FORMATS (JSON, CSV)
# ──────────────────────────────────────────
# hjson: Hash to JSON format
hjson() {
local file="$1"
[ -z "$file" ] || [ ! -f "$file" ] && { echo "Usage: hjson <file>"; return 1; }
local fname=$(basename "$file")
local fpath=$(realpath "$file")
local fsize=$(_pf_size "$file")
local ts=$(date '+%Y-%m-%dT%H:%M:%S%z')
local md5=$(_pf_md5 "$file")
local sha1=$(shasum -a 1 "$file" | awk '{print $1}')
local sha256=$(shasum -a 256 "$file" | awk '{print $1}')
local sha512=$(shasum -a 512 "$file" | awk '{print $1}')
cat <<EOF
{
"filename": "$fname",
"filepath": "$fpath",
"size_bytes": $fsize,
"hashed_at": "$ts",
"hashes": {
"md5": "$md5",
"sha1": "$sha1",
"sha256": "$sha256",
"sha512": "$sha512"
}
}
EOF
}
# hdirjson: Hash directory to JSON array
hdirjson() {
local dir="${1:-.}"
local outfile="hashes_$(basename "$dir")_$(date +%Y%m%d_%H%M%S).json"
[ ! -d "$dir" ] && { echo "Error: '$dir' is not a directory"; return 1; }
echo "[" > "$outfile"
local first=true
while IFS= read -r -d '' file; do
$first || echo "," >> "$outfile"
first=false
hjson "$file" >> "$outfile"
echo -n "."
done < <(find "$dir" -type f -print0 2>/dev/null)
echo ""
echo "]" >> "$outfile"
echo "✅ JSON output -> $outfile"
}
# hcsv: Hash to CSV format
hcsv() {
local file="$1"
[ -z "$file" ] || [ ! -f "$file" ] && { echo "Usage: hcsv <file>"; return 1; }
echo "timestamp,filename,filepath,size_bytes,md5,sha256"
echo "$(date '+%Y-%m-%d %H:%M:%S'),$(basename "$file"),$(realpath "$file"),$(_pf_size "$file"),$(_pf_md5 "$file"),$(shasum -a 256 "$file" | awk '{print $1}')"
}
# hdircsv: Hash directory to CSV file
hdircsv() {
local dir="${1:-.}"
local outfile="hashes_$(basename "$dir")_$(date +%Y%m%d_%H%M%S).csv"
[ ! -d "$dir" ] && { echo "Error: '$dir' is not a directory"; return 1; }
echo "timestamp,filename,filepath,size_bytes,md5,sha256" > "$outfile"
local count=0
while IFS= read -r -d '' file; do
((count++))
echo "$(date '+%Y-%m-%d %H:%M:%S'),$(basename "$file"),$(realpath "$file"),$(_pf_size "$file"),$(_pf_md5 "$file"),$(shasum -a 256 "$file" | awk '{print $1}')" >> "$outfile"
echo -n "."
done < <(find "$dir" -type f -print0 2>/dev/null)
echo ""
echo "✅ CSV output ($count files) -> $outfile"
}
# ──────────────────────────────────────────
# HASH COMPARISON & VERIFICATION
# ──────────────────────────────────────────
# hcmp: Compare two files by hash
hcmp() {
local file1="$1"
local file2="$2"
[ -z "$file1" ] || [ -z "$file2" ] && { echo "Usage: hcmp <file1> <file2>"; return 1; }
[ ! -f "$file1" ] && { echo "Error: '$file1' not found"; return 1; }
[ ! -f "$file2" ] && { echo "Error: '$file2' not found"; return 1; }
local h1=$(shasum -a 256 "$file1" | awk '{print $1}')
local h2=$(shasum -a 256 "$file2" | awk '{print $1}')
echo "File 1: $file1"
echo "SHA256: $h1"
echo ""
echo "File 2: $file2"
echo "SHA256: $h2"
echo ""
if [ "$h1" = "$h2" ]; then
echo "✅ MATCH - Files are identical"
return 0
else
echo "❌ MISMATCH - Files differ"
return 1
fi
}
# hverify: Verify file against known hash
hverify() {
local file="$1"
local expected="$2"
local algo="${3:-sha256}"
[ -z "$file" ] || [ -z "$expected" ] && { echo "Usage: hverify <file> <expected_hash> [md5|sha1|sha256|sha512]"; return 1; }
[ ! -f "$file" ] && { echo "Error: '$file' not found"; return 1; }
local actual
case "$algo" in
md5) actual=$(_pf_md5 "$file") ;;
sha1) actual=$(shasum -a 1 "$file" | awk '{print $1}') ;;
sha256) actual=$(shasum -a 256 "$file" | awk '{print $1}') ;;
sha512) actual=$(shasum -a 512 "$file" | awk '{print $1}') ;;
*) echo "Unknown algorithm: $algo"; return 1 ;;
esac
echo "File: $file"
echo "Algorithm: $algo"
echo "Expected: $expected"
echo "Actual: $actual"
echo ""
if [ "${expected,,}" = "${actual,,}" ]; then
echo "✅ VERIFIED - Hash matches"
return 0
else
echo "❌ FAILED - Hash does not match"
return 1
fi
}
# hchecksum: Generate checksum file (compatible with shasum -c)
hchecksum() {
local dir="${1:-.}"
local algo="${2:-256}"
local outfile="SHA${algo}SUMS_$(date +%Y%m%d_%H%M%S).txt"
[ ! -d "$dir" ] && { echo "Error: '$dir' is not a directory"; return 1; }
echo "# Generated: $(date '+%Y-%m-%d %H:%M:%S')" > "$outfile"
echo "# Directory: $(realpath "$dir")" >> "$outfile"
find "$dir" -type f -print0 2>/dev/null | while IFS= read -r -d '' file; do
shasum -a "$algo" "$file" >> "$outfile"
echo -n "."
done
echo ""
echo "✅ Checksum file -> $outfile"
echo " Verify with: shasum -a $algo -c $outfile"
}
# hverifychecksum: Verify against checksum file
alias hverifychecksum='shasum -c'
# ──────────────────────────────────────────
# DUPLICATE FILE DETECTION
# ──────────────────────────────────────────
# hdupes: Find duplicate files by hash
hdupes() {
local dir="${1:-.}"
local outfile="duplicates_$(date +%Y%m%d_%H%M%S).txt"
[ ! -d "$dir" ] && { echo "Error: '$dir' is not a directory"; return 1; }
echo "🔍 Scanning for duplicates in: $dir"
echo "═══════════════════════════════════════════════════════════════════" > "$outfile"
echo "DUPLICATE FILE REPORT" >> "$outfile"
echo "Directory: $(realpath "$dir")" >> "$outfile"
echo "Generated: $(date '+%Y-%m-%d %H:%M:%S')" >> "$outfile"
echo "═══════════════════════════════════════════════════════════════════" >> "$outfile"
# Build hash -> files mapping
local tmpfile=$(mktemp)
find "$dir" -type f -print0 2>/dev/null | while IFS= read -r -d '' file; do
echo "$(shasum -a 256 "$file" | awk '{print $1}') $file"
done | sort > "$tmpfile"
# Find duplicates
local dupes=$(awk '{print $1}' "$tmpfile" | sort | uniq -d)
if [ -z "$dupes" ]; then
echo "" >> "$outfile"
echo "No duplicates found." >> "$outfile"
echo "✅ No duplicates found"
else
echo "" >> "$outfile"
echo "$dupes" | while read hash; do
echo "" >> "$outfile"
echo "HASH: $hash" >> "$outfile"
echo "FILES:" >> "$outfile"
grep "^$hash " "$tmpfile" | awk '{$1=""; print " " $0}' >> "$outfile"
done
echo ""
echo "✅ Duplicate report -> $outfile"
cat "$outfile"
fi
rm -f "$tmpfile"
}
# ──────────────────────────────────────────
# FORENSIC/CHAIN OF CUSTODY HASHING
# ──────────────────────────────────────────
# hforensic: Generate forensic-grade hash report
hforensic() {
local target="$1"
local case_id="${2:-CASE-$(date +%Y%m%d)}"
local examiner="${3:-$(whoami)}"
local outfile="forensic_hash_${case_id}_$(date +%Y%m%d_%H%M%S).txt"
[ -z "$target" ] || [ ! -e "$target" ] && { echo "Usage: hforensic <file|dir> [case_id] [examiner]"; return 1; }
{
echo "╔════════════════════════════════════════════════════════════════════════════╗"
echo "║ FORENSIC HASH VERIFICATION REPORT ║"
echo "╚════════════════════════════════════════════════════════════════════════════╝"
echo ""
echo "CASE INFORMATION"
echo "────────────────────────────────────────────────────────────────────────────"
echo "Case ID: $case_id"
echo "Examiner: $examiner"
echo "Hostname: $(hostname)"
echo "Report Generated: $(date '+%Y-%m-%d %H:%M:%S %Z')"
echo "Working Dir: $(pwd)"
echo ""
echo "EVIDENCE ITEM(S)"
echo "────────────────────────────────────────────────────────────────────────────"
if [ -f "$target" ]; then
echo "Type: Single File"
echo "Filename: $(basename "$target")"
echo "Full Path: $(realpath "$target")"
echo "Size: $(_pf_size "$target") bytes"
echo "Modified: $(_pf_mtime "$target")"
echo "Permissions: $(_pf_perm "$target")"
echo ""
echo "HASH VALUES"
echo "────────────────────────────────────────────────────────────────────────────"
echo "MD5: $(_pf_md5 "$target")"
echo "SHA1: $(shasum -a 1 "$target" | awk '{print $1}')"
echo "SHA256: $(shasum -a 256 "$target" | awk '{print $1}')"
echo "SHA512: $(shasum -a 512 "$target" | awk '{print $1}')"
else
echo "Type: Directory"
echo "Path: $(realpath "$target")"
echo "Total Files: $(find "$target" -type f | wc -l | tr -d ' ')"
echo "Total Size: $(du -sh "$target" | awk '{print $1}')"
echo ""
echo "FILE INVENTORY WITH HASHES"
echo "────────────────────────────────────────────────────────────────────────────"
local idx=0
while IFS= read -r -d '' file; do
((idx++))
echo ""
echo "[$idx] $(basename "$file")"
echo " Path: $file"
echo " Size: $(_pf_size "$file") bytes"
echo " Modified: $(_pf_mtime "$file")"
echo " MD5: $(_pf_md5 "$file")"
echo " SHA256: $(shasum -a 256 "$file" | awk '{print $1}')"
done < <(find "$target" -type f -print0 2>/dev/null | sort -z)
fi
echo ""
echo "════════════════════════════════════════════════════════════════════════════"
echo "END OF REPORT"
echo "Report Hash (SHA256): [Calculate after saving]"
echo "════════════════════════════════════════════════════════════════════════════"
} > "$outfile"
# Self-hash the report
local report_hash=$(shasum -a 256 "$outfile" | awk '{print $1}')
sed -i '' "s/\[Calculate after saving\]/$report_hash/" "$outfile"
echo "✅ Forensic report -> $outfile"
echo " Report SHA256: $report_hash"
}
# ──────────────────────────────────────────
# HASH MONITORING (Change Detection)
# ──────────────────────────────────────────
# hwatch: Create baseline hash snapshot
hwatch() {
local dir="${1:-.}"
local baseline="$HOME/.hash_baseline_$(echo "$dir" | _pf_md5).txt"
[ ! -d "$dir" ] && { echo "Error: '$dir' is not a directory"; return 1; }
echo "# Hash Baseline: $(realpath "$dir")" > "$baseline"
echo "# Created: $(date '+%Y-%m-%d %H:%M:%S')" >> "$baseline"
find "$dir" -type f -print0 2>/dev/null | while IFS= read -r -d '' file; do
echo "$(shasum -a 256 "$file")"
done >> "$baseline"
echo "✅ Baseline created: $baseline"
echo " Files tracked: $(grep -v '^#' "$baseline" | wc -l | tr -d ' ')"
}
# hchanges: Check for changes since baseline
hchanges() {
local dir="${1:-.}"
local baseline="$HOME/.hash_baseline_$(echo "$dir" | _pf_md5).txt"
[ ! -f "$baseline" ] && { echo "No baseline found. Run: hwatch $dir"; return 1; }
echo "🔍 Checking for changes in: $dir"
echo " Baseline: $baseline"
echo ""
local changes=0
# Check for modified/deleted files
while read -r line; do
[[ "$line" =~ ^# ]] && continue
local hash=$(echo "$line" | awk '{print $1}')
local file=$(echo "$line" | awk '{print $2}')
if [ ! -f "$file" ]; then
echo "❌ DELETED: $file"
((changes++))
else
local current=$(shasum -a 256 "$file" | awk '{print $1}')
if [ "$hash" != "$current" ]; then
echo "⚠️ MODIFIED: $file"
((changes++))
fi
fi
done < "$baseline"
# Check for new files
while IFS= read -r -d '' file; do
if ! grep -q " $file$" "$baseline" 2>/dev/null; then
echo "➕ NEW: $file"
((changes++))
fi
done < <(find "$dir" -type f -print0 2>/dev/null)
echo ""
if [ $changes -eq 0 ]; then
echo "✅ No changes detected"
else
echo "⚠️ $changes change(s) detected"
fi
}
# ──────────────────────────────────────────
# HASH PIPED/STDIN DATA
# ──────────────────────────────────────────
# hpipe: Hash data from stdin
alias hpipe='shasum -a 256'
alias hpipe-md5='md5'
alias hpipe-sha1='shasum -a 1'
alias hpipe-sha512='shasum -a 512'
# hstr: Hash a string directly
hstr() {
local str="$1"
[ -z "$str" ] && { echo "Usage: hstr <string>"; return 1; }
echo "String: $str"
echo "MD5: $(echo -n "$str" | md5)"
echo "SHA256: $(echo -n "$str" | shasum -a 256 | awk '{print $1}')"
}
# ──────────────────────────────────────────
# BATCH & PARALLEL HASHING
# ──────────────────────────────────────────
# hbatch: Hash multiple files (arguments)
hbatch() {
[ $# -eq 0 ] && { echo "Usage: hbatch <file1> <file2> ..."; return 1; }
local ts=$(date '+%Y-%m-%d %H:%M:%S')
echo "═══════════════════════════════════════════════════════════════════"
echo "BATCH HASH REPORT - $ts"
echo "═══════════════════════════════════════════════════════════════════"
for file in "$@"; do
if [ -f "$file" ]; then
echo ""
echo "FILE: $file"
echo "SIZE: $(_pf_size "$file") bytes"
echo "MD5: $(_pf_md5 "$file")"
echo "SHA256: $(shasum -a 256 "$file" | awk '{print $1}')"
echo "───────────────────────────────────────────────────────────────────"
else
echo "⚠️ Skipped (not found): $file"
fi
done
}
# hparallel: Parallel hash directory (faster for large dirs)
hparallel() {
local dir="${1:-.}"
local outfile="hashes_parallel_$(date +%Y%m%d_%H%M%S).txt"
local jobs="${2:-4}"
[ ! -d "$dir" ] && { echo "Error: '$dir' is not a directory"; return 1; }
if ! command -v parallel >/dev/null 2>&1; then
echo "⚠️ GNU Parallel not found. Install: brew install parallel"
echo " Falling back to sequential hashing..."
hdirr "$dir"
return
fi
echo "🚀 Parallel hashing with $jobs jobs..."
echo "# Parallel Hash Report - $(date '+%Y-%m-%d %H:%M:%S')" > "$outfile"
echo "# Directory: $(realpath "$dir")" >> "$outfile"
find "$dir" -type f -print0 2>/dev/null | \
parallel -0 -j "$jobs" "echo \"{}: \$(shasum -a 256 {} | awk '{print \$1}')\"" >> "$outfile"
echo "✅ Parallel hash complete -> $outfile"
}
# ──────────────────────────────────────────
# HASH BY FILE TYPE / EXTENSION
# ──────────────────────────────────────────
# hext: Hash files by extension
hext() {
local ext="$1"
local dir="${2:-.}"
[ -z "$ext" ] && { echo "Usage: hext <extension> [directory]"; return 1; }
echo "Hashing *.$ext files in $dir"
echo "═══════════════════════════════════════════════════════════════════"
find "$dir" -type f -name "*.$ext" 2>/dev/null | while read -r file; do
echo "$(date '+%H:%M:%S') | $(shasum -a 256 "$file" | awk '{print $1}') | $file"
done
}
# Common extension shortcuts
alias himg='function _himg() { hext jpg "${1:-.}"; hext jpeg "${1:-.}"; hext png "${1:-.}"; hext gif "${1:-.}"; }; _himg'
alias hdoc='function _hdoc() { hext pdf "${1:-.}"; hext doc "${1:-.}"; hext docx "${1:-.}"; hext txt "${1:-.}"; }; _hdoc'
alias hcode='function _hcode() { hext py "${1:-.}"; hext js "${1:-.}"; hext sh "${1:-.}"; hext c "${1:-.}"; hext cpp "${1:-.}"; }; _hcode'
# ──────────────────────────────────────────
# HASH SIZE FILTERING
# ──────────────────────────────────────────
# hbig: Hash files larger than size
hbig() {
local size="${1:-10M}"
local dir="${2:-.}"
echo "Hashing files larger than $size in $dir"
echo "═══════════════════════════════════════════════════════════════════"
find "$dir" -type f -size "+$size" 2>/dev/null | while read -r file; do
echo "$(_pf_size "$file") bytes | $(shasum -a 256 "$file" | awk '{print $1}') | $file"
done | sort -rn
}
# hsmall: Hash files smaller than size
hsmall() {
local size="${1:-1K}"
local dir="${2:-.}"
echo "Hashing files smaller than $size in $dir"
find "$dir" -type f -size "-$size" 2>/dev/null | while read -r file; do
echo "$(_pf_size "$file") bytes | $(shasum -a 256 "$file" | awk '{print $1}') | $file"
done
}
# ──────────────────────────────────────────
# HASH HELP
# ──────────────────────────────────────────
hash-help() {
cat << 'EOF'
╔══════════════════════════════════════════════════════════════════════════════╗
║ HASH TOOLKIT QUICK REFERENCE ║
╚══════════════════════════════════════════════════════════════════════════════╝
SINGLE FILE HASHING
hf <file> Full hash (MD5, SHA1, SHA256, SHA512 + metadata)
hfq <file> Quick hash (MD5 + SHA256 only)
hmd5 <file> MD5 only
hsha256 <file> SHA256 only
hsha512 <file> SHA512 only
DIRECTORY HASHING
hdir [dir] Hash top-level files only
hdirr [dir] Hash recursively (all subdirectories)
hparallel [dir] Fast parallel hashing (requires GNU parallel)
OUTPUT FORMATS
hjson <file> JSON output
hdirjson [dir] Directory to JSON array
hcsv <file> CSV output
hdircsv [dir] Directory to CSV file
COMPARISON & VERIFICATION
hcmp <f1> <f2> Compare two files
hverify <file> <hash> [algo] Verify against known hash
hchecksum [dir] Generate SHA256SUMS file
hverifychecksum Verify checksum file
LOGGING & TRACKING
hlog <file> Append hash to persistent log
hlogview View hash log
hwatch [dir] Create baseline snapshot
hchanges [dir] Check for changes since baseline
SPECIAL USE CASES
hforensic <target> Forensic chain-of-custody report
hdupes [dir] Find duplicate files
hbatch <files...> Hash multiple files
hstr "text" Hash a string
hpipe Hash stdin (pipe data)
FILTERED HASHING
hext <ext> [dir] Hash by extension
himg [dir] Hash images
hdoc [dir] Hash documents
hcode [dir] Hash code files
hbig [size] [dir] Hash files > size (e.g., 10M)
hsmall [size] [dir] Hash files < size
Full cheat sheet: ~/Downloads/hash-cheatsheet.txt
EOF
}
alias hhelp='hash-help'
# ── gcommit (staged summary commit helper) ──
gcommit() {
# Abort if nothing is staged
if git diff --cached --quiet; then
echo "❌ Nothing staged to commit. Run 'git add' first."
return 1
fi
local branch=$(git rev-parse --abbrev-ref HEAD)
local timestamp=$(date +"%d %b %Y %H:%M:%S %Z")
local author=$(git config user.name)
# File counts by status
local added=$(git diff --cached --name-only --diff-filter=A | wc -l | tr -d ' ')
local modified=$(git diff --cached --name-only --diff-filter=M | wc -l | tr -d ' ')
local deleted=$(git diff --cached --name-only --diff-filter=D | wc -l | tr -d ' ')
local renamed=$(git diff --cached --name-only --diff-filter=R | wc -l | tr -d ' ')
local total=$(git diff --cached --name-only | wc -l | tr -d ' ')
# Line counts
local insertions=$(git diff --cached --numstat | awk '{a+=$1} END {print a+0}')
local deletions=$(git diff --cached --numstat | awk '{d+=$2} END {print d+0}')
# Optional custom subject message
local subject="${1:-Update}"
# Per-file breakdown
local file_details=$(git diff --cached --numstat | \
awk '{printf " • %-50s +%-5s -%s\n", $3, $1, $2}')
# Status breakdown (A/M/D/R per file)
local status_details=$(git diff --cached --name-status | \
awk '{
status=$1; $1=""; sub(/^ /, "");
label="?";
if (status=="A") label="➕ Added ";
else if (status=="M") label="✏️ Modified";
else if (status=="D") label="🗑️ Deleted ";
else if (status~/^R/) label="🔀 Renamed ";
else if (status=="C") label="📋 Copied ";
printf " %s %s\n", label, $0
}')
# Build commit message
local msg="🔧 ${subject} [${branch}] | ${timestamp}
📊 Stats: +${insertions} / -${deletions} across ${total} file(s)
📁 Breakdown: ➕${added} ✏️${modified} 🗑️${deleted} 🔀${renamed}
👤 Author: ${author}
📝 Changes:
${status_details}
📈 Line changes per file:
${file_details}"
git commit -m "$msg"
}
# ── update-all (system/package updater) ──
# Branches on platform: the whole body was Homebrew + softwareupdate, which on
# Linux is four `command not found` lines and no update at all.
update-all() {
if (( $+commands[brew] )); then
print -P "%F{green}▰▰▶ Homebrew formulae%f"
brew update && brew upgrade
print -P "%F{green}▰▰▶ Homebrew casks%f"
brew upgrade --cask --greedy
print -P "%F{green}▰▰▶ Cleanup%f"
brew cleanup -s --prune=all && brew autoremove
if (( $+commands[mas] )); then
print -P "%F{green}▰▰▶ App Store%f"
mas upgrade
fi
print -P "%F{green}▰▰▶ macOS updates%f"
softwareupdate -l
print -P "%F{yellow}Run: sudo softwareupdate -i -a --restart%f"
return
fi
# Omarchy wraps pacman + AUR + its own migrations in one command; prefer it.
if (( $+commands[omarchy] )); then
print -P "%F{green}▰▰▶ Omarchy (system + AUR + migrations)%f"
omarchy update
elif (( $+commands[yay] )); then
print -P "%F{green}▰▰▶ pacman + AUR%f"
yay -Syu
elif (( $+commands[pacman] )); then
print -P "%F{green}▰▰▶ pacman%f"
sudo pacman -Syu
fi
if (( $+commands[flatpak] )); then
print -P "%F{green}▰▰▶ Flatpak%f"
flatpak update
fi
if (( $+commands[mise] )); then
print -P "%F{green}▰▰▶ mise tools%f"
mise upgrade
fi
print -P "%F{green}▰▰▶ Cleanup%f"
(( $+commands[paccache] )) && sudo paccache -rk2
(( $+commands[pacman] )) && { local orphans; orphans=(${(f)"$(pacman -Qtdq 2>/dev/null)"});
(( $#orphans )) && sudo pacman -Rns --noconfirm $orphans || print " no orphans" }
}
# ── yazi (y) · lazygit (lg) · fzf command palette (Alt-p / pal) ──
# ── yazi: `y` opens the TUI file manager, cd's to where you quit ─────────────
if command -v yazi >/dev/null 2>&1; then
y() {
local tmp cwd
tmp="$(mktemp -t yazi-cwd.XXXXXX)"
yazi "$@" --cwd-file="$tmp"
cwd="$(command cat -- "$tmp" 2>/dev/null)"
[[ -n "$cwd" && "$cwd" != "$PWD" ]] && builtin cd -- "$cwd"
rm -f -- "$tmp"
}
fi
# ── ranger: `ranger` cd's to where you quit (like `y` for yazi) ──────────────
if command -v ranger >/dev/null 2>&1; then
ranger() {
local tmp cwd
tmp="$(mktemp -t ranger-cwd.XXXXXX)"
command ranger --choosedir="$tmp" "$@"
cwd="$(command cat -- "$tmp" 2>/dev/null)"
[[ -n "$cwd" && "$cwd" != "$PWD" ]] && builtin cd -- "$cwd"
rm -f -- "$tmp"
}
fi
# ── lazygit ───────────────────────────────────────────────────────────────--
command -v lazygit >/dev/null 2>&1 && alias lg='lazygit'
# ── fzf command palette: Alt-p (or `pal`) → fuzzy menu over your aliases + │
# functions. Pick one; its name drops onto the command line.
if command -v fzf >/dev/null 2>&1; then
_palette_select() {
emulate -L zsh
local -a items; local a
for a in ${(k)aliases}; do items+="${a}"$'\t'"→ ${aliases[$a]}"; done
for a in ${(k)functions}; do [[ $a == _* ]] && continue; items+="${a}"$'\t'"(function)"; done
print -l -- "${items[@]}" | sort -u |
fzf --prompt='palette ▶ ' --height=70% --layout=reverse \
--delimiter=$'\t' --with-nth=1,2 \
--preview 'echo {2..}' --preview-window=down:3:wrap
}
_cmd_palette_widget() {
local sel; sel=$(_palette_select) || { zle reset-prompt; return; }
LBUFFER+="${sel%%$'\t'*} "
zle reset-prompt
}
zle -N _cmd_palette_widget
bindkey '^[p' _cmd_palette_widget # Alt-p
palette() { local sel; sel=$(_palette_select) || return; print -z "${sel%%$'\t'*} "; }
alias pal='palette'
fi
# ── cheat sheet (cheat / cheat <tool> / cheat menu / Alt-h) ──
# ── cheat sheet ──────────────────────────────────────────────────────────────
# `cheat` quick card · `cheat <tool>` full guide · `cheat menu` browse · Alt-h
_cheat_quick() {
print -P ""
print -P "%F{#9ccfd8}▰▰▶ TERMINAL CHEAT SHEET%f"
print -P "%F{#908caa}────────────────────────────────────────────────%f"
print -P "%F{#f6c177} navigate%f %F{#e0def4}z <dir>%f jump %F{#e0def4}zi%f pick %F{#e0def4}y%f yazi (cd on quit)"
print -P "%F{#f6c177} history %f %F{#e0def4}Ctrl-R%f atuin fuzzy search"
print -P "%F{#f6c177} palette %f %F{#e0def4}Alt-p%f / %F{#e0def4}pal%f fuzzy menu of all aliases+functions"
print -P "%F{#f6c177} git %f %F{#e0def4}lg%f lazygit %F{#e0def4}gs ga gc gp gco gd%f (abbr, expand inline)"
print -P "%F{#f6c177} jj %f %F{#e0def4}j%f log %F{#e0def4}js jn jdm jsq jtug%f %F{#e0def4}jundo%f (%F{#e0def4}jj-cheat%f · %F{#e0def4}cheat jj%f)"
print -P "%F{#f6c177} modern %f %F{#e0def4}top%f btop %F{#e0def4}du%f dust %F{#e0def4}df%f duf %F{#e0def4}ps%f procs %F{#e0def4}? <cmd>%f tldr"
print -P "%F{#f6c177} splash %f %F{#e0def4}cross [ring|rain|both]%f %F{#e0def4}verse%f %F{#e0def4}crosssym%f %F{#e0def4}bonsai%f"
print -P "%F{#f6c177} kitty %f %F{#e0def4}⌘D%f split %F{#e0def4}⌘⌥arrows%f resize %F{#e0def4}⌘⇧E/P/Y%f hints(url/path/hash)"
print -P "%F{#f6c177} %f %F{#e0def4}⌘⇧B/N%f watermark off/on"
print -P "%F{#f6c177} reload %f %F{#e0def4}reload%f (re-source ~/.zshrc)"
print -P "%F{#f6c177} grab %f %F{#e0def4}ytget <url…>%f %F{#e0def4}-f audio -e mp3%f %F{#e0def4}--playlist%f (%F{#e0def4}cheat ytget%f)"
print -P "%F{#f6c177} sync %f %F{#e0def4}rmove copy|move|mirror <src> <dest>%f %F{#e0def4}-n -q -V -a%f (%F{#e0def4}cheat rmove%f)"
print -P "%F{#f6c177} archive %f %F{#e0def4}tarx -a -xz9e <dir>%f %F{#e0def4}-e%f %F{#e0def4}-xzls%f %F{#e0def4}--encrypt -r KEY%f (%F{#e0def4}tarx-cheat%f)"
print -P "%F{#908caa}────────────────────────────────────────────────%f"
print -P "%F{#eb6f92} pentest %f %F{#e0def4}cheat pentest%f %F{#908caa}htb·recon·web·xss-scan·nxc·impacket·ad·bloodhound·cracking·pivoting·shells·c2%f"
print -P "%F{#908caa} deep dives:%f %F{#e0def4}cheat <modern|git|delta|yazi|ranger|lazygit|atuin|zoxide|abbr|fzf|palette|kitty|prompt|splash|ytget|rmove|tarx|gpgx|imgx|jj>%f"
print -P "%F{#908caa} browse all:%f %F{#e0def4}cheat menu%f %F{#908caa}(fzf + rendered preview)%f"
}
# cheat — quick card (no arg) · full guide (`cheat yazi`) · fzf browser (`cheat menu`)
cheat() {
local dir=~/.config/cheats
# Render in the Rosé Pine card style (see ~/.local/bin/cheat-render).
# Falls back to glow, then a pager, if the renderer isn't available.
local _open; _open() {
if command -v cheat-render >/dev/null 2>&1; then cheat-render "$1" | less -RFX
elif command -v glow >/dev/null 2>&1; then glow -p "$1"
else ${PAGER:-less} "$1"; fi
}
case "$1" in
"")
_cheat_quick
;;
menu|-m|--menu)
if ! command -v fzf >/dev/null 2>&1; then print -l -- "$dir"/*.md(N:t:r); return; fi
local sel
sel=$(print -l -- "$dir"/*.md(N:t:r) |
fzf --prompt='cheat ▶ ' --height=85% --layout=reverse --ansi \
--preview "cheat-render $dir/{}.md 2>/dev/null || cat $dir/{}.md" \
--preview-window=right:72%:wrap) || return
_open "$dir/$sel.md"
;;
*)
if [[ -f "$dir/$1.md" ]]; then _open "$dir/$1.md"
else print -P "%F{#eb6f92} no guide '$1'%f — try %F{#e0def4}cheat menu%f"; fi
;;
esac
}
bindkey -s '^[h' 'cheat\n' # Alt-h → quick card
# ─────────────────────────────────────────────────────────────────────────────
# OMZ-builtin reimplementations (we dropped oh-my-zsh; these replace the plugins
# we actually used: extract, copypath, copyfile, web-search, dirhistory,
# colored-man-pages, sudo). Cross-platform clipboard helper underpins copy*.
# ─────────────────────────────────────────────────────────────────────────────
# clipboard abstraction: macOS pbcopy / Wayland wl-copy / X11 xclip
_clip() {
if (( $+commands[pbcopy] )); then pbcopy
elif (( $+commands[wl-copy] )); then wl-copy
elif (( $+commands[xclip] )); then xclip -selection clipboard
else cat >/dev/null; print -u2 "no clipboard tool found"; return 1; fi
}
# extract <archive> — unpack almost anything (replaces omz `extract`)
extract() {
local f="$1"
[[ -f $f ]] || { print -u2 "usage: extract <archive>"; return 1; }
case "$f" in
*.tar.bz2|*.tbz2) tar xjf "$f" ;;
*.tar.gz|*.tgz) tar xzf "$f" ;;
*.tar.xz) tar xJf "$f" ;;
*.tar.zst) tar --zstd -xf "$f" ;;
*.tar) tar xf "$f" ;;
*.bz2) bunzip2 "$f" ;;
*.gz) gunzip "$f" ;;
*.xz) unxz "$f" ;;
*.zst) unzstd "$f" ;;
*.zip|*.jar|*.war) unzip "$f" ;;
*.rar) unrar x "$f" ;;
*.7z) 7z x "$f" ;;
*.Z) uncompress "$f" ;;
*) print -u2 "extract: unknown archive type: $f"; return 1 ;;
esac
}
alias x='extract'
# copypath [dir] — copy absolute path to clipboard (replaces omz `copypath`)
copypath() { local p="${1:-$PWD}"; print -rn -- "${p:A}" | _clip && print "copied: ${p:A}"; }
# copyfile <file> — copy file contents to clipboard (replaces omz `copyfile`)
copyfile() { [[ -f $1 ]] || { print -u2 "usage: copyfile <file>"; return 1; }; _clip < "$1" && print "copied contents of $1"; }
# web-search (replaces omz `web-search`): web_search <engine> terms…
web_search() {
local engine="$1"; shift
local q="${(j:+:)@}"
local url
case "$engine" in
google) url="https://www.google.com/search?q=$q" ;;
ddg|duck) url="https://duckduckgo.com/?q=$q" ;;
bing) url="https://www.bing.com/search?q=$q" ;;
github|gh) url="https://github.com/search?q=$q" ;;
*) url="https://duckduckgo.com/?q=${engine}+$q" ;;
esac
if (( $+commands[open] )); then open "$url"; elif (( $+commands[xdg-open] )); then xdg-open "$url"; else print -r -- "$url"; fi
}
alias google='web_search google'
alias ddg='web_search ddg'
alias bing='web_search bing'
# colored-man-pages (replaces omz plugin): colorize less for man
export LESS_TERMCAP_mb=$'\e[1;31m' LESS_TERMCAP_md=$'\e[1;36m' \
LESS_TERMCAP_me=$'\e[0m' LESS_TERMCAP_se=$'\e[0m' \
LESS_TERMCAP_so=$'\e[1;44;33m' LESS_TERMCAP_ue=$'\e[0m' LESS_TERMCAP_us=$'\e[1;32m'
# dirhistory (replaces omz plugin): Alt+Shift-Left/Right walk cd history, Alt+Shift-Up = ..
autoload -Uz add-zsh-hook
typeset -ga _dh_past _dh_future
_dh_push() { _dh_past+=("$PWD"); _dh_future=(); }
add-zsh-hook chpwd _dh_push
_dh_back() { (( ${#_dh_past} > 1 )) || return; _dh_future=("${_dh_past[-1]}" $_dh_future); _dh_past[-1]=(); builtin cd -q "${_dh_past[-1]}"; zle && zle reset-prompt; }
_dh_fwd() { (( ${#_dh_future} )) || return; builtin cd -q "${_dh_future[1]}"; _dh_past+=("${_dh_future[1]}"); _dh_future[1]=(); zle && zle reset-prompt; }
_dh_up() { builtin cd -q ..; zle && zle reset-prompt; }
zle -N _dh_back; zle -N _dh_fwd; zle -N _dh_up
bindkey '^[[1;4D' _dh_back # Alt+Shift-Left
bindkey '^[[1;4C' _dh_fwd # Alt+Shift-Right
bindkey '^[[1;4A' _dh_up # Alt+Shift-Up
# Alt-Left/Right = jump between words (macOS muscle memory; these sequences
# previously drove dirhistory, which shadowed word movement)
bindkey '^[[1;3D' backward-word # Alt-Left
bindkey '^[[1;3C' forward-word # Alt-Right
# sudo plugin (replaces omz `sudo`): press ESC twice to prefix the line with sudo
_sudo_esc() {
[[ -z $BUFFER ]] && LBUFFER="$(fc -ln -1)"
if [[ $BUFFER == sudo\ * ]]; then BUFFER="${BUFFER#sudo }"; else BUFFER="sudo $BUFFER"; fi
CURSOR=${#BUFFER}
}
zle -N _sudo_esc
bindkey '\e\e' _sudo_esc
# mkcd <dir> — make a directory and cd into it
mkcd() { mkdir -p -- "$1" && builtin cd -- "$1"; }
# tmux-htb [box] — launch the HTB pentest tmux session layout (shell/listeners/server/recon/docker)
tmux-htb() { "${ZDOTDIR:-$HOME/.dotfiles}/scripts/htb-layout.sh" "$@"; }