// 项目发现、README 生成与“本轮改了什么”的判断。纯文件系统操作,不联网。 import { existsSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs' import { basename, join } from 'node:path' import { createHash } from 'node:crypto' export const IGNORED_DIRS = new Set([ 'node_modules', '.git', 'dist', 'build', '.next', '.nuxt', '.output', '.venv', 'venv', '__pycache__', 'vendor', 'Pods', '.dart_tool', 'coverage', '.cache', 'target', '.gradle', '.idea', '.vscode', '.svelte-kit', 'out' ]) const MARKERS = [ 'package.json', 'pubspec.yaml', 'index.html', 'Cargo.toml', 'go.mod', 'requirements.txt', 'pyproject.toml', 'composer.json', 'build.gradle', 'Podfile', '.git', 'app.json', 'main.py' ] export function isDirectory(path) { try { return statSync(path).isDirectory() } catch { return false } } export function hasMarker(dir) { return MARKERS.some((m) => existsSync(join(dir, m))) } /** 工作区根列表:配置里的 roots + 默认 ~/workspace + dsh 工作区注册表。 */ export function discoverRoots(extra = [], dshHome) { const set = new Set() for (const p of extra) if (typeof p === 'string' && p.trim() !== '') set.add(p.trim()) set.add(join(process.env.HOME || '/root', 'workspace')) if (dshHome) { try { const raw = JSON.parse(readFileSync(join(dshHome, 'storages', 'workspace.json'), 'utf8')) const table = raw?.tables?.workspaces if (table && typeof table === 'object') { for (const rec of Object.values(table)) if (rec && typeof rec.path === 'string') set.add(rec.path) } } catch {} } return [...set].filter((p) => isDirectory(p)) } /** 扫描工作区:根本身是项目就算一个,否则取一层子目录里的项目。 */ export function findProjects(roots) { const out = [] const seen = new Set() for (const root of roots) { const add = (dir, name) => { if (seen.has(dir) || dir.includes('node_modules')) return seen.add(dir) out.push({ dir, name }) } if (hasMarker(root)) add(root, projectName(root)) let entries = [] try { entries = readdirSync(root, { withFileTypes: true }) } catch { continue } for (const e of entries) { if (!e.isDirectory() || e.name.startsWith('.') || IGNORED_DIRS.has(e.name)) continue const dir = join(root, e.name) if (hasMarker(dir)) add(dir, e.name) } } return out.sort((a, b) => a.name.localeCompare(b.name)) } /** 从会话 cwd 往上找最近的包含项目标记的目录。 */ export function projectForCwd(cwd) { if (typeof cwd !== 'string' || cwd === '' || !isDirectory(cwd)) return null let dir = cwd for (let i = 0; i < 4; i++) { if (hasMarker(dir)) return dir const parent = dir.slice(0, dir.lastIndexOf('/')) || '/' if (parent === dir || parent === '/') break dir = parent } return null } /** 仓库名:ASCII 化;中文名退化为 app-。 */ export function repoName(dir) { const base = basename(dir).toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^[-._]+|[-._]+$/g, '').slice(0, 60) if (/[a-z0-9]/.test(base)) return base return `app-${createHash('sha1').update(dir).digest('hex').slice(0, 8)}` } export function projectName(dir) { return basename(dir) || 'app' } /** 目录树,深度 2、最多 60 行。 */ export function treeOf(dir, maxLines = 60) { const lines = [] const walk = (current, prefix, depth) => { if (lines.length >= maxLines || depth > 2) return let entries = [] try { entries = readdirSync(current, { withFileTypes: true }) } catch { return } entries = entries .filter((e) => !e.name.startsWith('.') || e.name === '.github') .filter((e) => !IGNORED_DIRS.has(e.name)) .filter((e) => e.name !== 'README.md' && e.name !== '.gitignore') .sort((a, b) => Number(b.isDirectory()) - Number(a.isDirectory()) || a.name.localeCompare(b.name)) entries.slice(0, 24).forEach((e, index) => { if (lines.length >= maxLines) return const last = index === entries.slice(0, 24).length - 1 lines.push(`${prefix}${last ? '└── ' : '├── '}${e.name}${e.isDirectory() ? '/' : ''}`) if (e.isDirectory()) walk(join(current, e.name), `${prefix}${last ? ' ' : '│ '}`, depth + 1) }) } walk(dir, '', 0) return lines.join('\n') } /** 粗略识别技术栈。 */ export function stackOf(dir) { const out = [] const readJson = (name) => { try { return JSON.parse(readFileSync(join(dir, name), 'utf8')) } catch { return null } } if (existsSync(join(dir, 'package.json'))) { const pkg = readJson('package.json') || {} const deps = Object.keys({ ...(pkg.dependencies || {}), ...(pkg.devDependencies || {}) }) const has = (n) => deps.includes(n) if (has('react') || has('react-dom')) out.push('React') if (has('vue')) out.push('Vue') if (has('svelte')) out.push('Svelte') if (has('next')) out.push('Next.js') if (has('vite')) out.push('Vite') if (has('express') || has('koa') || has('fastify')) out.push('Node 服务端') if (has('electron')) out.push('Electron') if (out.length === 0) out.push('Node.js') const scripts = pkg.scripts && typeof pkg.scripts === 'object' ? Object.keys(pkg.scripts) : [] if (scripts.length > 0) out.push(`脚本:${scripts.slice(0, 4).join(' / ')}`) } if (existsSync(join(dir, 'pubspec.yaml'))) out.push('Flutter / Dart') if (existsSync(join(dir, 'requirements.txt')) || existsSync(join(dir, 'pyproject.toml'))) out.push('Python') if (existsSync(join(dir, 'Cargo.toml'))) out.push('Rust') if (existsSync(join(dir, 'go.mod'))) out.push('Go') if (out.length === 0 && existsSync(join(dir, 'index.html'))) out.push('静态网页') return out } const README_MARK = '' /** 生成/更新 README 说明;手写的 README 原样保留。 */ export function ensureReadme(dir, { name, description, force = false }) { const file = join(dir, 'README.md') let current = '' try { current = readFileSync(file, 'utf8') } catch {} const ours = current.includes(README_MARK) if (current.trim() !== '' && !ours && !force) return { written: false, reason: 'existing' } const stack = stackOf(dir) const tree = treeOf(dir) // 已经是我们生成的 README:保留首次写入的说明,避免每次上传都改一遍。 let kept if (ours && !force) { const head = current.slice(0, current.indexOf(README_MARK)).split('\n') kept = head.slice(2).join('\n').trim() } const summary = (kept ?? '').trim() !== '' ? kept.trim() : ((description || '').trim() || `这是 ${name} 的源代码,由 dsh-go 自动同步到 GitHub。`) const body = [ `# ${name}`, '', summary, '', README_MARK, '## 技术栈', '', ...(stack.length > 0 ? stack.map((s) => `- ${s}`) : ['- 暂未识别']), '', '## 项目结构', '', '```text', tree === '' ? '(空目录)' : tree, '```', '', '## 同步说明', '', '本文件由 dsh-go 自动生成;提交与推送都在本机完成,令牌不会写进仓库。', '' ].join('\n') writeFileSync(file, body) return { written: true, reason: ours ? 'regenerated' : 'created' } } const GITIGNORE_LINES = [ 'node_modules/', 'dist/', 'build/', '.venv/', 'venv/', '__pycache__/', '*.pyc', '.DS_Store', '*.log', '.env', '.env.*', '.dart_tool/', '.next/', '.cache/', 'coverage/' ] export function ensureGitignore(dir) { const file = join(dir, '.gitignore') let current = '' try { current = readFileSync(file, 'utf8') } catch {} const lines = current.split('\n').map((l) => l.trim()) const missing = GITIGNORE_LINES.filter((l) => !lines.includes(l)) if (missing.length === 0) return false const next = `${current.trimEnd()}${current.trim() === '' ? '' : '\n'}\n# dsh-go 自动补充\n${missing.join('\n')}\n` writeFileSync(file, next.replace(/^\n+/, '')) return true } /** 目录里最新的文件修改时间(跳过依赖目录),用于判断本轮是否改过。 */ export function newestMtime(dir, budget = 1500) { let newest = 0 let seen = 0 const walk = (current, depth) => { if (depth > 5 || seen > budget) return let entries = [] try { entries = readdirSync(current, { withFileTypes: true }) } catch { return } for (const e of entries) { if (seen > budget) return if (e.name.startsWith('.') && e.name !== '.github' && e.name !== '.gitignore') continue if (IGNORED_DIRS.has(e.name)) continue const full = join(current, e.name) if (e.isDirectory()) { walk(full, depth + 1); continue } seen++ try { const st = statSync(full) if (st.mtimeMs > newest) newest = st.mtimeMs } catch {} } } walk(dir, 0) return newest } /** 本轮改动过的项目:cwd 对应项目 + cwd 下 mtime 晚于 since 的子项目。 */ export function changedProjects(cwd, since, extraRoots = []) { const out = [] const own = projectForCwd(cwd) if (own && newestMtime(own) >= since) out.push(own) const roots = [cwd, ...extraRoots].filter(isDirectory) for (const p of findProjects(roots)) { if (out.includes(p.dir)) continue if (newestMtime(p.dir) >= since) out.push(p.dir) } return out.slice(0, 6) } export function sizeOf(dir) { let total = 0 let seen = 0 const walk = (current) => { if (seen > 4000) return let entries = [] try { entries = readdirSync(current, { withFileTypes: true }) } catch { return } for (const e of entries) { if (IGNORED_DIRS.has(e.name) || e.name === '.git') continue const full = join(current, e.name) if (e.isDirectory()) { walk(full); continue } seen++ try { total += statSync(full).size } catch {} } } walk(dir) return total }