clean_rust_target.sh 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. #!/usr/bin/env bash
  2. # 清理本项目 target/ 的构建缓存,释放磁盘空间。
  3. # 逻辑对齐 seoh/clean-rust-targets.sh。
  4. #
  5. # 两种模式:
  6. # 默认(安全清理,推荐):只删构建过程中产生的「死数据」,保留增量编译。
  7. # · 被同 crate、同编译单元更新的元数据哈希所取代的产物
  8. # —— fingerprint 里每个 (package, unit) 只保留最新哈希;旧哈希对应的
  9. # deps 下 rlib/rmeta/.d/.o/可执行文件及 .fingerprint/*-<hash>/ 一并删除。
  10. # 不影响当前配置的增量构建;若以后又编回旧 features/工具链,该单元会重编。
  11. # · target/**/deps 下链接数为 1 的 *.rcgu.o
  12. # —— rustc 留在 deps 的中间产物;链接数 1 表示没有任何增量会话再引用,
  13. # cargo 的 fingerprint 也不追踪它(只记录 rlib/rmeta/bin)。
  14. # 实测删除后 cargo build 仍全 Fresh,0 个 crate 重编。
  15. # · incremental/<crate>-<hash>/ 下除最新会话之外的目录
  16. # —— rustc 每次成功编译保留 2 个会话(当前 + 上一个),更早的以及中断
  17. # 构建残留的 *-working 都不会再被读取。
  18. # 保留:当前哈希的 rlib/rmeta/bin、fingerprint、最新 incremental 会话。
  19. #
  20. # --full(全量清理):对本项目执行 cargo clean,target/ 整个清空。
  21. # 只在需要彻底回收空间或修复损坏缓存时使用;下次构建全量重编,耗时可观。
  22. #
  23. # 用法:
  24. # ./clean_rust_target.sh # 安全清理(交互确认)
  25. # ./clean_rust_target.sh --dry-run # 仅预览,不删除
  26. # ./clean_rust_target.sh -y # 跳过确认
  27. # ./clean_rust_target.sh --stale-days 30 # 额外丢弃 30 天未更新的增量会话
  28. # ./clean_rust_target.sh --full # 全量清理(cargo clean)
  29. #
  30. # 说明:
  31. # - 安全清理覆盖 target/ 下所有 profile(debug、release、交叉 target)。
  32. # - 所有 stat 用法为 macOS/BSD 语法(-f),Linux 上需改用 -c。
  33. set -uo pipefail
  34. PROJECT_ROOT="$(cd "$(dirname "$0")" && pwd)"
  35. DRY_RUN=0
  36. ASSUME_YES=0
  37. FULL=0
  38. STALE_DAYS=0
  39. usage() {
  40. sed -n '3,33p' "$0" | sed 's/^# \{0,1\}//'
  41. }
  42. while [ $# -gt 0 ]; do
  43. case "$1" in
  44. -n | --dry-run)
  45. DRY_RUN=1
  46. shift
  47. ;;
  48. -y | --yes)
  49. ASSUME_YES=1
  50. shift
  51. ;;
  52. --full)
  53. FULL=1
  54. shift
  55. ;;
  56. --stale-days)
  57. STALE_DAYS="${2:-0}"
  58. case "$STALE_DAYS" in
  59. '' | *[!0-9]*) echo "错误:--stale-days 需要正整数" >&2; exit 1 ;;
  60. esac
  61. shift 2
  62. ;;
  63. -h | --help)
  64. usage
  65. exit 0
  66. ;;
  67. *)
  68. echo "未知参数: $1" >&2
  69. usage
  70. exit 1
  71. ;;
  72. esac
  73. done
  74. human_kb() {
  75. awk -v kb="$1" 'BEGIN {
  76. if (kb >= 1048576) printf "%.1fG", kb / 1048576;
  77. else if (kb >= 1024) printf "%.0fM", kb / 1024;
  78. else printf "%dK", kb;
  79. }'
  80. }
  81. dir_kb() {
  82. du -sk "$1" 2>/dev/null | awk '{ print $1 }'
  83. }
  84. TOTAL_KB=0
  85. # ---------------------------------------------------------------- 安全清理
  86. # 元数据哈希:fingerprint / deps 文件名末尾的 16 位 hex。
  87. is_metadata_hash() {
  88. case "$1" in
  89. [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 ;;
  90. *) return 1 ;;
  91. esac
  92. }
  93. # 批量取「链接数|大小|路径」,只挑链接数为 1 的 .o。
  94. # 用 "|" 分隔,避免路径里的空格、中文导致切分错误。
  95. collect_nlink1_objects() {
  96. local deps_dir="$1" out="$2"
  97. : >"$out"
  98. find "$deps_dir" -maxdepth 1 -type f -name '*.o' -print0 2>/dev/null |
  99. xargs -0 -n 500 stat -f '%l|%z|%N' 2>/dev/null |
  100. awk -F'|' '$1 == 1 { print $3 }' >>"$out"
  101. }
  102. delete_file_list() {
  103. local list="$1" count size_kb
  104. count=$(wc -l <"$list" | tr -d ' ')
  105. [ "$count" -eq 0 ] && return 0
  106. size_kb=$(tr '\n' '\0' <"$list" | xargs -0 stat -f '%z' 2>/dev/null |
  107. awk '{ s += $1 } END { printf "%d", s / 1024 }')
  108. TOTAL_KB=$((TOTAL_KB + size_kb))
  109. if [ "$DRY_RUN" -eq 0 ]; then
  110. tr '\n' '\0' <"$list" | xargs -0 rm -f
  111. fi
  112. }
  113. # 每个 (package, unit) 只保留 fingerprint 最新的元数据哈希;
  114. # 被取代的哈希:删 .fingerprint/*-<hash>/ 以及 deps 下所有带该哈希的产物。
  115. # 无完整 unit 标记、且不属于任何 live 哈希的 fingerprint / deps 残留一并清除。
  116. prune_stale_metadata_artifacts() {
  117. local profile_dir="$1"
  118. local fp_dir="$profile_dir/.fingerprint"
  119. local deps_dir="$profile_dir/deps"
  120. local records live_hashes all_hashes stale_hashes path_list
  121. local d base hash pkg mtime unit bn rel size_kb count
  122. [ -d "$fp_dir" ] || [ -d "$deps_dir" ] || return 0
  123. records="$(mktemp)"
  124. live_hashes="$(mktemp)"
  125. all_hashes="$(mktemp)"
  126. stale_hashes="$(mktemp)"
  127. path_list="$(mktemp)"
  128. : >"$records"
  129. : >"$all_hashes"
  130. if [ -d "$fp_dir" ]; then
  131. for d in "$fp_dir"/*/; do
  132. [ -d "$d" ] || continue
  133. base=$(basename "${d%/}")
  134. hash="${base##*-}"
  135. is_metadata_hash "$hash" || continue
  136. pkg="${base%-*}"
  137. echo "$hash" >>"$all_hashes"
  138. if [ -f "$d/invoked.timestamp" ]; then
  139. mtime=$(stat -f '%m' "$d/invoked.timestamp")
  140. else
  141. mtime=$(stat -f '%m' "$d")
  142. fi
  143. for unit in "$d"*; do
  144. [ -f "$unit" ] || continue
  145. bn=$(basename "$unit")
  146. case "$bn" in
  147. *.json | dep-* | output-* | invoked.timestamp) continue ;;
  148. esac
  149. printf '%s|%s|%s\n' "$pkg/$bn" "$mtime" "$hash" >>"$records"
  150. done
  151. done
  152. fi
  153. if [ -d "$deps_dir" ]; then
  154. # 只从 rlib/rmeta 收候选哈希(数量少);.o 随其哈希一起删,不必全量 basename
  155. find "$deps_dir" -maxdepth 1 -type f \( -name 'lib*-*.rlib' -o -name 'lib*-*.rmeta' \) 2>/dev/null |
  156. sed -n 's/.*-\([0-9a-f]\{16\}\)\.\(rlib\|rmeta\)$/\1/p' >>"$all_hashes"
  157. fi
  158. sort -u "$all_hashes" -o "$all_hashes"
  159. if [ -s "$records" ]; then
  160. awk -F'|' '
  161. {
  162. if (!($1 in best_m) || $2 + 0 > best_m[$1] + 0) {
  163. best_m[$1] = $2
  164. best_h[$1] = $3
  165. }
  166. }
  167. END { for (k in best_h) print best_h[k] }
  168. ' "$records" | sort -u >"$live_hashes"
  169. else
  170. : >"$live_hashes"
  171. fi
  172. comm -23 "$all_hashes" "$live_hashes" >"$stale_hashes"
  173. if [ ! -s "$stale_hashes" ]; then
  174. rm -f "$records" "$live_hashes" "$all_hashes" "$stale_hashes" "$path_list"
  175. return 0
  176. fi
  177. : >"$path_list"
  178. o_list="$(mktemp)"
  179. : >"$o_list"
  180. if [ -d "$fp_dir" ]; then
  181. while IFS= read -r hash; do
  182. [ -n "$hash" ] || continue
  183. for d in "$fp_dir"/*-"$hash"; do
  184. [ -d "$d" ] || continue
  185. printf '%s\n' "$d" >>"$path_list"
  186. done
  187. done <"$stale_hashes"
  188. fi
  189. if [ -d "$deps_dir" ] && [ -s "$stale_hashes" ]; then
  190. # 单次扫 deps:非 .o 进 path_list(计价+删除),.o 进 o_list(删除;体积另行按 inode 去重粗算)
  191. find "$deps_dir" -maxdepth 1 -type f 2>/dev/null |
  192. awk -v stale="$stale_hashes" -v olst="$o_list" '
  193. BEGIN {
  194. while ((getline h < stale) > 0) if (h != "") s[h] = 1
  195. close(stale)
  196. }
  197. {
  198. base = $0
  199. sub(/.*\//, "", base)
  200. if (match(base, /-[0-9a-f]{16}(\.|$)/)) {
  201. h = substr(base, RSTART + 1, 16)
  202. if (h in s) {
  203. if (base ~ /\.o$/) print $0 >> olst
  204. else print $0
  205. }
  206. }
  207. }
  208. ' >>"$path_list"
  209. fi
  210. count=$(wc -l <"$stale_hashes" | tr -d ' ')
  211. o_count=$(wc -l <"$o_list" | tr -d ' ')
  212. size_kb=0
  213. if [ -s "$path_list" ]; then
  214. size_kb=$(tr '\n' '\0' <"$path_list" | xargs -0 -n 300 stat -f '%i %z' 2>/dev/null |
  215. awk '!seen[$1]++ { s += $2 } END { printf "%d", s / 1024 }')
  216. fi
  217. if [ -s "$o_list" ]; then
  218. # .o 常有硬链,按 inode 去重;分批避免参数过长
  219. o_kb=$(tr '\n' '\0' <"$o_list" | xargs -0 -n 300 stat -f '%i %z' 2>/dev/null |
  220. awk '!seen[$1]++ { s += $2 } END { printf "%d", s / 1024 }')
  221. size_kb=$((size_kb + o_kb))
  222. fi
  223. TOTAL_KB=$((TOTAL_KB + size_kb))
  224. rel="${profile_dir#$PROJECT_ROOT/}"
  225. if [ "$o_count" -gt 0 ]; then
  226. printf ' %-58s %6s (%s 个过期哈希, %s 个 .o)\n' "$rel" "$(human_kb "$size_kb")" "$count" "$o_count"
  227. else
  228. printf ' %-58s %6s (%s 个过期哈希)\n' "$rel" "$(human_kb "$size_kb")" "$count"
  229. fi
  230. if [ "$DRY_RUN" -eq 0 ]; then
  231. if [ -s "$path_list" ]; then
  232. dir_list="$(mktemp)"
  233. file_list="$(mktemp)"
  234. while IFS= read -r p; do
  235. [ -n "$p" ] || continue
  236. if [ -d "$p" ]; then
  237. printf '%s\n' "$p" >>"$dir_list"
  238. else
  239. printf '%s\n' "$p" >>"$file_list"
  240. fi
  241. done <"$path_list"
  242. if [ -s "$file_list" ]; then
  243. tr '\n' '\0' <"$file_list" | xargs -0 rm -f
  244. fi
  245. if [ -s "$dir_list" ]; then
  246. while IFS= read -r p; do
  247. rm -rf "$p"
  248. done <"$dir_list"
  249. fi
  250. rm -f "$dir_list" "$file_list"
  251. fi
  252. if [ -s "$o_list" ]; then
  253. tr '\n' '\0' <"$o_list" | xargs -0 rm -f
  254. fi
  255. fi
  256. rm -f "$records" "$live_hashes" "$all_hashes" "$stale_hashes" "$path_list" "$o_list"
  257. }
  258. # 每个 incremental/<crate>-<hash>/ 只保留最新会话。
  259. # 若最新会话本身是中断残留(*-working),再额外保留最新的已提交会话,
  260. # 保证增量编译有可用的上一次状态。
  261. # STALE_DAYS > 0 时,最新会话超过该天数未更新的目录整体丢弃。
  262. prune_incremental_sessions() {
  263. local inc_dir="$1"
  264. local hash_dir session_list keep_session keep_committed s base lock_base newest mtime cutoff
  265. cutoff=0
  266. if [ "$STALE_DAYS" -gt 0 ]; then
  267. cutoff=$(( $(date +%s) - STALE_DAYS * 86400 ))
  268. fi
  269. for hash_dir in "$inc_dir"/*/; do
  270. [ -d "$hash_dir" ] || continue
  271. hash_dir="${hash_dir%/}"
  272. session_list=$(find "$hash_dir" -maxdepth 1 -mindepth 1 -type d -name 's-*' -print0 2>/dev/null |
  273. xargs -0 -n 1 stat -f '%m|%N' 2>/dev/null | sort -rn)
  274. [ -z "$session_list" ] && continue
  275. newest=$(echo "$session_list" | head -1 | cut -d'|' -f1)
  276. keep_session=$(echo "$session_list" | head -1 | cut -d'|' -f2-)
  277. keep_committed=""
  278. if [ "$cutoff" -gt 0 ] && [ "$newest" -lt "$cutoff" ]; then
  279. keep_session="" # 最新会话也已过期:该 hash 目录整体丢弃
  280. elif [ "${keep_session%-working}" != "$keep_session" ]; then
  281. keep_committed=$(echo "$session_list" | awk -F'|' '$2 !~ /-working$/ { print $2; exit }')
  282. fi
  283. while IFS='|' read -r mtime s; do
  284. [ -n "$s" ] || continue
  285. [ "$s" = "$keep_session" ] && continue
  286. [ -n "$keep_committed" ] && [ "$s" = "$keep_committed" ] && continue
  287. base=$(basename "$s")
  288. lock_base="${base%%-*}-$(echo "$base" | cut -d'-' -f2)"
  289. if [ "$DRY_RUN" -eq 1 ]; then
  290. TOTAL_KB=$((TOTAL_KB + $(dir_kb "$s")))
  291. else
  292. rm -rf "$s"
  293. rm -f "$hash_dir/$lock_base.lock"
  294. fi
  295. done <<<"$session_list"
  296. done
  297. }
  298. run_safe_clean() {
  299. local target_dir="$PROJECT_ROOT/target"
  300. local profile inc deps count size_kb tmp_list before_kb after_kb
  301. if [ ! -d "$target_dir" ]; then
  302. echo "未发现 target/ 目录。"
  303. return 0
  304. fi
  305. before_kb=$(dir_kb "$target_dir")
  306. echo "target/ 当前约 $(human_kb "$before_kb")"
  307. echo
  308. tmp_list="$(mktemp)"
  309. # 1) 先清被取代的元数据哈希(旧 rlib/rmeta/.o/fingerprint)
  310. for profile in "$target_dir"/* "$target_dir"/*/*; do
  311. [ -d "$profile" ] || continue
  312. if [ -d "$profile/.fingerprint" ] || [ -d "$profile/deps" ]; then
  313. prune_stale_metadata_artifacts "$profile"
  314. fi
  315. done
  316. # 2) 再裁掉过期的增量会话
  317. for inc in "$target_dir"/*/incremental "$target_dir"/*/*/incremental; do
  318. [ -d "$inc" ] || continue
  319. before_inc=$(dir_kb "$inc")
  320. prune_incremental_sessions "$inc"
  321. if [ "$DRY_RUN" -eq 0 ]; then
  322. after_inc=$(dir_kb "$inc")
  323. freed=$((before_inc - after_inc))
  324. if [ "$freed" -gt 0 ]; then
  325. printf ' %-58s %6s (旧 incremental session)\n' \
  326. "${inc#$PROJECT_ROOT/}" "$(human_kb "$freed")"
  327. TOTAL_KB=$((TOTAL_KB + freed))
  328. fi
  329. else
  330. # dry-run 时 prune_incremental_sessions 已把待删 session 体积累加进 TOTAL_KB
  331. :
  332. fi
  333. done
  334. # 3) 再删掉不再被任何会话引用的 .o(链接数 1)
  335. for deps in "$target_dir"/*/deps "$target_dir"/*/*/deps; do
  336. [ -d "$deps" ] || continue
  337. collect_nlink1_objects "$deps" "$tmp_list"
  338. count=$(wc -l <"$tmp_list" | tr -d ' ')
  339. if [ "$count" -gt 0 ]; then
  340. size_kb=$(tr '\n' '\0' <"$tmp_list" | xargs -0 stat -f '%z' 2>/dev/null |
  341. awk '{ s += $1 } END { printf "%d", s / 1024 }')
  342. printf ' %-58s %6s (%s 个 .o)\n' "${deps#$PROJECT_ROOT/}" "$(human_kb "$size_kb")" "$count"
  343. fi
  344. delete_file_list "$tmp_list"
  345. done
  346. rm -f "$tmp_list"
  347. if [ "$DRY_RUN" -eq 0 ] && [ -d "$target_dir" ]; then
  348. after_kb=$(dir_kb "$target_dir")
  349. echo
  350. echo "清理后 target/ 约 $(human_kb "$after_kb")(du 实测减少 $(human_kb "$((before_kb - after_kb))"))"
  351. fi
  352. }
  353. # ---------------------------------------------------------------- 全量清理
  354. run_full_clean() {
  355. local target_dir="$PROJECT_ROOT/target"
  356. if ! command -v cargo >/dev/null 2>&1; then
  357. echo "错误: 未找到 cargo,请先安装 Rust 工具链。" >&2
  358. return 1
  359. fi
  360. if [ ! -d "$target_dir" ]; then
  361. echo "无 target/ 目录,无需清理。"
  362. return 0
  363. fi
  364. TOTAL_KB=$(dir_kb "$target_dir")
  365. if [ "$DRY_RUN" -eq 1 ]; then
  366. printf ' %-42s %8s target/\n' "." "$(human_kb "$TOTAL_KB")"
  367. return 0
  368. fi
  369. printf '清理 %s ... ' "$PROJECT_ROOT"
  370. if (cd "$PROJECT_ROOT" && cargo clean >/dev/null 2>&1); then
  371. echo "完成"
  372. return 0
  373. fi
  374. echo "失败(cargo clean 未成功)" >&2
  375. return 1
  376. }
  377. # ---------------------------------------------------------------- 主流程
  378. if [ "$FULL" -eq 1 ]; then
  379. echo "模式:全量清理(cargo clean,下次构建全量重编)"
  380. else
  381. echo "模式:安全清理(保留增量编译)$([ "$STALE_DAYS" -gt 0 ] && echo ",并丢弃 ${STALE_DAYS} 天未更新的增量会话")"
  382. fi
  383. if [ "$DRY_RUN" -eq 1 ]; then
  384. echo "[dry-run] 仅预览,不删除任何文件。"
  385. fi
  386. echo "项目根目录: $PROJECT_ROOT"
  387. echo
  388. if [ "$DRY_RUN" -eq 0 ] && [ "$ASSUME_YES" -ne 1 ]; then
  389. if [ "$FULL" -eq 1 ]; then
  390. read -r -p "确认执行全量清理(下次构建会全量重编)?[y/N] " answer
  391. else
  392. read -r -p "确认执行安全清理?[y/N] " answer
  393. fi
  394. case "$answer" in
  395. y | Y | yes | YES) ;;
  396. *)
  397. echo "已取消。"
  398. exit 0
  399. ;;
  400. esac
  401. echo
  402. fi
  403. if [ "$FULL" -eq 1 ]; then
  404. run_full_clean
  405. rc=$?
  406. else
  407. run_safe_clean
  408. rc=$?
  409. fi
  410. echo
  411. echo "预计释放:约 $(human_kb "$TOTAL_KB")"
  412. echo "检查/清理完成(rc=${rc})。说明:实时已用量请自行 df -h 复核,du 统计与实际回收可能略有差异。"
  413. exit $rc