Files
ProjectDashboard/lib/git.js
2026-11-12 09:32:23 +01:00

98 lines
4.5 KiB
JavaScript
Raw 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 and backup status of one project: branch, remote, uncommitted changes,
// commits not pushed, last commit. `level` drives the traffic light in the UI.
const fs = require('fs')
const path = require('path')
const { run } = require('./proc')
// Git is optional (a friend's PC may not have it): checked once.
let gitOk = null
async function gitAvailable() {
if (gitOk === null) gitOk = (await run('git', ['--version'])).ok
return gitOk
}
async function gitInfo(projectPath) {
if (!fs.existsSync(path.join(projectPath, '.git'))) {
return { isRepo: false, level: 'red', label: 'kein Git', lastCommit: null }
}
if (!(await gitAvailable())) {
return { isRepo: true, level: 'red', label: 'Git nicht installiert', remote: '', branch: '', upstream: '', ahead: 0, behind: 0, dirty: 0, lastCommit: null }
}
const [st, rem, log] = await Promise.all([
run('git', ['-C', projectPath, '-c', 'core.quotepath=off', 'status', '--porcelain=v2', '--branch'], { timeout: 8000 }),
run('git', ['-C', projectPath, 'remote', '-v']),
run('git', ['-C', projectPath, 'log', '-1', '--format=%ad|%s', '--date=short']),
])
let branch = '', upstream = '', ahead = 0, behind = 0, dirty = 0
for (const line of st.stdout.split('\n')) {
if (!line) continue
if (line.startsWith('# branch.head ')) branch = line.slice(14).trim()
else if (line.startsWith('# branch.upstream ')) upstream = line.slice(18).trim()
else if (line.startsWith('# branch.ab ')) {
const m = line.match(/\+(\d+) -(\d+)/)
if (m) { ahead = +m[1]; behind = +m[2] }
} else if (!line.startsWith('#')) dirty++
}
const remoteLine = rem.stdout.split('\n').find((l) => l.startsWith('origin\t')) ?? rem.stdout.split('\n').find(Boolean)
const remote = remoteLine ? remoteLine.split('\t')[1].replace(/\s+\((fetch|push)\)$/, '') : ''
let lastCommit = null
const out = log.stdout.trim()
if (out) {
const [date, ...msg] = out.split('|')
lastCommit = { date, message: msg.join('|') }
}
const parts = []
if (dirty) parts.push(`${dirty} geändert`)
if (ahead) parts.push(`${ahead} nicht gepusht`)
if (behind) parts.push(`${behind} hinterher`)
let level, label
if (!remote) { level = 'red'; label = ['kein Remote (nur lokal)', ...parts].join(' · ') }
else if (!upstream) { level = 'yellow'; label = ['kein Upstream', ...parts].join(' · ') }
else if (dirty || ahead) { level = 'yellow'; label = parts.join(' · ') }
else { level = 'green'; label = behind ? parts.join(' · ') : 'gesichert' }
return { isRepo: true, branch, upstream, remote, ahead, behind, dirty, level, label, lastCommit }
}
// Remote URL as typed in the Info tab: SSH (git@host:user/repo.git, ssh://...) or https.
// Never starts with "-", so it can't be taken for a git option.
const REMOTE_RE = /^(?:[\w.-]+@[\w.-]+:[\w./~-]+|ssh:\/\/[^\s"'`]+|https?:\/\/[^\s"'`]+|git:\/\/[^\s"'`]+)$/
// Sets (or with '' removes) the "origin" remote.
async function setRemote(projectPath, url) {
if (!(await gitAvailable())) throw new Error('Git ist nicht installiert.')
if (!fs.existsSync(path.join(projectPath, '.git'))) throw new Error('Kein Git-Repository – erst „Git einrichten“.')
const u = String(url ?? '').trim()
const has = (await run('git', ['-C', projectPath, 'remote'])).stdout.split(/\r?\n/).includes('origin')
if (!u) {
if (has) await run('git', ['-C', projectPath, 'remote', 'remove', 'origin'])
return
}
if (!REMOTE_RE.test(u)) throw new Error('Remote: z. B. git@github.com:name/projekt.git (SSH) oder https://github.com/name/projekt.git')
const r = await run('git', ['-C', projectPath, 'remote', has ? 'set-url' : 'add', 'origin', u])
if (!r.ok) throw new Error(r.stderr.trim() || 'git remote fehlgeschlagen')
}
// git init with branch "main" (no commit yet).
async function initRepo(projectPath) {
if (!(await gitAvailable())) throw new Error('Git ist nicht installiert.')
if (fs.existsSync(path.join(projectPath, '.git'))) throw new Error('Ist schon ein Git-Repository.')
const r = await run('git', ['init', '-b', 'main', projectPath])
if (!r.ok) throw new Error(r.stderr.trim() || 'git init fehlgeschlagen')
}
// The user's SSH public key (to paste into GitHub/GitLab), or null.
function sshKey() {
const dir = path.join(process.env.USERPROFILE || require('os').homedir(), '.ssh')
for (const n of ['id_ed25519.pub', 'id_ecdsa.pub', 'id_rsa.pub']) {
try { return { file: path.join(dir, n), key: fs.readFileSync(path.join(dir, n), 'utf-8').trim() } } catch {}
}
return null
}
module.exports = { gitInfo, setRemote, initRepo, sshKey }