Files

177 lines
6.9 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.
#!/usr/bin/env node
// 把本机所有项目仓库推到你自己的 Gitea(默认建成私有库)
//
// node push-all.mjs --url http://1.2.3.4:3000 --user gitea --token <令牌>
// node push-all.mjs --url http://1.2.3.4:3000 --user gitea --token <令牌> --dry
//
// 令牌在 Gitea 里生成:右上角头像 → 设置 → 应用 → 生成令牌,
// 勾上「写: 仓库」和「写: 用户」。也可以直接用管理员账号密码登录网页后创建。
//
// 行为:
// · 扫描 --dirs(默认 /root/workspace 下每个子目录)
// · 没有 .git 的先 init + commit(.gitignore 已存在就用,不存在补一个基本的)
// · 在 Gitea 里用同名建私有仓库(已存在就复用)
// · 远端名用 gitea,不覆盖原来的 origin(GitHub 那边还能留着)
// · 推 main 分支和所有标签
import { spawnSync } from 'node:child_process'
import { existsSync, readdirSync, statSync, writeFileSync } from 'node:fs'
import { basename, join } from 'node:path'
import { homedir } from 'node:os'
const argv = process.argv.slice(2)
const opt = (name, def = '') => {
const i = argv.indexOf(`--${name}`)
return i >= 0 && argv[i + 1] ? argv[i + 1] : def
}
const flag = (name) => argv.includes(`--${name}`)
const URL_BASE = opt('url', process.env.GITEA_URL || '').replace(/\/+$/, '')
const USER = opt('user', process.env.GITEA_USER || '')
const TOKEN = opt('token', process.env.GITEA_TOKEN || '')
const ROOT = opt('dirs', join(homedir(), 'workspace'))
const REMOTE = opt('remote', 'gitea')
const DRY = flag('dry')
if (!URL_BASE || !USER || !TOKEN) {
console.error('用法:node push-all.mjs --url http://服务器:3000 --user 用户名 --token 令牌 [--dirs 目录] [--dry]')
process.exit(2)
}
const log = (...a) => console.log(...a)
const dim = (s) => `\x1b[2m${s}\x1b[0m`
const green = (s) => `\x1b[32m${s}\x1b[0m`
const red = (s) => `\x1b[31m${s}\x1b[0m`
const cyan = (s) => `\x1b[36m${s}\x1b[0m`
const git = (dir, args, { allowFail = false } = {}) => {
const r = spawnSync('git', ['-C', dir, ...args], {
encoding: 'utf8',
env: {
...process.env,
GIT_TERMINAL_PROMPT: '0',
GIT_AUTHOR_NAME: process.env.GIT_AUTHOR_NAME || USER,
GIT_AUTHOR_EMAIL: process.env.GIT_AUTHOR_EMAIL || `${USER}@gitea.local`,
GIT_COMMITTER_NAME: process.env.GIT_COMMITTER_NAME || USER,
GIT_COMMITTER_EMAIL: process.env.GIT_COMMITTER_EMAIL || `${USER}@gitea.local`,
},
})
if (r.status !== 0 && !allowFail) throw new Error((r.stderr || r.stdout || 'git 失败').trim())
return r
}
async function api(path, init = {}) {
const res = await fetch(`${URL_BASE}/api/v1${path}`, {
...init,
headers: {
Authorization: `token ${TOKEN}`,
'Content-Type': 'application/json',
...(init.headers || {}),
},
signal: AbortSignal.timeout(30000),
})
const text = await res.text()
let body = null
try { body = text ? JSON.parse(text) : null } catch { body = text }
return { ok: res.ok, status: res.status, body }
}
function ensureRepo(name) {
return api('/user/repos', {
method: 'POST',
body: JSON.stringify({ name, private: true, auto_init: false, default_branch: 'main' }),
}).then(async (r) => {
if (r.ok) return { created: true }
if (r.status === 409) return { created: false }
if (r.status === 422) {
// 已存在
const got = await api(`/repos/${USER}/${name}`)
if (got.ok) return { created: false }
}
throw new Error(`建仓库失败(${r.status}):${typeof r.body === 'string' ? r.body : JSON.stringify(r.body)}`)
})
}
function isProject(dir) {
try {
if (!statSync(dir).isDirectory()) return false
if (existsSync(join(dir, '.git'))) return true
const files = readdirSync(dir)
return files.some((f) => ['package.json', 'index.html', 'README.md', 'pyproject.toml', 'Cargo.toml', 'go.mod', 'composer.json'].includes(f))
} catch {
return false
}
}
function initRepo(dir) {
git(dir, ['init', '-q'])
git(dir, ['symbolic-ref', 'HEAD', 'refs/heads/main'], { allowFail: true })
if (!existsSync(join(dir, '.gitignore'))) {
writeFileSync(join(dir, '.gitignore'), [
'node_modules/', 'dist/', 'build/', '.env', '*.log', '.DS_Store',
'data/', 'data.*/', '*.db', '*.db-journal', '*.db-wal', '*.db-shm',
'__pycache__/', '.venv/', 'venv/', 'target/',
].join('\n') + '\n')
}
git(dir, ['add', '-A'])
git(dir, ['commit', '-q', '-m', '初始提交(迁移到 Gitea)'], { allowFail: true })
}
function pushRepo(dir, name) {
const authUrl = `${URL_BASE.replace('://', `://${encodeURIComponent(USER)}:${encodeURIComponent(TOKEN)}@`)}/${USER}/${name}.git`
// 远端只存干净地址,令牌只出现在这一次 push 的命令行里,不落盘
git(dir, ['remote', 'remove', REMOTE], { allowFail: true })
git(dir, ['remote', 'add', REMOTE, `${URL_BASE}/${USER}/${name}.git`])
const head = git(dir, ['rev-parse', '--verify', 'HEAD'], { allowFail: true })
if (head.status !== 0) return { pushed: false, files: 0, note: '空仓库,没有提交' }
const branch = git(dir, ['symbolic-ref', '--short', 'HEAD'], { allowFail: true }).stdout.trim() || 'main'
git(dir, ['push', '--quiet', authUrl, `HEAD:refs/heads/main`])
git(dir, ['push', '--quiet', authUrl, '--tags'], { allowFail: true })
const count = git(dir, ['ls-files'], { allowFail: true }).stdout.trim().split('\n').filter(Boolean).length
return { pushed: true, files: count, branch }
}
const dirs = (existsSync(ROOT) ? readdirSync(ROOT) : [])
.map((n) => join(ROOT, n))
.filter(isProject)
.filter((d) => basename(d) !== '.git')
if (!dirs.length) {
console.error(red(`在 ${ROOT} 下没找到项目目录`))
process.exit(1)
}
log(cyan(`Gitea:${URL_BASE} 账号:${USER} 待推:${dirs.length} 个`))
if (DRY) log(dim('(--dry:只看不改)'))
const rows = []
for (const dir of dirs) {
const name = basename(dir)
try {
if (!existsSync(join(dir, '.git'))) {
if (DRY) { rows.push([name, '将初始化', '—', '—']); continue }
initRepo(dir)
}
if (!DRY) {
const { created } = await ensureRepo(name)
const r = pushRepo(dir, name)
rows.push([name, created ? '新建私有库' : '已存在', r.pushed ? `${r.files} 个文件` : r.note, `${URL_BASE}/${USER}/${name}`])
} else {
rows.push([name, '将推送', '—', `${URL_BASE}/${USER}/${name}`])
}
} catch (err) {
rows.push([name, red('失败'), String(err.message || err).slice(0, 90), ''])
}
}
const w = (s) => [...s].reduce((n, ch) => n + (ch.charCodeAt(0) > 255 ? 2 : 1), 0)
const pad = (s, n) => s + ' '.repeat(Math.max(0, n - w(s)))
const width = [20, 12, 14].map((n, i) => Math.max(n, ...rows.map((r) => w(String(r[i])))))
log('')
for (const r of rows) {
log(`${pad(r[0], width[0])} ${pad(r[1], width[1])} ${pad(r[2], width[2])} ${dim(r[3])}`)
}
const okCount = rows.filter((r) => !String(r[1]).includes('失败')).length
log('')
log(green(`完成:${okCount}/${rows.length}`))