tool-moyu.sh 21 KB

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