Files
dsh 25a5753aa9 fix(git): isRepo 只认目录自身为仓库根,避免把父仓库的 origin 与历史改掉
原先用 git rev-parse --is-inside-work-tree,在位于其他仓库内的子目录上会向上命中父仓库
并返回 true,导致 setRemote / add -A / rebase --autostash 全部作用在父仓库上。
改为:目录里有 .git 才算仓库;否则比较 --show-toplevel 与目录自身。
2026-11-18 20:36:27 +08:00

191 lines
7.8 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 本机 git 操作:init / add / commit / push。令牌只通过环境变量里的 http.extraheader 传递,
// 不落进 .git/config、命令行参数或日志。
import { spawn, spawnSync } from 'node:child_process'
import { existsSync } from 'node:fs'
import { join } from 'node:path'
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 hostOf(url) {
try { const u = new URL(String(url)); return `${u.protocol}//${u.host}/` } catch { return 'https://github.com/' }
}
function emailOf(login, scope) {
const host = String(scope).replace(/^https?:\/\//, '').replace(/\/$/, '') || 'localhost'
return login ? `${login}@users.noreply.${host}` : `dsh-go@${host}`
}
function run(dir, args, { token = '', login = '', url = '', timeoutMs = 180000 } = {}) {
const scope = hostOf(url)
return new Promise((resolve, reject) => {
const env = {
...process.env,
GIT_TERMINAL_PROMPT: '0',
GIT_AUTHOR_NAME: login || 'dsh-go',
GIT_AUTHOR_EMAIL: emailOf(login, scope),
GIT_COMMITTER_NAME: login || 'dsh-go',
GIT_COMMITTER_EMAIL: emailOf(login, scope)
}
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.${scope}.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() })
})
})
}
function normPath(p) {
return String(p || '').replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase()
}
/**
* 只有「这个目录自己就是仓库根」才算仓库。
* 旧实现用 `git rev-parse --is-inside-work-tree`:在别人仓库里的子目录上会向上命中父仓库并返回 true,
* 于是 setRemote / add -A / rebase 全落在父仓库上,把父仓库的 origin 和历史改掉。
*/
export async function isRepo(dir) {
if (existsSync(join(dir, '.git'))) return true
const r = await run(dir, ['rev-parse', '--show-toplevel']).catch(() => null)
if (r?.code !== 0 || !r.stdout) return false
return normPath(r.stdout) === normPath(dir)
}
/** 目标目录如果躺在别的仓库里,返回那个父仓库的根;否则返回 ''。 */
export async function outerRepo(dir) {
if (existsSync(join(dir, '.git'))) return ''
const r = await run(dir, ['rev-parse', '--show-toplevel']).catch(() => null)
if (r?.code !== 0 || !r.stdout) return ''
return normPath(r.stdout) === normPath(dir) ? '' : r.stdout
}
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 '推送被远端拒绝:令牌权限不足或已失效,请重新生成令牌后重试。'
}
if (/Could not resolve host|unable to access|Connection (timed out|refused)|Failed to connect/i.test(text)) {
return '连不上远端仓库,请检查网络后重试。'
}
if (/exceeds GitHub's file size limit|GH001/i.test(text)) {
return '仓库里有单个文件超过远端的 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=${emailOf(login, hostOf(url))}`,
'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, url, timeoutMs })
if (push.code !== 0 && /non-fast-forward|fetch first|rejected/i.test(push.stderr)) {
await run(dir, ['fetch', '-q', 'origin', 'main'], { token, login, url, timeoutMs }).catch(() => {})
await run(dir, ['rebase', '-q', '--autostash', 'origin/main'], { token, login, url, timeoutMs }).catch(() => {})
push = await run(dir, ['push', '-q', '-u', 'origin', 'HEAD:refs/heads/main'], { token, login, url, 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 }
}