初始化:GitHub 同步插件

This commit is contained in:
dsh committed 2026-11-17 12:03:35 +08:00
commit b1b1c821cc
14 files changed
+925

No files matched your search

+142
View File
@@ -0,0 +1,142 @@
// github-sync —— 在 Web 界面里用 `/github` 命令把项目源码推上 GitHub,并自动生成 README 说明。
// 与本地 dsh-go 插件共用同一份配置与令牌(~/.dsh/dsh-go/github-upload.json、github-token)。
import { loadConfig, saveConfig, readToken, writeToken, ago } from './lib/store.js'
import {
discoverRoots, findProjects, projectForCwd, projectName, repoName,
} from './lib/project.js'
import { getLogin } from './lib/github.js'
import { uploadOne, requireToken, friendly } from './lib/upload.js'
export const name = 'github-sync'
export const inject = ['commands']
const TOKEN_RE = /^(ghp_|github_pat_|gho_|ghs_|ghu_)[A-Za-z0-9_]{20,255}$/
const USAGE = [
'用法:',
' /github 上传当前工作区项目',
' /github token <令牌> 绑定 GitHub 令牌(不会进入对话记录)',
' /github status 看令牌、账号、最近一次上传',
' /github all 上传所有识别到的项目',
' /github auto on|off 每轮结束后自动上传本轮改过的项目',
].join('\n')
/** 会话当前工作目录。 */
function cwdOf(ctx, agent) {
const wd = ctx.get('workingDirectory')
try {
const dir = wd?.get(agent.session)
if (typeof dir === 'string' && dir !== '') return dir
} catch {}
return agent.session?.header?.cwd ?? process.cwd()
}
/** 把 cwd 归到项目目录;找不到就退回 cwd 本身。 */
function projectOf(ctx, agent) {
const cwd = cwdOf(ctx, agent)
return projectForCwd(cwd) ?? cwd
}
function ok(text) { return { kind: 'success', text } }
function fail(text) { return { kind: 'error', text } }
async function pushOne(dir, description) {
const rec = await uploadOne(dir, { description })
const bits = [
`✓ ${projectName(dir)} → ${rec.repo}${rec.created ? '(新建仓库)' : ''}`,
` ${rec.files} 个文件已提交${rec.pushed ? '并推送' : '(无改动,未推送)'}`,
` ${rec.url}`,
` README:${{ created: '已生成说明', regenerated: '已更新说明', existing: '保留你手写的版本' }[rec.readme] ?? '已保留'}`,
]
return bits.join('\n')
}
async function handle(ctx, inv) {
const raw = (inv.rawInput ?? '').trim()
const parts = raw.split(/\s+/).filter(Boolean)
const verb = parts[0] ?? ''
const arg = parts.slice(1).join(' ')
if (verb === '' || verb === 'push') {
const dir = projectOf(ctx, inv.agent)
try {
return ok(await pushOne(dir, ''))
} catch (error) {
return fail(friendly(error))
}
}
if (verb === 'token') {
const token = arg.trim()
if (token === '') return fail(`请把令牌写在命令后面。\n${USAGE}`)
if (!TOKEN_RE.test(token)) return fail('这个令牌格式不对:GitHub 令牌通常以 ghp_ 或 github_pat_ 开头,长度 20 位以上。')
writeToken(token)
const cfg = loadConfig()
try {
const login = await getLogin(token)
cfg.login = login
saveConfig(cfg)
return ok(`✓ 令牌已保存(权限 600),账号:${login}\n现在直接发 /github 就能上传。`)
} catch (error) {
const len = token.length
const shape = token.startsWith('ghp_')
? (len === 40 ? '' : `\n这串长度 ${len},classic 令牌固定 40 位(ghp_ + 36),多出的字符通常是复制时混进去的。`)
: `\n这串长度 ${len}。`
return fail(`令牌已保存,但校验失败:${friendly(error)}${shape}`)
}
}
if (verb === 'status') {
const cfg = loadConfig()
const token = readToken()
const dir = projectOf(ctx, inv.agent)
const rec = cfg.repos?.[dir]
const lines = [
token === '' ? '令牌:未绑定(发 /github token <令牌>)' : `令牌:已绑定${cfg.login ? `(${cfg.login})` : ''}`,
`可见性:${cfg.private ? '私有仓库' : '公开仓库'}`,
`自动上传:${cfg.auto ? '开' : '关'}`,
`当前项目:${projectName(dir)}(${dir})`,
rec ? `上次上传:${ago(rec.lastPush)} · ${rec.repo} · ${rec.files} 个文件\n ${rec.url}` : '这个项目还没上传过。',
]
return ok(lines.join('\n'))
}
if (verb === 'all') {
const cfg = loadConfig()
try { requireToken() } catch (error) { return fail(friendly(error)) }
const projects = findProjects(discoverRoots(cfg.roots ?? []))
if (projects.length === 0) return fail('没有找到项目目录。')
const lines = []
for (const item of projects.slice(0, 10)) {
try {
lines.push(await pushOne(item.dir, ''))
} catch (error) {
lines.push(`✗ ${item.name}:${friendly(error)}`)
}
}
return ok(lines.join('\n\n'))
}
if (verb === 'auto') {
const cfg = loadConfig()
if (arg === 'on' || arg === 'off') {
cfg.auto = arg === 'on'
saveConfig(cfg)
return ok(cfg.auto ? '✓ 已开启:每轮结束后自动上传本轮改过的项目。' : '✓ 已关闭自动上传。')
}
return ok(`自动上传现在是${cfg.auto ? '开' : '关'}的。用 /github auto on 或 on/off 切换。`)
}
return fail(USAGE)
}
export function apply(ctx) {
ctx.commands.register({
definitionId: '@local/github-sync',
name: 'github',
description: '上传项目源码到 GitHub,并自动生成 README 说明',
input: { hint: '[status | token <令牌> | all | auto on|off]' },
recordInput: false,
handler: (inv) => handle(ctx, inv),
})
}