diff --git a/lib/git.js b/lib/git.js index 55be98f..65c06aa 100644 --- a/lib/git.js +++ b/lib/git.js @@ -1,6 +1,8 @@ // 本机 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 = '' } = {}) { @@ -76,9 +78,28 @@ function run(dir, args, { token = '', login = '', url = '', timeoutMs = 180000 } }) } +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) { - const r = await run(dir, ['rev-parse', '--is-inside-work-tree']).catch(() => null) - return r?.code === 0 && r.stdout === 'true' + 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) {