#!/usr/bin/env bash # 清理本项目 target/ 的构建缓存,释放磁盘空间。 # 逻辑对齐 seoh/clean-rust-targets.sh。 # # 两种模式: # 默认(安全清理,推荐):只删构建过程中产生的「死数据」,保留增量编译。 # · 被同 crate、同编译单元更新的元数据哈希所取代的产物 # —— fingerprint 里每个 (package, unit) 只保留最新哈希;旧哈希对应的 # deps 下 rlib/rmeta/.d/.o/可执行文件及 .fingerprint/*-/ 一并删除。 # 不影响当前配置的增量构建;若以后又编回旧 features/工具链,该单元会重编。 # · target/**/deps 下链接数为 1 的 *.rcgu.o # —— rustc 留在 deps 的中间产物;链接数 1 表示没有任何增量会话再引用, # cargo 的 fingerprint 也不追踪它(只记录 rlib/rmeta/bin)。 # 实测删除后 cargo build 仍全 Fresh,0 个 crate 重编。 # · incremental/-/ 下除最新会话之外的目录 # —— rustc 每次成功编译保留 2 个会话(当前 + 上一个),更早的以及中断 # 构建残留的 *-working 都不会再被读取。 # 保留:当前哈希的 rlib/rmeta/bin、fingerprint、最新 incremental 会话。 # # --full(全量清理):对本项目执行 cargo clean,target/ 整个清空。 # 只在需要彻底回收空间或修复损坏缓存时使用;下次构建全量重编,耗时可观。 # # 用法: # ./clean_rust_target.sh # 安全清理(交互确认) # ./clean_rust_target.sh --dry-run # 仅预览,不删除 # ./clean_rust_target.sh -y # 跳过确认 # ./clean_rust_target.sh --stale-days 30 # 额外丢弃 30 天未更新的增量会话 # ./clean_rust_target.sh --full # 全量清理(cargo clean) # # 说明: # - 安全清理覆盖 target/ 下所有 profile(debug、release、交叉 target)。 # - 所有 stat 用法为 macOS/BSD 语法(-f),Linux 上需改用 -c。 set -uo pipefail PROJECT_ROOT="$(cd "$(dirname "$0")" && pwd)" DRY_RUN=0 ASSUME_YES=0 FULL=0 STALE_DAYS=0 usage() { sed -n '3,33p' "$0" | sed 's/^# \{0,1\}//' } while [ $# -gt 0 ]; do case "$1" in -n | --dry-run) DRY_RUN=1 shift ;; -y | --yes) ASSUME_YES=1 shift ;; --full) FULL=1 shift ;; --stale-days) STALE_DAYS="${2:-0}" case "$STALE_DAYS" in '' | *[!0-9]*) echo "错误:--stale-days 需要正整数" >&2; exit 1 ;; esac shift 2 ;; -h | --help) usage exit 0 ;; *) echo "未知参数: $1" >&2 usage exit 1 ;; esac done human_kb() { awk -v kb="$1" 'BEGIN { if (kb >= 1048576) printf "%.1fG", kb / 1048576; else if (kb >= 1024) printf "%.0fM", kb / 1024; else printf "%dK", kb; }' } dir_kb() { du -sk "$1" 2>/dev/null | awk '{ print $1 }' } TOTAL_KB=0 # ---------------------------------------------------------------- 安全清理 # 元数据哈希:fingerprint / deps 文件名末尾的 16 位 hex。 is_metadata_hash() { case "$1" in [0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]) return 0 ;; *) return 1 ;; esac } # 批量取「链接数|大小|路径」,只挑链接数为 1 的 .o。 # 用 "|" 分隔,避免路径里的空格、中文导致切分错误。 collect_nlink1_objects() { local deps_dir="$1" out="$2" : >"$out" find "$deps_dir" -maxdepth 1 -type f -name '*.o' -print0 2>/dev/null | xargs -0 -n 500 stat -f '%l|%z|%N' 2>/dev/null | awk -F'|' '$1 == 1 { print $3 }' >>"$out" } delete_file_list() { local list="$1" count size_kb count=$(wc -l <"$list" | tr -d ' ') [ "$count" -eq 0 ] && return 0 size_kb=$(tr '\n' '\0' <"$list" | xargs -0 stat -f '%z' 2>/dev/null | awk '{ s += $1 } END { printf "%d", s / 1024 }') TOTAL_KB=$((TOTAL_KB + size_kb)) if [ "$DRY_RUN" -eq 0 ]; then tr '\n' '\0' <"$list" | xargs -0 rm -f fi } # 每个 (package, unit) 只保留 fingerprint 最新的元数据哈希; # 被取代的哈希:删 .fingerprint/*-/ 以及 deps 下所有带该哈希的产物。 # 无完整 unit 标记、且不属于任何 live 哈希的 fingerprint / deps 残留一并清除。 prune_stale_metadata_artifacts() { local profile_dir="$1" local fp_dir="$profile_dir/.fingerprint" local deps_dir="$profile_dir/deps" local records live_hashes all_hashes stale_hashes path_list local d base hash pkg mtime unit bn rel size_kb count [ -d "$fp_dir" ] || [ -d "$deps_dir" ] || return 0 records="$(mktemp)" live_hashes="$(mktemp)" all_hashes="$(mktemp)" stale_hashes="$(mktemp)" path_list="$(mktemp)" : >"$records" : >"$all_hashes" if [ -d "$fp_dir" ]; then for d in "$fp_dir"/*/; do [ -d "$d" ] || continue base=$(basename "${d%/}") hash="${base##*-}" is_metadata_hash "$hash" || continue pkg="${base%-*}" echo "$hash" >>"$all_hashes" if [ -f "$d/invoked.timestamp" ]; then mtime=$(stat -f '%m' "$d/invoked.timestamp") else mtime=$(stat -f '%m' "$d") fi for unit in "$d"*; do [ -f "$unit" ] || continue bn=$(basename "$unit") case "$bn" in *.json | dep-* | output-* | invoked.timestamp) continue ;; esac printf '%s|%s|%s\n' "$pkg/$bn" "$mtime" "$hash" >>"$records" done done fi if [ -d "$deps_dir" ]; then # 只从 rlib/rmeta 收候选哈希(数量少);.o 随其哈希一起删,不必全量 basename find "$deps_dir" -maxdepth 1 -type f \( -name 'lib*-*.rlib' -o -name 'lib*-*.rmeta' \) 2>/dev/null | sed -n 's/.*-\([0-9a-f]\{16\}\)\.\(rlib\|rmeta\)$/\1/p' >>"$all_hashes" fi sort -u "$all_hashes" -o "$all_hashes" if [ -s "$records" ]; then awk -F'|' ' { if (!($1 in best_m) || $2 + 0 > best_m[$1] + 0) { best_m[$1] = $2 best_h[$1] = $3 } } END { for (k in best_h) print best_h[k] } ' "$records" | sort -u >"$live_hashes" else : >"$live_hashes" fi comm -23 "$all_hashes" "$live_hashes" >"$stale_hashes" if [ ! -s "$stale_hashes" ]; then rm -f "$records" "$live_hashes" "$all_hashes" "$stale_hashes" "$path_list" return 0 fi : >"$path_list" o_list="$(mktemp)" : >"$o_list" if [ -d "$fp_dir" ]; then while IFS= read -r hash; do [ -n "$hash" ] || continue for d in "$fp_dir"/*-"$hash"; do [ -d "$d" ] || continue printf '%s\n' "$d" >>"$path_list" done done <"$stale_hashes" fi if [ -d "$deps_dir" ] && [ -s "$stale_hashes" ]; then # 单次扫 deps:非 .o 进 path_list(计价+删除),.o 进 o_list(删除;体积另行按 inode 去重粗算) find "$deps_dir" -maxdepth 1 -type f 2>/dev/null | awk -v stale="$stale_hashes" -v olst="$o_list" ' BEGIN { while ((getline h < stale) > 0) if (h != "") s[h] = 1 close(stale) } { base = $0 sub(/.*\//, "", base) if (match(base, /-[0-9a-f]{16}(\.|$)/)) { h = substr(base, RSTART + 1, 16) if (h in s) { if (base ~ /\.o$/) print $0 >> olst else print $0 } } } ' >>"$path_list" fi count=$(wc -l <"$stale_hashes" | tr -d ' ') o_count=$(wc -l <"$o_list" | tr -d ' ') size_kb=0 if [ -s "$path_list" ]; then size_kb=$(tr '\n' '\0' <"$path_list" | xargs -0 -n 300 stat -f '%i %z' 2>/dev/null | awk '!seen[$1]++ { s += $2 } END { printf "%d", s / 1024 }') fi if [ -s "$o_list" ]; then # .o 常有硬链,按 inode 去重;分批避免参数过长 o_kb=$(tr '\n' '\0' <"$o_list" | xargs -0 -n 300 stat -f '%i %z' 2>/dev/null | awk '!seen[$1]++ { s += $2 } END { printf "%d", s / 1024 }') size_kb=$((size_kb + o_kb)) fi TOTAL_KB=$((TOTAL_KB + size_kb)) rel="${profile_dir#$PROJECT_ROOT/}" if [ "$o_count" -gt 0 ]; then printf ' %-58s %6s (%s 个过期哈希, %s 个 .o)\n' "$rel" "$(human_kb "$size_kb")" "$count" "$o_count" else printf ' %-58s %6s (%s 个过期哈希)\n' "$rel" "$(human_kb "$size_kb")" "$count" fi if [ "$DRY_RUN" -eq 0 ]; then if [ -s "$path_list" ]; then dir_list="$(mktemp)" file_list="$(mktemp)" while IFS= read -r p; do [ -n "$p" ] || continue if [ -d "$p" ]; then printf '%s\n' "$p" >>"$dir_list" else printf '%s\n' "$p" >>"$file_list" fi done <"$path_list" if [ -s "$file_list" ]; then tr '\n' '\0' <"$file_list" | xargs -0 rm -f fi if [ -s "$dir_list" ]; then while IFS= read -r p; do rm -rf "$p" done <"$dir_list" fi rm -f "$dir_list" "$file_list" fi if [ -s "$o_list" ]; then tr '\n' '\0' <"$o_list" | xargs -0 rm -f fi fi rm -f "$records" "$live_hashes" "$all_hashes" "$stale_hashes" "$path_list" "$o_list" } # 每个 incremental/-/ 只保留最新会话。 # 若最新会话本身是中断残留(*-working),再额外保留最新的已提交会话, # 保证增量编译有可用的上一次状态。 # STALE_DAYS > 0 时,最新会话超过该天数未更新的目录整体丢弃。 prune_incremental_sessions() { local inc_dir="$1" local hash_dir session_list keep_session keep_committed s base lock_base newest mtime cutoff cutoff=0 if [ "$STALE_DAYS" -gt 0 ]; then cutoff=$(( $(date +%s) - STALE_DAYS * 86400 )) fi for hash_dir in "$inc_dir"/*/; do [ -d "$hash_dir" ] || continue hash_dir="${hash_dir%/}" session_list=$(find "$hash_dir" -maxdepth 1 -mindepth 1 -type d -name 's-*' -print0 2>/dev/null | xargs -0 -n 1 stat -f '%m|%N' 2>/dev/null | sort -rn) [ -z "$session_list" ] && continue newest=$(echo "$session_list" | head -1 | cut -d'|' -f1) keep_session=$(echo "$session_list" | head -1 | cut -d'|' -f2-) keep_committed="" if [ "$cutoff" -gt 0 ] && [ "$newest" -lt "$cutoff" ]; then keep_session="" # 最新会话也已过期:该 hash 目录整体丢弃 elif [ "${keep_session%-working}" != "$keep_session" ]; then keep_committed=$(echo "$session_list" | awk -F'|' '$2 !~ /-working$/ { print $2; exit }') fi while IFS='|' read -r mtime s; do [ -n "$s" ] || continue [ "$s" = "$keep_session" ] && continue [ -n "$keep_committed" ] && [ "$s" = "$keep_committed" ] && continue base=$(basename "$s") lock_base="${base%%-*}-$(echo "$base" | cut -d'-' -f2)" if [ "$DRY_RUN" -eq 1 ]; then TOTAL_KB=$((TOTAL_KB + $(dir_kb "$s"))) else rm -rf "$s" rm -f "$hash_dir/$lock_base.lock" fi done <<<"$session_list" done } run_safe_clean() { local target_dir="$PROJECT_ROOT/target" local profile inc deps count size_kb tmp_list before_kb after_kb if [ ! -d "$target_dir" ]; then echo "未发现 target/ 目录。" return 0 fi before_kb=$(dir_kb "$target_dir") echo "target/ 当前约 $(human_kb "$before_kb")" echo tmp_list="$(mktemp)" # 1) 先清被取代的元数据哈希(旧 rlib/rmeta/.o/fingerprint) for profile in "$target_dir"/* "$target_dir"/*/*; do [ -d "$profile" ] || continue if [ -d "$profile/.fingerprint" ] || [ -d "$profile/deps" ]; then prune_stale_metadata_artifacts "$profile" fi done # 2) 再裁掉过期的增量会话 for inc in "$target_dir"/*/incremental "$target_dir"/*/*/incremental; do [ -d "$inc" ] || continue before_inc=$(dir_kb "$inc") prune_incremental_sessions "$inc" if [ "$DRY_RUN" -eq 0 ]; then after_inc=$(dir_kb "$inc") freed=$((before_inc - after_inc)) if [ "$freed" -gt 0 ]; then printf ' %-58s %6s (旧 incremental session)\n' \ "${inc#$PROJECT_ROOT/}" "$(human_kb "$freed")" TOTAL_KB=$((TOTAL_KB + freed)) fi else # dry-run 时 prune_incremental_sessions 已把待删 session 体积累加进 TOTAL_KB : fi done # 3) 再删掉不再被任何会话引用的 .o(链接数 1) for deps in "$target_dir"/*/deps "$target_dir"/*/*/deps; do [ -d "$deps" ] || continue collect_nlink1_objects "$deps" "$tmp_list" count=$(wc -l <"$tmp_list" | tr -d ' ') if [ "$count" -gt 0 ]; then size_kb=$(tr '\n' '\0' <"$tmp_list" | xargs -0 stat -f '%z' 2>/dev/null | awk '{ s += $1 } END { printf "%d", s / 1024 }') printf ' %-58s %6s (%s 个 .o)\n' "${deps#$PROJECT_ROOT/}" "$(human_kb "$size_kb")" "$count" fi delete_file_list "$tmp_list" done rm -f "$tmp_list" if [ "$DRY_RUN" -eq 0 ] && [ -d "$target_dir" ]; then after_kb=$(dir_kb "$target_dir") echo echo "清理后 target/ 约 $(human_kb "$after_kb")(du 实测减少 $(human_kb "$((before_kb - after_kb))"))" fi } # ---------------------------------------------------------------- 全量清理 run_full_clean() { local target_dir="$PROJECT_ROOT/target" if ! command -v cargo >/dev/null 2>&1; then echo "错误: 未找到 cargo,请先安装 Rust 工具链。" >&2 return 1 fi if [ ! -d "$target_dir" ]; then echo "无 target/ 目录,无需清理。" return 0 fi TOTAL_KB=$(dir_kb "$target_dir") if [ "$DRY_RUN" -eq 1 ]; then printf ' %-42s %8s target/\n' "." "$(human_kb "$TOTAL_KB")" return 0 fi printf '清理 %s ... ' "$PROJECT_ROOT" if (cd "$PROJECT_ROOT" && cargo clean >/dev/null 2>&1); then echo "完成" return 0 fi echo "失败(cargo clean 未成功)" >&2 return 1 } # ---------------------------------------------------------------- 主流程 if [ "$FULL" -eq 1 ]; then echo "模式:全量清理(cargo clean,下次构建全量重编)" else echo "模式:安全清理(保留增量编译)$([ "$STALE_DAYS" -gt 0 ] && echo ",并丢弃 ${STALE_DAYS} 天未更新的增量会话")" fi if [ "$DRY_RUN" -eq 1 ]; then echo "[dry-run] 仅预览,不删除任何文件。" fi echo "项目根目录: $PROJECT_ROOT" echo if [ "$DRY_RUN" -eq 0 ] && [ "$ASSUME_YES" -ne 1 ]; then if [ "$FULL" -eq 1 ]; then read -r -p "确认执行全量清理(下次构建会全量重编)?[y/N] " answer else read -r -p "确认执行安全清理?[y/N] " answer fi case "$answer" in y | Y | yes | YES) ;; *) echo "已取消。" exit 0 ;; esac echo fi if [ "$FULL" -eq 1 ]; then run_full_clean rc=$? else run_safe_clean rc=$? fi echo echo "预计释放:约 $(human_kb "$TOTAL_KB")" echo "检查/清理完成(rc=${rc})。说明:实时已用量请自行 df -h 复核,du 统计与实际回收可能略有差异。" exit $rc