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

+3
View File
@@ -0,0 +1,3 @@
node_modules/
.DS_Store
*.log
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+84
View File
@@ -0,0 +1,84 @@
# GitHub 同步(DSH 插件)
一个给 **DSH Web 界面**用的插件:在输入框里发 `/github`,就把当前项目的源码推上 GitHub,并自动生成一份带说明的 `README.md`。
没有按钮、没有弹窗,就是一条斜杠命令。
## 它做什么
- **建仓库**:第一次上传时自动在 GitHub 新建仓库(默认私有,可改公开),仓库名取自项目目录名
- **写说明**:自动生成 `README.md`,包含项目名、技术栈、目录结构、同步说明;你手写的 README 不会被覆盖
- **补忽略**:给项目补上 `.gitignore`(`node_modules`、`dist`、`.env` 之类),不把垃圾和密钥传上去
- **提交并推送**:提交信息带上时间,推送到 `main`
- **记状态**:记住每个项目的仓库地址、上次提交、文件数,用 `/github status` 随时查
## 命令
| 命令 | 作用 |
| --- | --- |
| `/github` | 上传当前工作区的项目 |
| `/github token ghp_xxx` | 绑定 GitHub 令牌(输入不写入对话记录) |
| `/github status` | 查令牌、账号、可见性、当前项目、上次上传 |
| `/github all` | 上传所有识别到的项目(最多 10 个) |
| `/github auto on` / `off` | 每轮对话结束后,自动上传本轮改过的项目 |
## 安装
```bash
dsh plugin --profile web add <本目录>
```
或者在本目录执行 `plugin_manager install_bundle`。安装后重开一个对话,在输入框里打 `/` 就能看到 **github** 命令。
## 令牌怎么来
手机上只能走浏览器(GitHub App 里没有这个页面):
```
https://github.com/settings/tokens/new?scopes=repo&description=dsh
```
Generate new token (classic) → 勾 `repo` → Generate → **点复制图标**(不要长按选文字,容易多粘几个字符)。
然后发:`/github token ghp_……`
令牌存在 `~/.dsh/dsh-go/github-token`(权限 600),不会写进仓库,也不会进对话记录。
## 配置与数据
| 路径 | 内容 |
| --- | --- |
| `~/.dsh/dsh-go/github-token` | 令牌(0600) |
| `~/.dsh/dsh-go/github-upload.json` | 账号、可见性、自动开关、各项目上次上传记录(0600) |
也可以直接用环境变量 `GITHUB_TOKEN` 提供令牌。
## 工作区怎么判定「项目」
从会话的工作目录往上找最多 4 层,命中这些标记之一就算项目根:
`package.json`、`pubspec.yaml`、`index.html`、`Cargo.toml`、`go.mod`、`requirements.txt`、`pyproject.toml`、`composer.json`、`build.gradle`、`Podfile`、`app.json`、`main.py`、`.git`
## 目录结构
```
github-sync/
├── index.js 插件入口,注册 /github 命令
├── cordis.patch.yml 安装补丁
├── lib/
│ ├── upload.js 一次上传的完整流程
│ ├── github.js GitHub API(建仓库、取账号)
│ ├── git.js git 命令封装(提交、推送、重试)
│ ├── project.js 项目识别、README/ignore 生成、目录树
│ └── store.js 配置与令牌读写
├── locale/ 中文 / English 文案
└── icon.svg
```
## 与 dsh-go 手机版插件的关系
同一个作者的手机原生插件(`local-github-upload`,带输入框上方胶囊和面板)和本插件**共用**同一份配置和令牌,两边可以混用。
## 许可
MIT
+3
View File
@@ -0,0 +1,3 @@
- insert:
- id: github-sync
name: '@local/github-sync'
+8
View File
@@ -0,0 +1,8 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
<rect width="64" height="64" rx="14" fill="#0f172a"/>
<path d="M20 44V22m0 10h12a5 5 0 0 1 5 5v7" fill="none" stroke="#7dd3fc" stroke-width="4" stroke-linecap="round"/>
<circle cx="20" cy="46" r="4" fill="#7dd3fc"/>
<circle cx="20" cy="20" r="4" fill="#7dd3fc"/>
<circle cx="37" cy="46" r="4" fill="#7dd3fc"/>
<path d="M44 18l6 6-6 6" fill="none" stroke="#38bdf8" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 510 B

+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),
})
}
+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 }
}
+6
View File
@@ -0,0 +1,6 @@
{
"meta": {
"title": "GitHub sync",
"description": "Type /github in the composer to push the project to GitHub with a generated README."
}
}
+6
View File
@@ -0,0 +1,6 @@
{
"meta": {
"title": "GitHub 同步",
"description": "输入框里发 /github 就把项目源码推上 GitHub,自动生成 README 说明。"
}
}
+17
View File
@@ -0,0 +1,17 @@
{
"name": "@local/github-sync",
"version": "1.0.0",
"private": true,
"type": "module",
"description": "把项目源码上传到 GitHub,并自动生成 README 说明",
"exports": {
".": "./index.js",
"./lib/*.js": "./lib/*.js",
"./locale/*.json": "./locale/*.json",
"./icon": "./icon.svg"
},
"files": ["index.js", "lib/*.js", "cordis.patch.yml", "locale/*.json", "icon.svg"],
"dsh": {
"bundle": { "patch": "./cordis.patch.yml" }
}
}