160 lines
6.7 KiB
JavaScript
160 lines
6.7 KiB
JavaScript
// 本机 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 }
|
||
}
|