@pompeii-labs/cli
Version:
Magma CLI
135 lines (134 loc) • 4.95 kB
JavaScript
import chalk from "chalk";
import { Bundler } from "../bundler.js";
import boxen from "boxen";
import path from "path";
import { UI } from "../ui.js";
import { promisify } from "util";
import { exec } from "child_process";
import fs from "fs";
import {
deployTemplate,
getTemplateByName,
getTemplateEnv,
setTemplateEnv,
unsetTemplateEnv
} from "../api.js";
const execAsync = promisify(exec);
async function templateDeploy() {
const projectDir = path.resolve(process.cwd());
const packageJson = JSON.parse(fs.readFileSync(path.join(projectDir, "package.json"), "utf8"));
console.log(
boxen(chalk.bold(`Deploying ${chalk.cyan(packageJson.name)}`), {
padding: 1,
margin: 1,
borderStyle: "round",
borderColor: "cyan"
})
);
if (packageJson.scripts?.build) {
const buildSpinner = UI.spinner("Building template").start();
try {
await execAsync(`npm run build`, { cwd: projectDir });
} catch (error) {
const errorOutput = error.stdout || error.stderr || error.message;
buildSpinner.fail();
console.log(errorOutput);
console.log(chalk.red("\nFailed to build template"));
process.exit(1);
}
buildSpinner.succeed();
}
const bundler = new Bundler(projectDir, null);
const files = bundler.collectFiles();
const startupSpinner = UI.spinner("Deploying Template").start();
try {
await deployTemplate({
name: packageJson.name,
description: packageJson.description,
version: packageJson.version,
files
});
startupSpinner.succeed();
console.log(
chalk.cyan(
`
\u{1F30B} Template image has been successfully uploaded for ${packageJson.name}!`
)
);
console.log();
} catch (error) {
startupSpinner.fail();
console.log(chalk.red(`Failed to deploy template ${packageJson.name}: ${error.message}`));
}
}
function getTemplateName() {
if (!fs.existsSync(path.join(process.cwd(), "package.json"))) {
throw new Error("No package.json found in the current directory");
}
const packageJson = JSON.parse(
fs.readFileSync(path.join(process.cwd(), "package.json"), "utf8")
);
return packageJson.name;
}
async function getEnvCmd(key) {
try {
const templateName = getTemplateName();
const template = await getTemplateByName(templateName);
const value = await getTemplateEnv(template.id, key);
if (!value) {
console.log(`${key} not found`);
}
console.log(chalk.green(`${key}=${value}`));
} catch (error) {
console.error(chalk.red(`Failed to get environment variable: ${error.message}`));
process.exit(1);
}
}
async function setEnvCmd(keyValue) {
try {
const templateName = getTemplateName();
const template = await getTemplateByName(templateName);
let env = [];
if (keyValue) {
const [key, ...valueParts] = keyValue.split("=");
const value = valueParts.join("=");
if (!value) {
console.error(chalk.red("Invalid format. Use KEY=VALUE"));
process.exit(1);
}
env = [{ key, value }];
} else {
const envContents = fs.readFileSync(path.join(process.cwd(), ".env"), "utf8");
env = envContents.split("\n").map((f) => f.trim()).filter((f) => !!f && !f.startsWith("#")).map((f) => f.split("=")).map(([key, value]) => ({ key, value }));
}
await setTemplateEnv(template.id, env);
console.log(chalk.green(`Successfully set ${env.length} environment variables`));
console.log();
console.log(chalk.dim(env.map((e) => `${e.key}=${e.value}`).join("\n")));
} catch (error) {
console.error(chalk.red(`Failed to set environment variable: ${error.message}`));
process.exit(1);
}
}
async function unsetEnvCmd(key) {
try {
const templateName = getTemplateName();
const template = await getTemplateByName(templateName);
await unsetTemplateEnv(template.id, key);
console.log(chalk.green(`Successfully unset environment variable ${key}`));
} catch (error) {
console.error(chalk.red(`Failed to unset environment variable: ${error.message}`));
process.exit(1);
}
}
function templateCommand(program) {
const template = program.command("template").description("Create and deploy Magma agent templates");
template.command("deploy").description("Deploy a template").action(templateDeploy);
const env = template.command("env").description("Manage default environment variables for templates");
env.command("set").argument("[key_value]", "Key value pair in format KEY=VALUE").description("Set an environment variable. If no argument, lists all variables").action(setEnvCmd);
env.command("get").argument("<key>", "The environment variable key to retrieve").description("Get the value of an environment variable").action(getEnvCmd);
env.command("unset").argument("<key>", "The environment variable key to unset").description("Unset an environment variable").action(unsetEnvCmd);
}
export {
templateCommand
};