import { spawnSync } from 'node:child_process'; import { mkdir, readFile, writeFile } from 'node:fs/promises'; import { resolve, relative, isAbsolute } from 'node:path'; import YAML from 'yaml'; const env = process.env; for (const key of ['GITOPS_REPOSITORY', 'GITOPS_USERNAME', 'GITOPS_TOKEN', 'IMAGE_REPOSITORY', 'IMAGE_DIGEST']) if (!env[key]) throw new Error(`Missing ${key}`); if (!/^sha256:[a-f0-9]{64}$/.test(env.IMAGE_DIGEST)) throw new Error('Invalid image digest'); const repository = new URL(env.GITOPS_REPOSITORY); if (repository.protocol !== 'https:' || repository.username || repository.password) throw new Error('GITOPS_REPOSITORY must be HTTPS without credentials'); const root = resolve('.local/gitops'); const askpass = resolve('.local/git-askpass.cjs'); await mkdir(resolve('.local'), { recursive: true }); await writeFile(askpass, '#!/usr/bin/env node\nprocess.stdout.write(process.argv[2].toLowerCase().includes("username") ? process.env.GITOPS_USERNAME : process.env.GITOPS_TOKEN);\n', { mode: 0o700 }); function git(args, cwd = process.cwd()) { const result = spawnSync('git', args, { cwd, env: { ...env, GIT_ASKPASS: askpass, GIT_TERMINAL_PROMPT: '0' }, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }); if (result.status !== 0) throw new Error(`Git operation failed (${args[0]}): ${result.stderr.replaceAll(env.GITOPS_TOKEN, '[redacted]')}`); return result.stdout; } git(['clone', '--branch', env.GITOPS_BRANCH || 'main', '--depth', '1', '--', repository.href, root]); const file = resolve(root, env.GITOPS_VALUES_FILE || 'apps/aeternalis/values.yaml'); const local = relative(root, file); if (local.startsWith('..') || isAbsolute(local) || !/\.ya?ml$/.test(local)) throw new Error('Values file must stay inside the GitOps checkout'); const document = YAML.parseDocument(await readFile(file, 'utf8')); document.setIn(['image', 'repository'], env.IMAGE_REPOSITORY); document.setIn(['image', 'digest'], env.IMAGE_DIGEST); await writeFile(file, document.toString()); git(['config', 'user.name', 'Aeternalis CI'], root); git(['config', 'user.email', 'aeternalis-ci@localhost'], root); git(['add', '--', local], root); if (git(['diff', '--cached', '--name-only'], root).trim()) { git(['commit', '-m', `Deploy Aeternalis ${env.IMAGE_DIGEST.slice(0,19)}`], root); git(['push', 'origin', `HEAD:${env.GITOPS_BRANCH || 'main'}`], root); }