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
+16
@@ -0,0 +1,16 @@
|
||||
# dsh-go 自动补充
|
||||
node_modules/
|
||||
dist/
|
||||
build/
|
||||
.venv/
|
||||
venv/
|
||||
__pycache__/
|
||||
*.pyc
|
||||
.DS_Store
|
||||
*.log
|
||||
.env
|
||||
.env.*
|
||||
.dart_tool/
|
||||
.next/
|
||||
.cache/
|
||||
coverage/
|
||||
@@ -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.
|
||||
@@ -0,0 +1,60 @@
|
||||
# local-github-upload
|
||||
|
||||
dsh-go 手机版插件:把工作区里做好的 App 源代码提交并推送到你的 GitHub,并在仓库里自动生成一份
|
||||
README 说明(项目名、说明、技术栈、目录结构)。
|
||||
|
||||
## 用起来
|
||||
|
||||
- **输入框上方的「上传 GitHub」胶囊**:只适用于工作区里只有一个项目的情况;有多个项目时会打开面板让你选。
|
||||
如果你的输入框里写了草稿,草稿会作为这次提交的说明。
|
||||
- **「GitHub 上传」面板**(对话详情页「插件」页签 / 对话页侧边 / 全部功能里):
|
||||
- 列出工作区里检测到的项目,点一行就单独上传它;
|
||||
- 「上传全部」一次推完;
|
||||
- 「自动上传」打开后,每轮对话结束只推送这一轮改过的项目(子代理的轮次不算)。
|
||||
- **回合脚注**:显示「未配置令牌 / 上传中 1/2 / 已传 GitHub / 已同步 · 3 分钟前」。
|
||||
|
||||
## 令牌
|
||||
|
||||
只需要一个带 `repo` 权限的 Personal Access Token(classic):
|
||||
|
||||
1. 面板里点「打开令牌页」,在 GitHub 上生成令牌(勾选 `repo`);
|
||||
2. 复制令牌;
|
||||
3. 写进本机文件(不会上传、不会进仓库):
|
||||
|
||||
```sh
|
||||
mkdir -p ~/.dsh/dsh-go && printf '%s' '你的令牌' > ~/.dsh/dsh-go/github-token && chmod 600 ~/.dsh/dsh-go/github-token
|
||||
```
|
||||
|
||||
也可以直接设置 `GITHUB_TOKEN` / `GH_TOKEN` 环境变量,优先级高于文件。
|
||||
|
||||
## 第一次上传会做什么
|
||||
|
||||
1. 补 `.gitignore`(node_modules、dist、.env 等);
|
||||
2. 生成 `README.md`:`# 项目名`、说明、技术栈、目录树、同步说明。
|
||||
已经手写的 README 不会被动;插件生成的 README 里带 `
|
||||
|
||||
<!-- dsh-go:auto-readme -->
|
||||
## 技术栈
|
||||
|
||||
- Node.js
|
||||
|
||||
## 项目结构
|
||||
|
||||
```text
|
||||
├── bin/
|
||||
│ ├── push.js
|
||||
│ └── token.js
|
||||
├── lib/
|
||||
│ ├── git.js
|
||||
│ ├── github.js
|
||||
│ ├── index.js
|
||||
│ ├── project.js
|
||||
│ └── store.js
|
||||
├── cordis.patch.yml
|
||||
├── LICENSE
|
||||
└── package.json
|
||||
```
|
||||
|
||||
## 同步说明
|
||||
|
||||
本文件由 dsh-go 自动生成;提交与推送都在本机完成,令牌不会写进仓库。
|
||||
Executable
+62
@@ -0,0 +1,62 @@
|
||||
#!/usr/bin/env node
|
||||
// 命令行上传:node bin/push.js [项目目录…] [--desc 说明] [--all]
|
||||
// 和面板走同一套逻辑(补 README、建仓库、提交、推送),不依赖 dsh-go 桥接。
|
||||
import { existsSync } from 'node:fs'
|
||||
import { resolve } from 'node:path'
|
||||
import { loadConfig, readToken } from '../lib/store.js'
|
||||
import { discoverRoots, findProjects, projectName } from '../lib/project.js'
|
||||
import { DSH_HOME } from '../lib/store.js'
|
||||
|
||||
const args = process.argv.slice(2)
|
||||
const dirs = []
|
||||
let description = ''
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
const a = args[i]
|
||||
if (a === '--desc' || a === '-d') description = args[++i] ?? ''
|
||||
else if (a === '--all') dirs.push('__all__')
|
||||
else if (a === '--help' || a === '-h') { printHelp(); process.exit(0) }
|
||||
else dirs.push(a)
|
||||
}
|
||||
|
||||
function printHelp() {
|
||||
console.log(`用法:node bin/push.js [目录…] [--desc "说明"] [--all]
|
||||
|
||||
目录 要上传的项目路径,默认当前目录
|
||||
--desc 这次提交的说明(也会在第一次生成 README 时用上)
|
||||
--all 上传工作区里检测到的所有项目
|
||||
`)
|
||||
}
|
||||
|
||||
const token = readToken()
|
||||
if (token === '') {
|
||||
console.error('还没有配置 GitHub 令牌。先运行:node bin/token.js')
|
||||
process.exit(2)
|
||||
}
|
||||
|
||||
let targets = []
|
||||
if (dirs.includes('__all__')) {
|
||||
targets = findProjects(discoverRoots(loadConfig().roots, DSH_HOME)).map((p) => p.dir)
|
||||
} else if (dirs.length === 0) {
|
||||
targets = [process.cwd()]
|
||||
} else {
|
||||
targets = dirs.map((d) => resolve(d))
|
||||
}
|
||||
|
||||
const { uploadOne } = await import('../lib/index.js')
|
||||
let failed = 0
|
||||
for (const dir of targets) {
|
||||
if (!existsSync(dir)) {
|
||||
console.error(`✗ ${dir} 不存在`)
|
||||
failed++
|
||||
continue
|
||||
}
|
||||
process.stdout.write(`→ ${projectName(dir)} … `)
|
||||
try {
|
||||
const rec = await uploadOne(dir, { description })
|
||||
console.log(`✓ ${rec.repo}${rec.created ? '(新建)' : ''} · ${rec.files} 个文件 · ${rec.url}`)
|
||||
} catch (error) {
|
||||
console.log(`✗ ${error?.message ?? error}`)
|
||||
failed++
|
||||
}
|
||||
}
|
||||
if (failed > 0) process.exitCode = 1
|
||||
Executable
+25
@@ -0,0 +1,25 @@
|
||||
#!/usr/bin/env node
|
||||
// 交互式写入 GitHub 令牌:在终端里运行,粘贴令牌后回车。令牌只写本机文件,权限 600。
|
||||
import { mkdirSync, writeFileSync, chmodSync } from 'node:fs'
|
||||
import { dirname, join } from 'node:path'
|
||||
|
||||
const home = process.env.DSH_HOME || join(process.env.HOME || '/root', '.dsh')
|
||||
const file = join(home, 'dsh-go', 'github-token')
|
||||
|
||||
process.stdout.write('把 GitHub 令牌粘贴到这里,然后按回车(只保存在本机):\n')
|
||||
let raw = ''
|
||||
process.stdin.setEncoding('utf8')
|
||||
process.stdin.on('data', (chunk) => { raw += chunk })
|
||||
process.stdin.on('end', () => {
|
||||
const token = raw.split('\n')[0].trim()
|
||||
if (!/^[A-Za-z0-9_]{20,255}$/.test(token)) {
|
||||
console.error('这看起来不像 GitHub 令牌(应该是一串 40 位左右的字母数字,可能以 ghp_ 开头),没有写入。')
|
||||
process.exitCode = 1
|
||||
return
|
||||
}
|
||||
mkdirSync(dirname(file), { recursive: true, mode: 0o700 })
|
||||
writeFileSync(file, `${token}\n`, { mode: 0o600 })
|
||||
chmodSync(file, 0o600)
|
||||
console.log(`已保存到 ${file}(权限 600,不会上传、不会进仓库)。`)
|
||||
console.log('回到 dsh-go 的「GitHub 上传」面板,点一下项目就能上传了。')
|
||||
})
|
||||
@@ -0,0 +1,4 @@
|
||||
# local dsh-go plugin: GitHub 上传
|
||||
- insert:
|
||||
- id: local-github-upload
|
||||
name: local-github-upload
|
||||
+159
@@ -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 }
|
||||
}
|
||||
@@ -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 }
|
||||
}
|
||||
}
|
||||
+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 }
|
||||
+257
@@ -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
|
||||
}
|
||||
@@ -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`
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
{
|
||||
"name": "local-github-upload",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "lib/index.js",
|
||||
"description": "把工作区里的 App 源码提交并推送到 GitHub,附自动生成的 README",
|
||||
"dsh": {
|
||||
"bundle": {
|
||||
"patch": "./cordis.patch.yml"
|
||||
}
|
||||
},
|
||||
"engines": {
|
||||
"dsh": ">=0.2.1-rc.2 <0.3.0-0"
|
||||
},
|
||||
"dshGo": {
|
||||
"v": 1,
|
||||
"title": {
|
||||
"zh": "GitHub 上传",
|
||||
"en": "GitHub upload"
|
||||
},
|
||||
"icon": "cloud",
|
||||
"wants": [
|
||||
"draft",
|
||||
"clipboard"
|
||||
],
|
||||
"contributes": {
|
||||
"composer.actions": [
|
||||
{
|
||||
"id": "push",
|
||||
"label": {
|
||||
"zh": "上传 GitHub",
|
||||
"en": "Push"
|
||||
},
|
||||
"icon": "cloud"
|
||||
},
|
||||
{
|
||||
"id": "token",
|
||||
"label": {
|
||||
"zh": "绑定令牌",
|
||||
"en": "Token"
|
||||
},
|
||||
"icon": "account"
|
||||
}
|
||||
],
|
||||
"panels": [
|
||||
{
|
||||
"id": "github",
|
||||
"title": {
|
||||
"zh": "GitHub 上传",
|
||||
"en": "GitHub upload"
|
||||
},
|
||||
"icon": "cloud",
|
||||
"placement": [
|
||||
"session.tab",
|
||||
"chat.panel",
|
||||
"features"
|
||||
]
|
||||
}
|
||||
],
|
||||
"turn.note": [
|
||||
{
|
||||
"id": "sync"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user