初始化: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

+159
View File
@@ -0,0 +1,159 @@
// 本机 git 操作:init / add / commit / push。令牌只通过环境变量里的 http.extraheader 传递,
// 不落进 .git/config、命令行参数或日志。
import { spawn, spawnSync } from 'node:child_process'
export class GitError extends Error {
constructor(message, { code = 0, stderr = '' } = {}) {
super(message)
this.name = 'GitError'
this.code = code
this.stderr = stderr
}
}
let gitPath
export function gitAvailable() {
if (gitPath !== undefined) return gitPath
try {
const r = spawnSync('git', ['--version'], { stdio: 'ignore', timeout: 5000 })
gitPath = r.status === 0 ? 'git' : null
} catch {
gitPath = null
}
return gitPath
}
function run(dir, args, { token = '', login = '', timeoutMs = 180000 } = {}) {
return new Promise((resolve, reject) => {
const env = {
...process.env,
GIT_TERMINAL_PROMPT: '0',
GIT_AUTHOR_NAME: login || 'dsh-go',
GIT_AUTHOR_EMAIL: login ? `${login}@users.noreply.github.com` : 'dsh-go@users.noreply.github.com',
GIT_COMMITTER_NAME: login || 'dsh-go',
GIT_COMMITTER_EMAIL: login ? `${login}@users.noreply.github.com` : 'dsh-go@users.noreply.github.com'
}
if (token !== '') {
const basic = Buffer.from(`${login || 'x-access-token'}:${token}`, 'utf8').toString('base64')
env.GIT_CONFIG_COUNT = '1'
env.GIT_CONFIG_KEY_0 = 'http.https://github.com/.extraheader'
env.GIT_CONFIG_VALUE_0 = `Authorization: Basic ${basic}`
}
let child
try {
child = spawn('git', ['-C', dir, ...args], { env, stdio: ['ignore', 'pipe', 'pipe'] })
} catch (error) {
reject(new GitError(`无法启动 git:${error?.message ?? error}`, { code: -1 }))
return
}
let stdout = ''
let stderr = ''
const timer = setTimeout(() => {
try { child.kill('SIGTERM') } catch {}
reject(new GitError('git 操作超时(3 分钟),可能是网络太慢。', { code: -2 }))
}, timeoutMs)
timer.unref?.()
child.stdout.on('data', (d) => { if (stdout.length < 400000) stdout += d })
child.stderr.on('data', (d) => { if (stderr.length < 400000) stderr += d })
child.on('error', (error) => {
clearTimeout(timer)
reject(new GitError(`无法运行 git:${error?.message ?? error}`, { code: -1 }))
})
child.on('close', (code) => {
clearTimeout(timer)
resolve({ code: code ?? 0, stdout: stdout.trim(), stderr: stderr.trim() })
})
})
}
export async function isRepo(dir) {
const r = await run(dir, ['rev-parse', '--is-inside-work-tree']).catch(() => null)
return r?.code === 0 && r.stdout === 'true'
}
export async function initRepo(dir) {
const r = await run(dir, ['init', '-q'])
if (r.code !== 0) throw new GitError(`git init 失败:${r.stderr || r.stdout}`, { code: r.code, stderr: r.stderr })
await run(dir, ['symbolic-ref', 'HEAD', 'refs/heads/main']).catch(() => {})
}
export async function hasCommits(dir) {
const r = await run(dir, ['rev-parse', '--verify', 'HEAD']).catch(() => null)
return r?.code === 0
}
export async function remoteUrl(dir) {
const r = await run(dir, ['remote', 'get-url', 'origin']).catch(() => null)
return r?.code === 0 ? r.stdout : ''
}
export async function setRemote(dir, url) {
const current = await remoteUrl(dir)
if (current === url) return
const r = current === ''
? await run(dir, ['remote', 'add', 'origin', url])
: await run(dir, ['remote', 'set-url', 'origin', url])
if (r.code !== 0) throw new GitError(`设置 git 远程地址失败:${r.stderr || r.stdout}`, { code: r.code, stderr: r.stderr })
}
export async function dirtyCount(dir) {
if (!(await isRepo(dir))) return 0
const r = await run(dir, ['status', '--porcelain'])
if (r.code !== 0) return 0
return r.stdout === '' ? 0 : r.stdout.split('\n').filter(Boolean).length
}
function friendlyPushError(stderr) {
const text = String(stderr || '')
if (/Authentication failed|could not read Username|403|Permission to .* denied|repository not found/i.test(text)) {
return '推送被 GitHub 拒绝:令牌没有 repo 权限,或令牌已失效。请重新生成令牌(勾选 repo)后重试。'
}
if (/Could not resolve host|unable to access|Connection (timed out|refused)|Failed to connect/i.test(text)) {
return '连不上 GitHub,请检查网络后重试。'
}
if (/exceeds GitHub's file size limit|GH001/i.test(text)) {
return '仓库里有单个文件超过 GitHub 的 100MB 限制,请先把这个文件排除掉。'
}
if (/non-fast-forward|fetch first|rejected/i.test(text)) {
return '远端仓库已有新提交,自动合并失败。请先在面板点一次上传重试,或手动处理冲突。'
}
return `推送失败:${text.split('\n').filter(Boolean).slice(-2).join(' ')}`
}
/**
* 提交并推送一个项目目录。
* @returns {{ commit: string, url: string, files: number, pushed: boolean }}
*/
export async function commitAndPush(dir, { url, token, login, message, timeoutMs = 180000 }) {
if (!gitAvailable()) throw new GitError('这台机器上没有 git,无法上传。')
if (!(await isRepo(dir))) await initRepo(dir)
await setRemote(dir, url)
const add = await run(dir, ['add', '-A'])
if (add.code !== 0) throw new GitError(`git add 失败:${add.stderr || add.stdout}`, { code: add.code, stderr: add.stderr })
const staged = await run(dir, ['diff', '--cached', '--name-only'])
const files = staged.code === 0 && staged.stdout !== '' ? staged.stdout.split('\n').filter(Boolean).length : 0
const commit = await run(dir, [
'-c', `user.name=${login || 'dsh-go'}`,
'-c', `user.email=${login ? `${login}@users.noreply.github.com` : 'dsh-go@users.noreply.github.com'}`,
'commit', '-q', '-m', message
])
const nothing = commit.code !== 0
if (nothing && !/nothing to commit|no changes added|empty commit/i.test(commit.stderr + commit.stdout)) {
throw new GitError(`git commit 失败:${commit.stderr || commit.stdout}`, { code: commit.code, stderr: commit.stderr })
}
let push = await run(dir, ['push', '-q', '-u', 'origin', 'HEAD:refs/heads/main'], { token, login, timeoutMs })
if (push.code !== 0 && /non-fast-forward|fetch first|rejected/i.test(push.stderr)) {
await run(dir, ['fetch', '-q', 'origin', 'main'], { token, login, timeoutMs }).catch(() => {})
await run(dir, ['rebase', '-q', '--autostash', 'origin/main'], { token, login, timeoutMs }).catch(() => {})
push = await run(dir, ['push', '-q', '-u', 'origin', 'HEAD:refs/heads/main'], { token, login, timeoutMs })
}
if (push.code !== 0) throw new GitError(friendlyPushError(push.stderr), { code: push.code, stderr: push.stderr })
const head = await run(dir, ['rev-parse', '--short', 'HEAD']).catch(() => null)
const commitHash = head?.code === 0 ? head.stdout : ''
return { commit: commitHash, files, pushed: true }
}
+82
View File
@@ -0,0 +1,82 @@
// GitHub REST 调用:校验令牌、取账号、按需创建仓库。只用原生 fetch。
const API = (process.env.DSH_GITHUB_API || 'https://api.github.com').replace(/\/+$/, '')
const UA = 'dsh-go-github-upload/0.1'
export class GitHubError extends Error {
constructor(message, { status = 0, code = '' } = {}) {
super(message)
this.name = 'GitHubError'
this.status = status
this.code = code
}
}
function headers(token, extra = {}) {
return {
accept: 'application/vnd.github+json',
authorization: `Bearer ${token}`,
'x-github-api-version': '2022-11-28',
'user-agent': UA,
...extra
}
}
async function request(path, { token, method = 'GET', body, timeoutMs = 25000 } = {}) {
let res
try {
res = await fetch(`${API}${path}`, {
method,
headers: headers(token, body === undefined ? {} : { 'content-type': 'application/json' }),
body: body === undefined ? undefined : JSON.stringify(body),
signal: AbortSignal.timeout(timeoutMs)
})
} catch (error) {
const reason = error?.name === 'TimeoutError' ? '请求超时' : '连不上 GitHub'
throw new GitHubError(`${reason},请检查手机网络(GitHub 在国内可能不稳定),或稍后重试。`, { code: 'network' })
}
const text = await res.text().catch(() => '')
let json = null
try { json = text === '' ? null : JSON.parse(text) } catch {}
if (res.ok) return json
const detail = typeof json?.message === 'string' ? json.message : text.slice(0, 200)
if (res.status === 401) throw new GitHubError('GitHub 令牌无效或已过期,请重新生成令牌。', { status: 401, code: 'bad-token' })
if (res.status === 403) {
const limited = String(json?.message || '').toLowerCase().includes('rate limit')
throw new GitHubError(limited ? 'GitHub 接口被限流,过一会儿再试。' : `GitHub 拒绝了这个操作(403):${detail}`, { status: 403, code: limited ? 'rate-limit' : 'forbidden' })
}
if (res.status === 404) throw new GitHubError(`找不到 GitHub 资源(404):${detail}`, { status: 404, code: 'not-found' })
if (res.status === 422) throw new GitHubError(`GitHub 不接受这次请求(422):${detail}`, { status: 422, code: 'invalid' })
throw new GitHubError(`GitHub 返回 ${res.status}:${detail}`, { status: res.status, code: 'http' })
}
/** 校验令牌并返回账号名。 */
export async function getLogin(token) {
const me = await request('/user', { token })
if (typeof me?.login !== 'string' || me.login === '') throw new GitHubError('GitHub 没有返回账号名,令牌可能权限不足。', { code: 'bad-token' })
return me.login
}
/** 保证仓库存在;已存在就复用。返回 { url, cloneUrl, created }。 */
export async function ensureRepo({ token, login, name, privateRepo = true, description = '' }) {
try {
const repo = await request('/user/repos', {
token,
method: 'POST',
body: { name, description: description.slice(0, 350), private: privateRepo, auto_init: false, has_issues: true, has_wiki: false }
})
return { url: repo.html_url, cloneUrl: repo.clone_url, created: true }
} catch (error) {
if (!(error instanceof GitHubError) || error.status !== 422) throw error
// 同名仓库已存在:复用(可能是之前上传过的)。
let repo
try {
repo = await request(`/repos/${login}/${name}`, { token })
} catch (inner) {
throw new GitHubError(`仓库名 ${name} 已被占用且无法访问,请改名后重试。`, { code: 'name-taken' })
}
if (repo?.full_name?.toLowerCase() !== `${login}/${name}`.toLowerCase()) {
throw new GitHubError(`仓库名 ${name} 已被其它账号占用。`, { code: 'name-taken' })
}
return { url: repo.html_url, cloneUrl: repo.clone_url, created: false }
}
}
+257
View File
@@ -0,0 +1,257 @@
// 项目发现、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-<hash>。 */
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 = '<!-- dsh-go:auto-readme -->'
/** 生成/更新 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
}
+71
View File
@@ -0,0 +1,71 @@
// 本机配置:$DSH_HOME/dsh-go/github-upload.json(不含令牌)
// 令牌单独放 $DSH_HOME/dsh-go/github-token,权限 600,绝不写进视图或插件代码。
import { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync, existsSync } from 'node:fs'
import { homedir } from 'node:os'
import { join } from 'node:path'
export const DSH_HOME = process.env.DSH_HOME || join(homedir(), '.dsh')
export const CONFIG_DIR = join(DSH_HOME, 'dsh-go')
export const CONFIG_PATH = join(CONFIG_DIR, 'github-upload.json')
export const TOKEN_PATH = join(CONFIG_DIR, 'github-token')
export function emptyConfig() {
return { login: '', private: true, auto: false, roots: [], description: '', repos: {} }
}
export function loadConfig() {
let raw
try {
raw = JSON.parse(readFileSync(CONFIG_PATH, 'utf8'))
} catch {
return emptyConfig()
}
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return emptyConfig()
const cfg = { ...emptyConfig(), ...raw }
if (!cfg.repos || typeof cfg.repos !== 'object' || Array.isArray(cfg.repos)) cfg.repos = {}
if (!Array.isArray(cfg.roots)) cfg.roots = []
cfg.private = cfg.private !== false
cfg.auto = cfg.auto === true
return cfg
}
export function saveConfig(cfg) {
mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 })
const tmp = `${CONFIG_PATH}.${process.pid}.tmp`
writeFileSync(tmp, JSON.stringify(cfg, null, 2), { mode: 0o600 })
renameSync(tmp, CONFIG_PATH)
try { chmodSync(CONFIG_PATH, 0o600) } catch {}
}
/** 令牌优先级:环境变量 > 本机令牌文件。 */
export function readToken() {
const env = (process.env.GITHUB_TOKEN || process.env.GH_TOKEN || '').trim()
if (env !== '') return env
try {
if (!existsSync(TOKEN_PATH)) return ''
return readFileSync(TOKEN_PATH, 'utf8').trim()
} catch {
return ''
}
}
export function writeToken(token) {
mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 })
const tmp = `${TOKEN_PATH}.${process.pid}.tmp`
writeFileSync(tmp, `${String(token).trim()}\n`, { mode: 0o600 })
renameSync(tmp, TOKEN_PATH)
try { chmodSync(TOKEN_PATH, 0o600) } catch {}
}
/** 相对时间,短:刚刚 / 5 分钟前 / 3 小时前 / 2 天前。 */
export function ago(ms, zh = true) {
if (!Number.isFinite(ms) || ms <= 0) return zh ? '从未' : 'never'
const diff = Math.max(0, Date.now() - ms)
const min = Math.floor(diff / 60000)
if (min < 1) return zh ? '刚刚' : 'just now'
if (min < 60) return zh ? `${min} 分钟前` : `${min} min ago`
const hour = Math.floor(min / 60)
if (hour < 24) return zh ? `${hour} 小时前` : `${hour} h ago`
const day = Math.floor(hour / 24)
return zh ? `${day} 天前` : `${day} d ago`
}
+66
View File
@@ -0,0 +1,66 @@
// 上传一个项目:补 .gitignore/README → 建仓库 → 提交 → 推送 → 记录状态。
import { loadConfig, saveConfig, readToken } from './store.js'
import { repoName, projectName, ensureReadme, ensureGitignore } from './project.js'
import { getLogin, ensureRepo } from './github.js'
import { gitAvailable, commitAndPush } from './git.js'
export class UploadError extends Error {}
/** 把错误翻译成一句人话。 */
export function friendly(error) {
const message = error?.message ?? String(error)
if (/fetch failed|ENOTFOUND|ECONNREFUSED|ETIMEDOUT|EAI_AGAIN/i.test(message)) {
return '连不上 GitHub,请检查网络后重试。'
}
return message.length > 200 ? `${message.slice(0, 197)}…` : message
}
/** 读当前配置里的令牌;没有就抛出可直接展示的错误。 */
export function requireToken() {
const token = readToken()
if (token === '') {
throw new UploadError('还没有绑定 GitHub 令牌。先发 `/github token <你的令牌>`(令牌不会写进对话记录)。')
}
return token
}
export async function uploadOne(dir, { description = '' } = {}) {
const cfg = loadConfig()
const token = requireToken()
if (!gitAvailable()) throw new UploadError('这台机器上没有 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 同步`,
})
const when = new Date().toLocaleString('zh-CN', { hour12: false })
const head = description.trim() === '' ? `同步 ${projectName(dir)} 源码` : description.trim()
const result = await commitAndPush(dir, {
url: repo.cloneUrl,
token,
login,
message: `${head}\n\n由 DSH 自动上传 · ${when}`,
})
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, pushed: result.pushed }
}