dsh-go 手机版 GitHub 自动上传插件(胶囊 + 面板 + 回合脚注)
由 dsh-go 自动上传 · 2026/11/17 12:09:15
This commit is contained in:
commit
7c02807cb6
12 files changed
+1302
No files matched your search
+477
@@ -0,0 +1,477 @@
|
||||
// local-github-upload —— 把 App 源码提交并推送到 GitHub,并自动生成 README 说明。
|
||||
// 手动:输入框上方的「上传 GitHub」胶囊 + 「GitHub 上传」面板。
|
||||
// 自动:每轮结束时只推送本轮改过的项目(面板里可开)。
|
||||
import { DSH_HOME, loadConfig, saveConfig, readToken, writeToken, ago } from './store.js'
|
||||
import {
|
||||
discoverRoots, findProjects, changedProjects, repoName, projectName,
|
||||
ensureReadme, ensureGitignore
|
||||
} from './project.js'
|
||||
import { getLogin, ensureRepo, GitHubError } from './github.js'
|
||||
import { gitAvailable, commitAndPush, GitError } from './git.js'
|
||||
|
||||
export const name = 'local-github-upload'
|
||||
|
||||
const TOKEN_COMMAND = 'node ~/.dsh/dsh-go/plugins/local-github-upload/bin/token.js'
|
||||
|
||||
let bridge = null
|
||||
let job = null
|
||||
let lastError = ''
|
||||
|
||||
function refreshPanels() {
|
||||
try { bridge?.refresh('github', {}) } catch {}
|
||||
}
|
||||
|
||||
function friendly(error) {
|
||||
if (error instanceof GitHubError || error instanceof GitError) return error.message
|
||||
const message = error?.message ?? String(error)
|
||||
if (/fetch failed|ENOTFOUND|ECONNREFUSED|ETIMEDOUT/i.test(message)) return '连不上 GitHub,请检查网络后重试。'
|
||||
return message.length > 160 ? `${message.slice(0, 157)}…` : message
|
||||
}
|
||||
|
||||
/** 上传一个项目:补 README/.gitignore → 建仓库 → 提交 → 推送 → 记状态。 */
|
||||
async function uploadOne(dir, { description = '' } = {}) {
|
||||
const cfg = loadConfig()
|
||||
const token = readToken()
|
||||
if (token === '') throw new Error('还没有配置 GitHub 令牌')
|
||||
if (!gitAvailable()) throw new Error('这台机器上没有 git,无法上传')
|
||||
let login = cfg.login
|
||||
if (login === '') {
|
||||
login = await getLogin(token)
|
||||
cfg.login = login
|
||||
saveConfig(cfg)
|
||||
}
|
||||
const name = repoName(dir)
|
||||
ensureGitignore(dir)
|
||||
const readme = ensureReadme(dir, { name, description })
|
||||
const repo = await ensureRepo({
|
||||
token,
|
||||
login,
|
||||
name,
|
||||
privateRepo: cfg.private,
|
||||
description: (description || cfg.description || '').trim() || `${projectName(dir)},由 dsh-go 同步`
|
||||
})
|
||||
const when = new Date().toLocaleString('zh-CN', { hour12: false })
|
||||
const head = description.trim() === '' ? `同步 ${projectName(dir)} 源码` : description.trim()
|
||||
const message = `${head}\n\n由 dsh-go 自动上传 · ${when}`
|
||||
const result = await commitAndPush(dir, { url: repo.cloneUrl, token, login, message })
|
||||
const rec = {
|
||||
repo: `${login}/${name}`,
|
||||
url: repo.url,
|
||||
lastPush: Date.now(),
|
||||
lastCommit: result.commit,
|
||||
files: result.files,
|
||||
readme: readme.written ? readme.reason : 'kept'
|
||||
}
|
||||
cfg.repos[dir] = rec
|
||||
saveConfig(cfg)
|
||||
return { ...rec, created: repo.created }
|
||||
}
|
||||
|
||||
/** 后台任务:串行上传,面板数据轮询进度。 */
|
||||
function startJob(items, description, { auto = false } = {}) {
|
||||
if (job?.running) return { busy: true }
|
||||
const list = items.slice(0, 20)
|
||||
job = {
|
||||
running: true,
|
||||
auto,
|
||||
total: list.length,
|
||||
done: 0,
|
||||
current: list[0]?.name ?? '',
|
||||
startedAt: Date.now(),
|
||||
finishedAt: 0,
|
||||
ok: true,
|
||||
results: [],
|
||||
error: ''
|
||||
}
|
||||
lastError = ''
|
||||
;(async () => {
|
||||
for (const item of list) {
|
||||
job.current = item.name
|
||||
try {
|
||||
const rec = await uploadOne(item.dir, { description })
|
||||
job.results.push({ ok: true, name: item.name, url: rec.url, files: rec.files })
|
||||
} catch (error) {
|
||||
const message = friendly(error)
|
||||
job.ok = false
|
||||
job.results.push({ ok: false, name: item.name, message })
|
||||
lastError = message
|
||||
}
|
||||
job.done++
|
||||
refreshPanels()
|
||||
}
|
||||
job.running = false
|
||||
job.finishedAt = Date.now()
|
||||
refreshPanels()
|
||||
})().catch((error) => {
|
||||
if (job !== null) {
|
||||
job.running = false
|
||||
job.ok = false
|
||||
job.finishedAt = Date.now()
|
||||
job.error = friendly(error)
|
||||
}
|
||||
lastError = friendly(error)
|
||||
refreshPanels()
|
||||
})
|
||||
return { started: true }
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 面板
|
||||
|
||||
const TEXT = {
|
||||
pushAll: { zh: '上传全部', en: 'Push all' },
|
||||
refresh: { zh: '刷新', en: 'Refresh' },
|
||||
tokenHelp: { zh: '令牌步骤', en: 'Token steps' },
|
||||
openTokens: { zh: '打开令牌页', en: 'Open tokens' }
|
||||
}
|
||||
|
||||
function panelView(_scope, caps) {
|
||||
const zh = !String(caps?.locale ?? '').toLowerCase().startsWith('en')
|
||||
const L = (a, b) => (zh ? a : b)
|
||||
return {
|
||||
v: 2,
|
||||
type: 'stack',
|
||||
title: L('GitHub 上传', 'GitHub upload'),
|
||||
children: [
|
||||
{ type: 'callout', text: { $: 'data.hint' }, tone: { $: 'data.hintTone' } },
|
||||
{
|
||||
type: 'keyValue',
|
||||
items: [
|
||||
{ label: L('账号', 'Account'), value: { $: 'data.account' } },
|
||||
{ label: L('可见性', 'Visibility'), value: { $: 'data.visibility' } },
|
||||
{ label: L('自动上传', 'Auto'), value: { $: 'data.autoText' } },
|
||||
{ label: L('工作区', 'Workspace'), value: { $: 'data.rootsText' } }
|
||||
]
|
||||
},
|
||||
{
|
||||
type: 'progress',
|
||||
value: { $: 'data.jobPct' },
|
||||
label: { $: 'data.jobLabel' },
|
||||
caption: { $: 'data.jobCaption' },
|
||||
tone: { $: 'data.jobTone' }
|
||||
},
|
||||
{ type: 'list', items: { $: 'data.projects' } },
|
||||
{ type: 'text', text: { $: 'data.emptyHint' }, tone: 'muted' },
|
||||
{
|
||||
type: 'actions',
|
||||
items: [
|
||||
{ label: L(TEXT.pushAll.zh, TEXT.pushAll.en), action: 'pushAll' },
|
||||
{ label: L(TEXT.refresh.zh, TEXT.refresh.en), action: 'refresh' }
|
||||
]
|
||||
},
|
||||
{
|
||||
type: 'options',
|
||||
id: 'autoMode',
|
||||
selected: { $: 'data.autoValue' },
|
||||
options: [
|
||||
{ label: L('关闭', 'Off'), value: 'off', description: L('只用手动按钮', 'Manual only') },
|
||||
{ label: L('开启', 'On'), value: 'on', description: L('每轮结束推送改动', 'Push after each turn') }
|
||||
]
|
||||
},
|
||||
{
|
||||
type: 'options',
|
||||
id: 'visibility',
|
||||
selected: { $: 'data.privateValue' },
|
||||
options: [
|
||||
{ label: L('私有仓库', 'Private'), value: 'private' },
|
||||
{ label: L('公开仓库', 'Public'), value: 'public' }
|
||||
]
|
||||
},
|
||||
{
|
||||
type: 'actions',
|
||||
items: [
|
||||
{ label: L(TEXT.tokenHelp.zh, TEXT.tokenHelp.en), action: 'tokenHelp' },
|
||||
{ label: L(TEXT.openTokens.zh, TEXT.openTokens.en), action: 'openTokens' }
|
||||
]
|
||||
},
|
||||
{ type: 'text', text: { $: 'data.tokenHint' }, tone: 'muted' }
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
function panelData(_scope, emit, caps) {
|
||||
const zh = !String(caps?.locale ?? '').toLowerCase().startsWith('en')
|
||||
const tick = () => {
|
||||
try { emit(snapshot(zh)) } catch (error) { lastError = friendly(error) }
|
||||
}
|
||||
tick()
|
||||
const timer = setInterval(tick, 2500)
|
||||
timer.unref?.()
|
||||
return () => clearInterval(timer)
|
||||
}
|
||||
|
||||
function snapshot(zh) {
|
||||
const L = (a, b) => (zh ? a : b)
|
||||
const cfg = loadConfig()
|
||||
const token = readToken()
|
||||
const roots = discoverRoots(cfg.roots, DSH_HOME)
|
||||
const projects = findProjects(roots)
|
||||
const items = projects.slice(0, 12).map((p) => {
|
||||
const rec = cfg.repos[p.dir]
|
||||
return {
|
||||
title: p.name.slice(0, 40),
|
||||
subtitle: rec
|
||||
? L(`已上传 ${rec.files ?? 0} 个文件`, `pushed ${rec.files ?? 0} files`)
|
||||
: L('还没上传过', 'not pushed yet'),
|
||||
trailing: rec ? ago(rec.lastPush, zh) : L('未上传', 'never'),
|
||||
tone: rec ? 'good' : 'muted',
|
||||
icon: 'cloud',
|
||||
action: { id: 'push', args: { path: p.dir } }
|
||||
}
|
||||
})
|
||||
const more = projects.length > 12 ? L(`,还有 ${projects.length - 12} 个`, `, +${projects.length - 12}`) : ''
|
||||
const running = job !== null && job.running
|
||||
const recent = job !== null && !job.running && job.finishedAt > 0 && Date.now() - job.finishedAt < 10 * 60 * 1000
|
||||
let jobPct = 0
|
||||
let jobLabel = L('就绪', 'Ready')
|
||||
let jobCaption = ''
|
||||
let jobTone = 'info'
|
||||
if (running) {
|
||||
jobPct = job.total > 0 ? Math.round((job.done / job.total) * 100) : 0
|
||||
jobLabel = L(`上传中:${job.current}`, `Pushing ${job.current}`)
|
||||
jobCaption = `${job.done}/${job.total}`
|
||||
jobTone = 'info'
|
||||
} else if (recent) {
|
||||
jobPct = 100
|
||||
const failed = job.results.filter((r) => !r.ok).length
|
||||
jobLabel = failed === 0 ? L('上传完成', 'Pushed') : L(`失败 ${failed} 个`, `${failed} failed`)
|
||||
const last = job.results[job.results.length - 1]
|
||||
jobCaption = failed === 0
|
||||
? (job.results.map((r) => r.name).join(' · ').slice(0, 80) || '')
|
||||
: (job.results.find((r) => !r.ok)?.message ?? '')
|
||||
jobTone = failed === 0 ? 'good' : 'bad'
|
||||
} else if (lastError !== '') {
|
||||
jobLabel = L('上次失败', 'Last failed')
|
||||
jobCaption = lastError.slice(0, 100)
|
||||
jobTone = 'bad'
|
||||
} else {
|
||||
jobCaption = L('点下面的项目可单独上传', 'Tap a project to push it')
|
||||
}
|
||||
|
||||
let hint
|
||||
let hintTone
|
||||
if (!gitAvailable()) {
|
||||
hint = L('这台机器上没有 git,上传用不了。', 'git is missing on this host.')
|
||||
hintTone = 'bad'
|
||||
} else if (token === '') {
|
||||
hint = L('还没有配置 GitHub 令牌,先点「令牌步骤」。', 'No GitHub token yet. Use "Token steps".')
|
||||
hintTone = 'warn'
|
||||
} else if (projects.length === 0) {
|
||||
hint = L('工作区里还没检测到项目。', 'No project found in the workspaces.')
|
||||
hintTone = 'info'
|
||||
} else {
|
||||
hint = L(`检测到 ${projects.length} 个项目${more}。第一次上传会自动建仓库。`, `${projects.length} project(s)${more}. The first push creates the repo.`)
|
||||
hintTone = 'good'
|
||||
}
|
||||
|
||||
return {
|
||||
hint,
|
||||
hintTone,
|
||||
account: cfg.login !== '' ? cfg.login : (token !== '' ? L('令牌已写入(待校验)', 'Token saved') : L('未配置', 'none')),
|
||||
visibility: cfg.private ? L('私有', 'Private') : L('公开', 'Public'),
|
||||
autoText: cfg.auto ? L('每轮结束 · 开', 'on, per turn') : L('手动', 'manual'),
|
||||
rootsText: roots.map((r) => r.replace(/^\/root\//, '~/')).join(' · ').slice(0, 48) || '—',
|
||||
projects: items,
|
||||
emptyHint: projects.length === 0 ? L('把 App 建在工作区里,刷新就能看到。', 'Build the app inside a workspace, then refresh.') : '',
|
||||
jobPct,
|
||||
jobLabel,
|
||||
jobCaption,
|
||||
jobTone,
|
||||
autoValue: cfg.auto ? 'on' : 'off',
|
||||
privateValue: cfg.private ? 'private' : 'public',
|
||||
tokenHint: token === ''
|
||||
? L('绑定令牌:先在 GitHub 复制令牌,再点输入框上方的「绑定令牌」,会自动从剪贴板读取并保存在本机(权限 600)。', 'Copy the token on GitHub, then tap "Token" above the composer — it reads the clipboard and saves locally (mode 600).')
|
||||
: L('令牌已就绪,点项目行即可上传。', 'Token ready — tap a project to push.')
|
||||
}
|
||||
}
|
||||
|
||||
function pickValue(event) {
|
||||
const value = event?.value
|
||||
if (typeof value === 'string') return value
|
||||
if (value !== null && typeof value === 'object') {
|
||||
if (typeof value.value === 'string') return value.value
|
||||
if (typeof value.selected === 'string') return value.selected
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
const actions = {
|
||||
pushAll(_scope, _event) {
|
||||
const cfg = loadConfig()
|
||||
if (readToken() === '') return { toast: '先配置 GitHub 令牌' }
|
||||
const projects = findProjects(discoverRoots(cfg.roots, DSH_HOME))
|
||||
if (projects.length === 0) return { toast: '没有可上传的项目' }
|
||||
if (job?.running) return { toast: '已有上传任务在跑' }
|
||||
startJob(projects, '', {})
|
||||
return { toast: `开始上传 ${projects.length} 个项目` }
|
||||
},
|
||||
push(_scope, event) {
|
||||
const path = typeof event?.value?.path === 'string' ? event.value.path : ''
|
||||
if (path === '') return { toast: '没找到项目路径' }
|
||||
if (readToken() === '') return { toast: '先配置 GitHub 令牌' }
|
||||
if (job?.running) return { toast: '已有上传任务在跑' }
|
||||
startJob([{ dir: path, name: projectName(path) }], '', {})
|
||||
return { toast: `开始上传 ${projectName(path)}` }
|
||||
},
|
||||
refresh() {
|
||||
return { refresh: true }
|
||||
},
|
||||
autoMode(_scope, event) {
|
||||
const value = pickValue(event)
|
||||
if (value !== 'on' && value !== 'off') return { refresh: true }
|
||||
const cfg = loadConfig()
|
||||
cfg.auto = value === 'on'
|
||||
saveConfig(cfg)
|
||||
return { toast: cfg.auto ? '自动上传已开启' : '自动上传已关闭', refresh: true }
|
||||
},
|
||||
visibility(_scope, event) {
|
||||
const value = pickValue(event)
|
||||
if (value !== 'private' && value !== 'public') return { refresh: true }
|
||||
const cfg = loadConfig()
|
||||
cfg.private = value === 'private'
|
||||
saveConfig(cfg)
|
||||
return { toast: cfg.private ? '新仓库默认私有' : '新仓库默认公开', refresh: true }
|
||||
},
|
||||
tokenHelp() {
|
||||
return { copy: TOKEN_COMMAND, toast: '命令已复制' }
|
||||
},
|
||||
openTokens() {
|
||||
return { link: 'https://github.com/settings/tokens/new?scopes=repo&description=dsh-go-upload' }
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 胶囊 / 自动
|
||||
|
||||
function capsulePush(scope) {
|
||||
if (readToken() === '') return { toast: '先配置 GitHub 令牌', open: 'panel:github' }
|
||||
const cfg = loadConfig()
|
||||
const projects = findProjects(discoverRoots(cfg.roots, DSH_HOME))
|
||||
if (projects.length === 0) return { toast: '工作区里没有项目' }
|
||||
if (job?.running) return { toast: '已有上传任务在跑' }
|
||||
if (projects.length > 1) {
|
||||
return { toast: `有 ${projects.length} 个项目,请选择`, open: 'panel:github' }
|
||||
}
|
||||
const draft = typeof scope?.draft === 'string' ? scope.draft.trim() : ''
|
||||
startJob([{ dir: projects[0].dir, name: projects[0].name }], draft.slice(0, 120), {})
|
||||
return { toast: `开始上传 ${projects[0].name}`.slice(0, 40) }
|
||||
}
|
||||
|
||||
const TOKEN_RE = /^(ghp_|github_pat_|gho_|ghs_|ghu_)[A-Za-z0-9_]{20,255}$/
|
||||
|
||||
/** 从剪贴板里找令牌并保存;顺便后台校验一次。 */
|
||||
function capsuleToken(scope) {
|
||||
const clip = typeof scope?.clipboard === 'string' ? scope.clipboard.trim() : ''
|
||||
if (clip === '') return { toast: '剪贴板是空的,先复制令牌' }
|
||||
const parts = clip.split(/[\s'"]+/).filter(Boolean)
|
||||
const token = parts.find((p) => TOKEN_RE.test(p)) ?? (/^[A-Za-z0-9_]{30,255}$/.test(clip) ? clip : '')
|
||||
if (token === '') return { toast: '剪贴板里没有 GitHub 令牌' }
|
||||
try {
|
||||
writeToken(token)
|
||||
} catch (error) {
|
||||
return { toast: '写入令牌失败,看终端权限' }
|
||||
}
|
||||
lastError = ''
|
||||
void (async () => {
|
||||
try {
|
||||
const login = await getLogin(token)
|
||||
const cfg = loadConfig()
|
||||
cfg.login = login
|
||||
saveConfig(cfg)
|
||||
refreshPanels()
|
||||
} catch (error) {
|
||||
lastError = friendly(error)
|
||||
refreshPanels()
|
||||
}
|
||||
})()
|
||||
return { toast: '令牌已保存,点上传试试' }
|
||||
}
|
||||
|
||||
function noteText(zh) {
|
||||
const L = (a, b) => (zh ? a : b)
|
||||
if (readToken() === '') return L('未配置令牌', 'No token')
|
||||
if (job !== null && job.running) return L(`上传中 ${job.done}/${job.total}`, `Pushing ${job.done}/${job.total}`)
|
||||
if (job !== null && job.finishedAt > 0 && Date.now() - job.finishedAt < 5 * 60 * 1000) {
|
||||
return job.ok ? L('已传 GitHub', 'Pushed') : L('上传失败', 'Push failed')
|
||||
}
|
||||
const cfg = loadConfig()
|
||||
const last = Object.values(cfg.repos).reduce((max, rec) => Math.max(max, Number(rec?.lastPush) || 0), 0)
|
||||
if (last > 0) return L(`已同步 · ${ago(last, true)}`, `Synced ${ago(last, false)}`)
|
||||
return lastError !== '' ? L('上传失败', 'Push failed') : L('还没有上传', 'Not pushed')
|
||||
}
|
||||
|
||||
function noteData(scope, emit, caps) {
|
||||
const zh = !String(caps?.locale ?? '').toLowerCase().startsWith('en')
|
||||
const key = String(scope?.turnId ?? '1')
|
||||
const send = () => {
|
||||
const text = noteText(zh)
|
||||
if (text !== '') emit({ [key]: { text: text.slice(0, 16), tone: lastError !== '' ? 'warn' : 'muted' } })
|
||||
}
|
||||
send()
|
||||
const timer = setInterval(send, 5000)
|
||||
timer.unref?.()
|
||||
return () => clearInterval(timer)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 自动上传
|
||||
|
||||
let autoTimer = null
|
||||
let autoCwd = ''
|
||||
let autoSince = 0
|
||||
|
||||
function scheduleAuto(cwd, since) {
|
||||
const cfg = loadConfig()
|
||||
if (!cfg.auto) return
|
||||
if (readToken() === '') return
|
||||
autoCwd = cwd
|
||||
autoSince = since
|
||||
if (autoTimer !== null) clearTimeout(autoTimer)
|
||||
autoTimer = setTimeout(runAuto, 5000)
|
||||
autoTimer.unref?.()
|
||||
}
|
||||
|
||||
function runAuto() {
|
||||
autoTimer = null
|
||||
try {
|
||||
if (readToken() === '' || autoCwd === '') return
|
||||
const cfg = loadConfig()
|
||||
if (!cfg.auto) return
|
||||
if (job?.running) { autoTimer = setTimeout(runAuto, 15000); autoTimer.unref?.(); return }
|
||||
const dirs = changedProjects(autoCwd, autoSince, cfg.roots)
|
||||
const targets = dirs.map((dir) => ({ dir, name: projectName(dir) }))
|
||||
if (targets.length === 0) return
|
||||
startJob(targets, cfg.description, { auto: true })
|
||||
} catch (error) {
|
||||
lastError = friendly(error)
|
||||
}
|
||||
}
|
||||
|
||||
export function apply(ctx) {
|
||||
ctx.inject(['dshGo'], (host) => {
|
||||
bridge = host.dshGo
|
||||
host.dshGo.panel('github', { view: panelView, data: panelData, actions })
|
||||
host.dshGo.on('push', capsulePush)
|
||||
host.dshGo.on('token', capsuleToken)
|
||||
host.dshGo.turnNote('sync', noteData)
|
||||
})
|
||||
|
||||
// 记录每轮开始时间与所在工作区;轮次结束只推送本轮改过的项目。
|
||||
ctx.on('session/event', (session, event) => {
|
||||
try {
|
||||
if (event === null || typeof event.type !== 'string') return
|
||||
const header = session?.header
|
||||
const cwd = header?.cwd
|
||||
if (typeof cwd !== 'string' || cwd === '') return
|
||||
if (header?.origin === 'subagent' || (header?.delegationDepth ?? 0) > 0) return
|
||||
if (event.type === 'turn/start') {
|
||||
turns.set(session.id, { cwd, since: Date.now() - 3000 })
|
||||
} else if (event.type === 'turn/end') {
|
||||
const rec = turns.get(session.id)
|
||||
turns.delete(session.id)
|
||||
scheduleAuto(rec?.cwd ?? cwd, rec?.since ?? Date.now() - 600000)
|
||||
}
|
||||
} catch {}
|
||||
})
|
||||
}
|
||||
|
||||
const turns = new Map()
|
||||
|
||||
export { uploadOne, snapshot }
|
||||
Reference in new issue
Block a user