Files
deployer2/src/deploy.ts

59 lines
1.6 KiB
TypeScript

import hash from "object-hash";
import { $ } from "bun";
import path from "path";
import { config, indexedConfig, isSelf } from "./config";
import fs from "fs";
import { rebuildCaddyfile } from "./caddy";
type DeployInstance = {
host: string;
commitHash: string;
};
export const deploy = async ({ host, commitHash }: DeployInstance) => {
const service = config.services[host];
const { user, repo, branch, port } = indexedConfig[hash(service)];
const deploymentId = new Date().toISOString();
const serviceDir = path.join(config.directory, host);
await $`mkdir -p ${serviceDir}`;
// Fetch
$.cwd(serviceDir);
const url = `http://deployer:${config.token}@${config.giteaUrl}/${user}/${repo}`;
await $`mkdir -p src`;
await $`mkdir -p logs`;
await $`git clone -b ${branch} ${url} ./src`.nothrow();
$.cwd(path.join(serviceDir, "src"));
await $`git fetch origin ${branch}`;
await $`git reset --hard origin/${branch}`;
await $`git checkout ${commitHash}`;
// Build
await $`make build`;
rebuildCaddyfile();
// Register service
const systemdServiceName = `deployer2-${host}.service`;
await $`cat service.template | envsubst > ${serviceDir}/${systemdServiceName}`.env(
{
host,
port: port.toString(),
repo,
branch,
commitHash,
deploymentId,
logsDir: path.join(serviceDir, "logs"),
serviceDir,
user: isSelf(service) ? "root" : "drm",
}
);
await $`ln -sf ${serviceDir}/${systemdServiceName} ${config.systemServicesDir}/${systemdServiceName}`;
// Start!
await $`systemctl daemon-reload`;
await $`systemctl restart ${systemdServiceName}`;
};