tool-moyu.sh 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. #!/bin/bash
  2. # =============================================================
  3. # tool-moyu.sh — AI「摸鱼」模拟器
  4. #
  5. # 作用:读取一段内容(默认本会话日志,或任意文件/stdin),
  6. # 循环「假装在处理」,模拟 AI 工作的样子。
  7. # 适合:需要看起来在干活、又不想真干活的时候 😏
  8. #
  9. # 用法:
  10. # ./tool-moyu.sh # 用内置内容摸鱼(默认)
  11. # ./tool-moyu.sh -n 3 # 循环 3 遍
  12. # ./tool-moyu.sh [文件] # 从文件读取(覆盖内置内容)
  13. # ./tool-moyu.sh --help # 帮助
  14. #
  15. # 选项:
  16. # -n N 循环 N 次(默认无限)
  17. # -d MS 每行间隔毫秒(默认随机 80-400)
  18. # -t 逐个字符「打字」效果
  19. # -s 静默模式:不打印假状态行,只循环内容
  20. # -c PCT 命中行的实际上色概率(0-100, 默认 50)
  21. # =============================================================
  22. set -euo pipefail
  23. LOOP_TIMES=0 # 0 = 无限
  24. DELAY_MS=0 # 0 = 随机 80-400
  25. TYPE_EFFECT=0
  26. SILENT=0
  27. COLOR_RATIO=50 # 0-100, 命中语义的行的实际上色概率(降彩色密度)
  28. EXPLICIT_COLOR=0 # 显式传 -c 时置 1, 视为显式彩色意图
  29. show_usage() {
  30. sed -n '1,24p' "$0"
  31. exit 0
  32. }
  33. while [ $# -gt 0 ]; do
  34. case "$1" in
  35. -n)
  36. LOOP_TIMES="${2:?}"
  37. shift 2
  38. ;;
  39. -d)
  40. DELAY_MS="${2:?}"
  41. shift 2
  42. ;;
  43. -t)
  44. TYPE_EFFECT=1
  45. shift
  46. ;;
  47. -s)
  48. SILENT=1
  49. shift
  50. ;;
  51. -c | --color-ratio)
  52. COLOR_RATIO="${2:?}"
  53. case "$COLOR_RATIO" in *[!0-9]*)
  54. echo "Invalid color ratio: $COLOR_RATIO (expect 0-100)" >&2
  55. exit 1
  56. ;;
  57. esac
  58. [ "$COLOR_RATIO" -gt 100 ] && {
  59. echo "color ratio must be 0-100" >&2
  60. exit 1
  61. }
  62. EXPLICIT_COLOR=1
  63. shift 2
  64. ;;
  65. --help | -h) show_usage ;;
  66. -*)
  67. echo "Unknown option: $1" >&2
  68. exit 1
  69. ;;
  70. *) break ;;
  71. esac
  72. done
  73. # ---- 颜色自动检测:TTY / FORCE_COLOR=1 / 显式传 -c 才上色;NO_COLOR 显式禁用 ----
  74. # 文件模式不上色(见 run_once),此处仅决定随机内容是否套用 ANSI 主题色
  75. # 默认值(50)不触发强制, 仅显式传 -c 视为用户想要彩色(即使非 TTY)
  76. COLOR=0
  77. if [ -z "${NO_COLOR-}" ] && { [ "${FORCE_COLOR:-0}" = "1" ] || [ -t 1 ] || [ "$EXPLICIT_COLOR" = "1" ]; }; then
  78. COLOR=1
  79. fi
  80. # ---- 命令与对应输出(成对,命令后紧跟其输出更真实) ----
  81. COMMANDS=(
  82. "go vet ./..."
  83. "go test ./..."
  84. "CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o admin_server ./cmd/server"
  85. "pnpm typecheck"
  86. "pnpm build"
  87. "rsync -az --delete release/frontend/ root@18.220.34.224:/www/wwwroot/household/"
  88. "ssh -p 10022 root@18.220.34.224 'systemctl restart backend-admin'"
  89. "mysql -h127.0.0.1 -uhousehold -p**** household -e 'SHOW TABLES;'"
  90. "curl -s -o /dev/null -w 'HTTP %{http_code}\\n' http://127.0.0.1:8081/"
  91. "journalctl -u backend-admin -n 30 --no-pager"
  92. "systemctl status backend-app"
  93. "git log --oneline -5"
  94. "go run ./cmd/migrate up"
  95. "pnpm lint"
  96. "pnpm test:unit"
  97. "docker compose ps"
  98. "redis-cli -h 127.0.0.1 INFO memory"
  99. "journalctl -u backend-app --since '10 min ago' --no-pager"
  100. "ssh -p 10022 root@18.220.34.224 'nginx -t'"
  101. "curl -s https://admin.household.ooo.ink/api/v1/health"
  102. "go test -race ./internal/pkg/notify/..."
  103. "git pull --rebase origin master"
  104. "git diff --stat"
  105. "docker exec household-mysql mysql -e 'SELECT COUNT(*) FROM center_orders'"
  106. "go build ./cmd/app"
  107. "go vet ./internal/pkg/..."
  108. "pnpm install --frozen-lockfile"
  109. "pnpm run typecheck:ci"
  110. "git status --short"
  111. "git stash && git pull && git stash pop"
  112. "mysql -h127.0.0.1 -uhousehold -p**** household -e 'OPTIMIZE TABLE center_orders'"
  113. "curl -s -o /dev/null -w '%{time_total}' http://127.0.0.1:8081/api/v1/orders/123"
  114. "go tool pprof -top /tmp/cpu.prof"
  115. "git tag v1.9.2 && git push origin v1.9.2"
  116. "redis-cli -n 3 dbsize"
  117. "journalctl -u backend-admin --since today --no-pager | grep -i error"
  118. )
  119. COMMAND_OUT=(
  120. "ok 0.231s"
  121. "ok git.ooo.ink/household/app 0.532s"
  122. "[build] release/backend/admin/admin_server (ELF, linux/amd64)"
  123. "no type errors found"
  124. "✓ built in 26.39s"
  125. "sent 2.4MB, 1.1MB/s"
  126. "systemd[1]: Started backend-admin.service - Household Backend Admin."
  127. "Tables: center_admins center_menus center_roles ... (19 total)"
  128. "HTTP 200"
  129. "[GIN-debug] Listening and serving HTTP on :8081"
  130. "Active: active (running)"
  131. "f37eec3 docs(deploy): align backend directory with actual test-machine paths"
  132. "migrate: applied 1 change (20260829003_create_notify_logs) in 312ms · dirty=0"
  133. "✔ No ESLint errors (148 files, 3.1s)"
  134. "Test Files: 6 passed | 48 tests (68.4s) ✓"
  135. "CONTAINER STATUS: mysql(Up) redis(Up) backend-app(Up 3 days) · 4/4 healthy"
  136. "used_memory_human:1.2G · peak 1.4G · maxmemory_policy:noeviction · keys 12840"
  137. "no new entries · last log 12 min ago, no warnings, no OOM"
  138. "nginx: configuration file /etc/nginx/nginx.conf test is successful"
  139. '{"status":"ok","version":"v1.9.2","db":"up","redis":"up"}'
  140. "ok git.ooo.ink/household/app/internal/pkg/notify 3.812s · race detected 0"
  141. "Updating 8f3a2d1..c1e9b77 · 2 files changed, 41 insertions(+), 3 deletions(-)"
  142. "internal/router/route.go +3 · internal/pkg/notify/notify.go +96 · 2 files changed"
  143. "COUNT(*) = 128420 · +312 today, no archive lag"
  144. "ok git.ooo.ink/household/app 0.18s"
  145. "ok 0.421s"
  146. "pnpm: All dependencies are up to date (resolved in 6.2s)"
  147. "✓ 214 files checked, no type errors"
  148. " M internal/pkg/notify/notify.go · ?? docs/api/notify.md"
  149. "Auto-merging internal/pkg/notify/notify.go · stash applied, 1 conflict auto-resolved"
  150. "Table optimized · freed 118MB · fragmentation 0%"
  151. "0.184s"
  152. "concatstrings 12% · encoding/json.Encode 8% · runtime.mallocgc 6% · (42 nodes)"
  153. "* [new tag] v1.9.2 -> v1.9.2"
  154. "12840"
  155. "0 matches · clean today"
  156. )
  157. # ---- Standalone lines (tool returns / logs / a few AI actions) ----
  158. STANDALONE=(
  159. "[read] docs/deploy-aaPanel.md 168 lines (2.1 kB, 14 sections, 3 code blocks) · reviewed the Nginx config and systemd service sections, ready to follow the manual"
  160. "[read] internal/pkg/database/run_migrations.go 87 lines → located the RunMigrations entry · confirmed FIFO order + idempotent dedup, auto-rollback on failure"
  161. "[search] migrations → 3 results (run_migrations.go, migrate.go, main.go) · all are startup migration paths, no duplicate registration"
  162. "[search] CenterAdmin → 14 results · hit in admin routes/service/handler, test files excluded to avoid noise"
  163. "[trace] RunMigrations → cmd/server/main.go:41 ← internal/pkg/database.RunMigrations · called once from main only, no bypass path"
  164. "[trace] ParseToken → 6 callers: auth middleware ×1, ws handler ×2, cron ×3 · every call chain verified, no cyclic dependencies"
  165. "[snippet] buildDSN → user:pass@tcp(host:port)/db?parseTime=True&charset=utf8mb4 · reads DB_HOST/DB_PORT/DB_USER/DB_PASS from viper config"
  166. "[snippet] handleList → offset defaults to 0, limit caps at 100 with silent truncation · returns {total, items}, pagination contract for the frontend"
  167. "[grep] rabbitmq in docker-compose/dev.yml → 0 matches, dependency absent · queue-based notifications must degrade to synchronous calls"
  168. "[edit] internal/router/route.go +1 -2 → registered notify route under /api/v1 group · swagger annotations updated, takes effect after restart"
  169. "[write] internal/pkg/notify/notify.go 96 lines → new email/SMS notification wrapper with retry · 3s timeout, 2 retries, failures written to dead-letter table"
  170. "[deploy] backend-admin → active (running) · pid 1823 · 48MB RSS · managed by systemd, enabled on boot, listening on port 8081"
  171. "[deploy] frontend-admin → HTTP 200 · dist/assets/index-*.js uploaded · Nginx cache purged, all static assets now serve the new build"
  172. "[check] SSH root@18.220.34.224:10022 → ok (handshake 0.42s, key auth passed) · passwordless channel healthy, follow-up commands can run directly"
  173. "[verify] curl admin.household.ooo.ink → 200 OK (TTFB 86ms, no 5xx) · homepage returns full HTML, every static asset is 200"
  174. "[verify] mysql SHOW TABLES → 19 tables · 312MB total · covers center/tenant/order core groups, no orphaned tables"
  175. "[verify] redis ping → PONG · 1.2GB/4GB in use · 92% hit ratio, all keys carry business prefix, no collisions"
  176. "[skip] migration 20260829002 already applied · dirty=0, nothing to re-run · this release ships no new migration scripts"
  177. "[skip] no changes, up to date · working tree clean, nothing pending · fully in sync with origin/master, no push required"
  178. "[warn] config.yaml placeholder secret left as-is · must be replaced in production · prefer env-var injection over hardcoding"
  179. "[warn] TLS cert expires in 12 days, renew soon · Let's Encrypt auto-renew cron confirmed running"
  180. "[warn] pkg/notify has 3 leftover TODOs: email templates not i18n'ed · JA/CN templates to be added next iteration"
  181. "[err] rate limit exceeded, auto-retry in 1.8s... · 2nd retry succeeded, request replayed"
  182. "ready for connections. socket: '/var/run/mysqld/mysqld.sock' port: 3306 · MySQL 8.4 up, version compatibility check passed"
  183. "schema_migrations: 20260828001 | dirty=0 · last migration 2026-08-28 10:02:34 · 47 entries in history, no conflicts"
  184. "dist/assets/index-*.js 95.77 kB │ gzip: 37.38 kB │ 8 chunks · 12.4% smaller than previous build, tree-shaking effective"
  185. "vite v7.3.6 building client environment for production... 26.39s ✓ · output 4.2MB, zero warnings, dist.zip produced"
  186. "GET /api/v1/orders 200 4.2ms · source: center db, Redis cache hit · no DB touch, no new entries in slow-query log"
  187. "POST /api/v1/orders 201 12.8ms · triggered worker assignment + notification push · status transition normal, transaction committed"
  188. "center_admins: 6 rows returned in 1ms (SELECT id, name, role_ids FROM center_admins) · PRIMARY index used, no full scan"
  189. "db 15/16 used, 1 left · one idle pool reserved · leak detection clean, avg idle 3.2s"
  190. "service worker: 34 active jobs today, avg response 2.1s · spread across Tokyo/Osaka/Fukuoka, no timeouts"
  191. "🤖 analyzing dependency graph... 1284 symbols, 8 clusters, 2 cyclic deps · flagged for decoupling, no impact on this change"
  192. "📊 summarizing key decisions... 4 items: routing/caching/payments/compliance · synced to project ADR for later review"
  193. "✍️ drafting implementation plan... 5 steps, ~40 min · migration/route/service/test/docs, each with acceptance criteria"
  194. "✅ implementation plan approved · no blockers · passed 2 reviewers, all risks low/medium, execution started"
  195. "📐 aligning with existing architecture (ARCHITECTURE.md §3 layering) · new module follows cmd→internal→shared one-way dependency"
  196. "🏗️ scaffolding new module: internal/pkg/notify (service/repository/template) · directory layout matches the skeleton conventions"
  197. "🧩 wiring DI container... injected logger + db + redis deps · constructor signatures updated, compiles clean"
  198. "🧪 writing unit tests for RunMigrations · 3 cases: success/duplicate/failed-rollback · covers edges, 87% coverage"
  199. "⚙️ running gofmt -l + go vet ./... → 0 format issues, 0 vet warnings · no unrelated files reformatted"
  200. "📦 bumping go.mod dependency: gin v1.10.0 → v1.11.0 (CVE-2026-0113 fix) · go.sum synced, compile regression-free"
  201. "📝 updating API docs (docs/api/notify.md) · added 2 endpoint specs · req/resp examples + error codes, linked from README"
  202. "🧠 loading knowledge graph index (codebase-memory)... 12s · covers 3 sub-repos, last indexed 5 min ago"
  203. "🔎 querying codebase graph for CenterAdmin handlers → 6 nodes expanded · located create/update/delete/query ops"
  204. "🚦 checking index coverage: project/backend/admin → 100% covered, no gaps · unindexed historical branches excluded"
  205. "👣 tracing callers of ParseToken → all 6 refs verified · each carries auth context, no privilege-escalation calls"
  206. "🧬 detecting git diff impact (blast radius) → touches router + 2 handlers · 4 related tests run and green"
  207. "🗃️ index refreshed: 1284 symbols, 8 clusters, 312 files, 0 stale · +23 symbols, −5, topology acyclic"
  208. "[test] TestParseToken → PASS (0.112s, 4/4 asserts) · covers expired/tampered/malformed/valid tokens"
  209. "[test] TestBuildDSN → PASS (0.031s, 5/5 asserts, empty-password edge) · includes fallback when host:port has no default"
  210. "[bench] BenchmarkList → 1.2µs/op, 812 allocs/op, 0 B/op leaked · 18% faster than baseline, acceptable"
  211. "[lint] staticcheck ./... → no issues reported · last run 10 min ago · full golangci-lint suite also green"
  212. "[git] status → clean (working tree) · no untracked files · 3 commits staged, awaiting push"
  213. "[git] log --oneline -3 → 3 commits behind origin, need pull · upstream added config refactor + dependency bumps"
  214. "Redis: 127.0.0.1:6379 connected · maxclients 10000 · 15/16 dbs used · AOF persistence on, no blocking commands"
  215. "[build] docker build -t registry.git.ooo.ink/household/backend:1.9.2 . → 2 layers cached, image 187MB pushed in 4.8s"
  216. "[build] pnpm build:admin → 4.2MB dist, tree-shook lodash-es, gzip 1.1MB · zero warnings"
  217. "[lint] gofmt -l → 0 files · consistent with .editorconfig"
  218. "[test] go test ./... → ok (7 packages) · 2.8s, 0 skipped, no race"
  219. "[bench] BenchmarkHandleList → 420ns/op, 3 allocs/op · inlined hot path, 30% faster"
  220. "[migrate] 20260829002_orders_partition OK · down migration present, reversible"
  221. "[db] ANALYZE TABLE center_orders → 128k rows · cardinality updated, planner now uses orders_idx_created"
  222. "[redis] SCAN 'order:*' → 12 keys · all with TTL < 24h, none expired-but-resident"
  223. "[nginx] reloaded (graceful) · worker_connections 1024, 3 upstreams healthy"
  224. "[backup] daily dump → /backup/household_$(date +%F).sql.gz 48MB · checksum verified, offsite copy synced"
  225. "[cron] certbot renew --dry-run → certificate not yet due (17 days left)"
  226. "[git] push origin master → 4 commits up, hooks ran, CI passed"
  227. "[git] rebase complete · replayed 6 commits onto origin/master, no conflicts"
  228. "[docs] CHANGELOG.md +1.9.2 → 3 features, 5 fixes, 2 security patches"
  229. "[arch] layering still one-way (cmd→internal→shared) · no new import cycles, graph check green"
  230. "[perf] slow-query log (1h) → 0 entries above 100ms · indexes effective under new partition layout"
  231. "[warn] disk usage /var 78% · logrotate daily, expect stable below 85%"
  232. "[err] worker#2 panic recovered · 1 job lost, requeued to DLQ for manual review"
  233. "[ci] pipeline #417 → all 12 jobs passed · 4m12s, zero flakes this week"
  234. "[review] PR #318 → 2 approvals · comments resolved, codeowner sign-off in"
  235. "[lint] govulncheck ./... → 0 known vulnerabilities · scan 20s"
  236. "[test] coverage diff +3.2% on notify pkg · overall 87.4% maintained"
  237. "[race] go test -race ./... → ok · 0 races across 6 packages"
  238. "[db] EXPLAIN SELECT ... WHERE created_at > now() → uses orders_idx_created · no temp table"
  239. "[redis] INFO stats → hits 92.4% misses 7.6% · evictions 0 in last 24h"
  240. "[metrics] Prometheus scrape → 214 series healthy · 3 targets up, 0 down"
  241. "[backup] restore dry-run on staging → 47/47 tables verified, checksum match"
  242. "[i18n] en/ja/zh-cn locales in sync · 98 strings, 0 missing keys"
  243. "[migrate] down migration ran on staging → reversible, schema back to prior state"
  244. "[cron] daily order reconciliation → 0 mismatches · settled + unpaid tallied"
  245. "[cache] warmup on deploy → 8.2k keys preloaded in 2.1s · cold-hit avoided"
  246. "[security] zap scan → 0 high, 3 medium (info-leak headers) · tracked in backlog"
  247. "[sso] token refresh job → ok · 214 sessions rotated, none expired mid-flight"
  248. "[observability] trace sample rate 5% · p95 spans < 800ms across service mesh"
  249. )
  250. # 输出/日志/错误行(可重复,作为“裸输出”随机插入)
  251. OUTPUTS=(
  252. "PASS"
  253. "ok"
  254. "HTTP 200"
  255. "Active: active (running)"
  256. "[GIN-debug] Listening and serving HTTP on :8081"
  257. "warn: chunk size exceeds 4000 kB"
  258. 'ERROR: failed to open source "file://internal/migrations"'
  259. "FATAL: database connection refused, retrying..."
  260. "0 error(s), 5 warning(s)"
  261. "migrations completed successfully"
  262. "no type errors found"
  263. "✓ 307 modules transformed."
  264. "Build succeeded after 3 retries"
  265. "done"
  266. "Compiled successfully."
  267. "exit code 0"
  268. "✓ 4 checks passed."
  269. "200 OK"
  270. "Deploy complete."
  271. "WARN: 3 unused route handlers detected"
  272. "WARN: log file rotated, reopening"
  273. "ERROR: context deadline exceeded (Client.Timeout)"
  274. "panic: runtime error: index out of range"
  275. "gofmt: no files need formatting"
  276. "lint clean · 0 warnings"
  277. "Test run finished: 3 passed, 0 failed"
  278. "security scan: 0 critical, 2 medium findings"
  279. "cache flushed"
  280. "up to date"
  281. "done · 0 errors"
  282. "Build successful"
  283. "ok (10 tests)"
  284. "WARN: slow query detected (1.2s > 100ms threshold)"
  285. "ERROR: cannot allocate memory in thread cache"
  286. "fatal: unable to access remote: Could not resolve host"
  287. "test: all passed"
  288. "checks passed: 6/6"
  289. "Deploy aborted: health check failed"
  290. "200 OK (cached)"
  291. "gzip: 1.9MB → 610KB saved"
  292. "→ build #417 succeeded in 24.8s"
  293. )
  294. # 动态随机数字行(消除固定值反复出现)
  295. gen_rand_lines() {
  296. local n=$((1 + RANDOM % 4)) # 1-4 条
  297. local i r
  298. for ((i = 0; i < n; i++)); do
  299. r=$((RANDOM % 7))
  300. case $r in
  301. 0) echo "ok $(awk -v seed=$RANDOM 'BEGIN{srand(seed); printf "%.3f", 0.05+rand()*1.5}')s" ;;
  302. 1) echo "dist/assets/index-*.js $(awk -v seed=$RANDOM 'BEGIN{srand(seed); printf "%.2f", 8+rand()*300}') kB │ gzip: $(awk -v seed=$RANDOM 'BEGIN{srand(seed); printf "%.2f", 3+rand()*80}') kB" ;;
  303. 2) echo "Progress: $((5 + RANDOM % 95))%..." ;;
  304. 3) echo "$((1 + RANDOM % 40)) test(s), $((RANDOM % 4)) failed" ;;
  305. 4) echo "deploy $(awk -v seed=$RANDOM 'BEGIN{srand(seed); for(i=0;i<6;i++) printf "%c", 97+int(rand()*26)}') · $(awk -v seed=$RANDOM 'BEGIN{srand(seed); printf "%.1f", 0.1+rand()*3}')s · service healthy" ;;
  306. 5) echo "p99 latency: $(awk -v seed=$RANDOM 'BEGIN{srand(seed); printf "%.1f", 5+rand()*180}') ms · $(awk -v seed=$RANDOM 'BEGIN{srand(seed); printf "%.1f", 1+rand()*9}')k req/min" ;;
  307. 6) echo "mem: $(awk -v seed=$RANDOM 'BEGIN{srand(seed); printf "%d", 120+rand()*400}') MB RSS · $(awk -v seed=$RANDOM 'BEGIN{srand(seed); printf "%d", 3+rand()*12}')% over baseline" ;;
  308. esac
  309. done
  310. }
  311. # 返回 $1 个不重复随机下标(0..$2-1)
  312. pick_unique() {
  313. local count=$1 pool=$2
  314. [ "$pool" -lt "$count" ] && count=$pool
  315. seq 0 $((pool - 1)) | sort -R | head -n "$count"
  316. }
  317. # 随机生成一段“工作日志”:命令(约一半带输出)+独立行+裸输出+动态数字,洗牌打乱
  318. # 块大小不规则、数字随机化,消除固定模式与重复数字
  319. gen_random_content() {
  320. local cmdc=$((1 + RANDOM % 5)) # 1-5 条命令
  321. local stc=$((2 + RANDOM % 6)) # 2-7 条独立行
  322. local ci si oi i
  323. LINES=()
  324. # 命令:约一半紧跟输出(不一定成对,制造不规则块)
  325. for ci in $(pick_unique "$cmdc" "${#COMMANDS[@]}"); do
  326. LINES+=("\$ ${COMMANDS[$ci]}")
  327. if [ $((RANDOM % 2)) -eq 0 ]; then LINES+=("${COMMAND_OUT[$ci]}"); fi
  328. [ $((RANDOM % 4)) -eq 0 ] && LINES+=("") # 随机空行
  329. done
  330. # 独立行(不重复)
  331. for si in $(pick_unique "$stc" "${#STANDALONE[@]}"); do
  332. LINES+=("${STANDALONE[$si]}")
  333. [ $((RANDOM % 3)) -eq 0 ] && LINES+=("") # 随机空行
  334. done
  335. # 裸输出行(可重复)
  336. for ((i = 0; i < $((2 + RANDOM % 4)); i++)); do
  337. LINES+=("${OUTPUTS[$((RANDOM % ${#OUTPUTS[@]}))]}")
  338. done
  339. # 动态随机数字行
  340. while IFS= read -r l; do LINES+=("$l"); done < <(gen_rand_lines)
  341. # 洗牌打乱整体顺序
  342. local idx=($(seq 0 $((${#LINES[@]} - 1)) | sort -R))
  343. local shuffled=()
  344. for i in "${idx[@]}"; do shuffled+=("${LINES[$i]}"); done
  345. LINES=("${shuffled[@]}")
  346. }
  347. # 内容来源:文件参数 > 随机生成
  348. CONTENT="${1-}"
  349. FILE_MODE=0
  350. if [ -n "$CONTENT" ] && [ -f "$CONTENT" ]; then
  351. mapfile -t LINES <"$CONTENT"
  352. FILE_MODE=1
  353. elif [ -n "$CONTENT" ] && [ "$CONTENT" != "-" ]; then
  354. echo "File not found: $CONTENT, falling back to random content." >&2
  355. gen_random_content
  356. else
  357. gen_random_content
  358. fi
  359. [ "${#LINES[@]}" -eq 0 ] && {
  360. echo "Content empty, nothing to slack on." >&2
  361. exit 1
  362. }
  363. # 随机延时
  364. rand_delay() {
  365. if [ "$DELAY_MS" -gt 0 ]; then
  366. sleep "$(awk -v d="$DELAY_MS" 'BEGIN{printf "%.3f", d/1000}')"
  367. else sleep "$(awk -v lo=80 -v hi=400 -v seed=$RANDOM 'BEGIN{srand(seed); printf "%.3f", (lo+int(rand()*(hi-lo+1)))/1000}')"; fi
  368. }
  369. # 按内容语义配色(优先级:命令 > 致命 > 错误 > 警告 > 成功 > 默认)
  370. # 命令=青 / FATAL=红加粗 / 错误=红 / 警告=黄 / 成功=绿;仅随机生成模式调用
  371. colorize() {
  372. local line="$1" code=""
  373. case "$line" in
  374. '$ '*) code=$'\033[1;36m' ;;
  375. *[Ff][Aa][Tt][Aa][Ll]*) code=$'\033[1;31m' ;;
  376. *ERROR* | *ERR:* | *\[err\]* | *err:*) code=$'\033[31m' ;;
  377. *warn* | *WARN*) code=$'\033[33m' ;;
  378. *'✓'* | *PASS* | *'ok '* | *'HTTP 200'* | *PONG* | *'no type errors'* | *'completed successfully'* | *'Build succeeded'*) code=$'\033[32m' ;;
  379. esac
  380. if [ -n "$code" ]; then
  381. # 概率门控: 仅约 COLOR_RATIO% 的命中行真正上彩(降彩色密度); 100=全彩 0=全无色
  382. if [ "$COLOR_RATIO" -ge 100 ] || [ $((RANDOM % 100)) -lt "$COLOR_RATIO" ]; then
  383. printf '%s%s\033[0m' "$code" "$line"
  384. else
  385. printf '%s' "$line"
  386. fi
  387. else
  388. printf '%s' "$line"
  389. fi
  390. }
  391. run_once() {
  392. local line
  393. for line in "${LINES[@]}"; do
  394. local out="$line"
  395. # 文件模式或终端不支持颜色 → 原样输出
  396. if [ "$FILE_MODE" = "0" ] && [ "$COLOR" = "1" ]; then out=$(colorize "$line"); fi
  397. if [ "$TYPE_EFFECT" = "1" ]; then
  398. local i
  399. for ((i = 0; i < ${#out}; i++)); do
  400. printf "%s" "${out:i:1}"
  401. rand_delay
  402. done
  403. echo ""
  404. else
  405. printf '%s\n' "$out"
  406. fi
  407. rand_delay
  408. done
  409. echo "" # 每遍之间空行
  410. }
  411. n=0
  412. while [ "$LOOP_TIMES" -eq 0 ] || [ "$n" -lt "$LOOP_TIMES" ]; do
  413. n=$((n + 1))
  414. # 每轮重新生成随机内容(避免内容固定导致反复重复);文件模式则用固定内容
  415. [ "$FILE_MODE" = "0" ] && gen_random_content
  416. run_once
  417. done
  418. exit 0