import { execFileSync } from 'node:child_process'; import { fileURLToPath } from 'node:url'; import { readCiContext } from './ci-context.mjs'; try { const { commit, tag, slug, publish } = readCiContext(); if (!publish) throw new Error('Images can only be published by pushes or same-repository PRs.'); execFileSync(process.execPath, [fileURLToPath(new URL('./ci-policy.mjs', import.meta.url))]); const env = process.env; if (!env.REGISTRY_USERNAME || !env.REGISTRY_PASSWORD) { throw new Error('REGISTRY_USERNAME and REGISTRY_PASSWORD are required for publication.'); } const registry = new URL(env.GITHUB_SERVER_URL).host; const image = `${registry}/${env.GITHUB_REPOSITORY.toLowerCase()}`; const shaImage = `${image}:sha-${commit}`; const docker = (...args) => execFileSync('docker', args, { stdio: 'inherit' }); execFileSync( 'docker', ['login', registry, '--username', env.REGISTRY_USERNAME, '--password-stdin'], { input: env.REGISTRY_PASSWORD, stdio: ['pipe', 'inherit', 'inherit'], }, ); if (tag) { docker('pull', shaImage); docker('tag', shaImage, `${image}:${tag}`); docker('push', `${image}:${tag}`); docker('tag', shaImage, `${image}:latest`); docker('push', `${image}:latest`); } else { const branchImage = `${image}:branch-${slug}`; docker('build', '-t', shaImage, '-t', branchImage, '.'); docker('push', shaImage); docker('push', branchImage); } } catch (error) { console.error(error.message); process.exitCode = 1; }