226 lines
7.2 KiB
JavaScript
226 lines
7.2 KiB
JavaScript
#!/usr/bin/env node
|
||
// 扫描工作区,生成控制台用的 manifest.json
|
||
// 用法:
|
||
// node scan.mjs # 扫描 /root/workspace
|
||
// node scan.mjs --no-probe # 不探测服务器上的站点
|
||
// node scan.mjs --dir /path # 换一个目录
|
||
import { readdir, stat, readFile, writeFile } from 'node:fs/promises'
|
||
import { join, extname } from 'node:path'
|
||
import { execFile } from 'node:child_process'
|
||
import { promisify } from 'node:util'
|
||
|
||
const run = promisify(execFile)
|
||
const args = process.argv.slice(2)
|
||
const NO_PROBE = args.includes('--no-probe')
|
||
const dirArg = args.indexOf('--dir')
|
||
const ROOT = dirArg >= 0 ? args[dirArg + 1] : '/root/workspace'
|
||
const OUT = new URL('./manifest.json', import.meta.url).pathname
|
||
const HOST = 'http://110.42.217.133'
|
||
|
||
// 已经部署到服务器的站点
|
||
const SERVICES = [
|
||
{ name: 'DevBox 工具箱', port: 8090, desc: '25 个开发者工具 · 账号/积分' },
|
||
{ name: 'imgbed 图床', port: 8088, desc: '多用户图库 · SQLite' },
|
||
{ name: '堂食点餐', port: 8099, desc: '顾客点餐 + 后厨看板' },
|
||
{ name: '深海迷宫', port: 8100, desc: '光线投射小游戏' },
|
||
{ name: '工作区控制台', port: 8089, desc: '就是这个页面' },
|
||
{ name: 'Gitea', port: 3000, desc: '代码仓库' },
|
||
]
|
||
|
||
const DEPLOYED = { devbox: 8090, imgbed: 8088, 'dine-order': 8099, raycast3d: 8100, console: 8089, minecraft: 8093, gctools: 8092 }
|
||
const SKIP = new Set(['node_modules', '.git', 'data', 'dist', 'build', '.cache'])
|
||
|
||
async function walk(dir, acc = { bytes: 0, files: 0, ext: {}, top: [] }, depth = 0) {
|
||
let entries = []
|
||
try {
|
||
entries = await readdir(dir, { withFileTypes: true })
|
||
} catch {
|
||
return acc
|
||
}
|
||
for (const e of entries) {
|
||
if (SKIP.has(e.name)) continue
|
||
const p = join(dir, e.name)
|
||
if (e.isDirectory()) {
|
||
if (depth === 0) acc.top.push(`${e.name}/`)
|
||
await walk(p, acc, depth + 1)
|
||
} else if (e.isFile()) {
|
||
try {
|
||
const s = await stat(p)
|
||
acc.bytes += s.size
|
||
acc.files += 1
|
||
const ext = extname(e.name).slice(1).toLowerCase() || 'none'
|
||
acc.ext[ext] = (acc.ext[ext] || 0) + 1
|
||
if (depth === 0) acc.top.push(e.name)
|
||
} catch {}
|
||
}
|
||
}
|
||
return acc
|
||
}
|
||
|
||
async function gitInfo(dir) {
|
||
const opt = { cwd: dir, timeout: 5000 }
|
||
try {
|
||
const [branch, head, status, remote, aheadBehind] = await Promise.all([
|
||
run('git', ['rev-parse', '--abbrev-ref', 'HEAD'], opt).then((r) => r.stdout.trim()).catch(() => ''),
|
||
run('git', ['log', '-1', '--pretty=%h|%s|%cI'], opt).then((r) => r.stdout.trim()).catch(() => ''),
|
||
run('git', ['status', '--porcelain'], opt).then((r) => r.stdout.trim()).catch(() => ''),
|
||
run('git', ['remote', 'get-url', 'origin'], opt).then((r) => r.stdout.trim()).catch(() => ''),
|
||
run('git', ['rev-list', '--left-right', '--count', 'origin/HEAD...HEAD'], opt).then((r) => r.stdout.trim()).catch(() => ''),
|
||
])
|
||
if (!head) return null
|
||
const [sha, subject, date] = head.split('|')
|
||
const m = remote.match(/(?:github\.com|:3000)[/:]([\w.-]+)\/([\w.-]+?)(?:\.git)?$/)
|
||
const repo = m ? `${m[1]}/${m[2]}` : ''
|
||
let ahead = 0
|
||
let behind = 0
|
||
if (aheadBehind) {
|
||
const [b, a] = aheadBehind.split(/\s+/).map(Number)
|
||
behind = b || 0
|
||
ahead = a || 0
|
||
}
|
||
return {
|
||
branch,
|
||
sha,
|
||
subject,
|
||
date,
|
||
dirty: status !== '',
|
||
changes: status ? status.split('\n').length : 0,
|
||
remote,
|
||
repo,
|
||
webRepo: repo ? (remote.includes('github.com') ? `https://github.com/${repo}` : `${HOST}:3000/${repo}`) : '',
|
||
ahead,
|
||
behind,
|
||
}
|
||
} catch {
|
||
return null
|
||
}
|
||
}
|
||
|
||
async function readme(dir) {
|
||
for (const name of ['README.md', 'readme.md', 'README.MD']) {
|
||
try {
|
||
const text = await readFile(join(dir, name), 'utf8')
|
||
const lines = text.split('\n')
|
||
const head = lines.slice(0, 6).find((l) => /^#\s+/.test(l.trim()))
|
||
const title = head ? head.replace(/^#\s+/, '').trim().slice(0, 60) : ''
|
||
const para = text
|
||
.split(/\n{2,}/)
|
||
.map((p) => p.replace(/[*_`>#]/g, '').trim())
|
||
.find((p) => p && !p.startsWith('!') && !p.startsWith('<') && !p.startsWith('|') && !p.startsWith('-'))
|
||
return { title, desc: (para || '').replace(/\s+/g, ' ').slice(0, 160) }
|
||
} catch {}
|
||
}
|
||
return { title: '', desc: '' }
|
||
}
|
||
|
||
function kindOf(name) {
|
||
if (DEPLOYED[name]) return 'site'
|
||
if (name.endsWith('-backup') || name.includes('mirror')) return 'mirror'
|
||
if (/^(local-|dsh-)/.test(name)) return 'plugin'
|
||
return 'repo'
|
||
}
|
||
|
||
const human = (n) => {
|
||
const u = ['B', 'KB', 'MB', 'GB']
|
||
let i = 0
|
||
let v = n
|
||
while (v >= 1024 && i < u.length - 1) {
|
||
v /= 1024
|
||
i++
|
||
}
|
||
return `${v < 10 ? v.toFixed(1) : Math.round(v)} ${u[i]}`
|
||
}
|
||
|
||
async function probeServices() {
|
||
const out = []
|
||
for (const s of SERVICES) {
|
||
const url = `${HOST}:${s.port}/`
|
||
const started = Date.now()
|
||
let ok = false
|
||
try {
|
||
const res = await fetch(url, { signal: AbortSignal.timeout(4000), redirect: 'manual' })
|
||
ok = res.status > 0 && res.status < 500
|
||
} catch {}
|
||
out.push({ ...s, url, ok, ms: Date.now() - started })
|
||
}
|
||
return out
|
||
}
|
||
|
||
const entries = []
|
||
let totalBytes = 0
|
||
let totalFiles = 0
|
||
|
||
for (const e of await readdir(ROOT, { withFileTypes: true })) {
|
||
if (e.name.startsWith('.') || SKIP.has(e.name)) continue
|
||
const p = join(ROOT, e.name)
|
||
const s = await stat(p)
|
||
if (!e.isDirectory()) {
|
||
totalBytes += s.size
|
||
totalFiles += 1
|
||
entries.push({
|
||
name: e.name,
|
||
kind: 'file',
|
||
bytes: s.size,
|
||
size: human(s.size),
|
||
files: 1,
|
||
mtime: s.mtime.toISOString(),
|
||
title: '',
|
||
desc: '',
|
||
top: [],
|
||
ext: ['file'],
|
||
port: 0,
|
||
})
|
||
continue
|
||
}
|
||
const acc = await walk(p)
|
||
const git = await gitInfo(p)
|
||
const readmeInfo = await readme(p)
|
||
const extTop = Object.entries(acc.ext)
|
||
.sort((a, b) => b[1] - a[1])
|
||
.slice(0, 4)
|
||
.map(([k, v]) => `${k}×${v}`)
|
||
totalBytes += acc.bytes
|
||
totalFiles += acc.files
|
||
entries.push({
|
||
name: e.name,
|
||
kind: kindOf(e.name),
|
||
bytes: acc.bytes,
|
||
size: human(acc.bytes),
|
||
files: acc.files,
|
||
mtime: s.mtime.toISOString(),
|
||
title: readmeInfo.title,
|
||
desc: readmeInfo.desc,
|
||
top: acc.top.slice(0, 8),
|
||
ext: extTop,
|
||
git,
|
||
port: DEPLOYED[e.name] || 0,
|
||
url: DEPLOYED[e.name] ? `${HOST}:${DEPLOYED[e.name]}/` : '',
|
||
})
|
||
}
|
||
|
||
entries.sort((a, b) => b.bytes - a.bytes)
|
||
const services = NO_PROBE ? SERVICES.map((s) => ({ ...s, url: `${HOST}:${s.port}/`, ok: null, ms: 0 })) : await probeServices()
|
||
|
||
const manifest = {
|
||
root: ROOT,
|
||
scannedAt: new Date().toISOString(),
|
||
totals: {
|
||
bytes: totalBytes,
|
||
size: human(totalBytes),
|
||
files: totalFiles,
|
||
projects: entries.filter((e) => e.kind !== 'file').length,
|
||
dirty: entries.filter((e) => e.git?.dirty).length,
|
||
},
|
||
services,
|
||
entries,
|
||
}
|
||
|
||
await writeFile(OUT, JSON.stringify(manifest, null, 2))
|
||
const up = services.filter((s) => s.ok).length
|
||
console.log(`扫描完成:${entries.length} 项 · ${human(totalBytes)} · ${totalFiles} 个文件 · 站点 ${up}/${services.length} 在线`)
|
||
for (const e of entries) {
|
||
const tag = e.port ? `:${e.port}` : ''
|
||
const g = e.git ? ` ${e.git.branch}${e.git.dirty ? '*' : ''}` : ''
|
||
console.log(` ${e.size.padStart(9)} ${(e.name + tag + g).padEnd(34)} ${e.title || ''}`)
|
||
}
|