UNPKG

@qodly/cli

Version:

Qodly CLI

84 lines (83 loc) 2.64 kB
import { exec as execCB } from "node:child_process"; import { existsSync } from "node:fs"; import { promisify } from "node:util"; import { mkdir, rm } from "node:fs/promises"; import { resolve } from "node:path"; import inquirer from "inquirer"; import Ora from "ora"; import { fetch } from "./fetch.js"; import { libDir } from "./pkg.js"; const cacheFolder = resolve(libDir, '.cache'); const exec = promisify(execCB); const TEMPLATES = []; export async function getTemplates() { if (TEMPLATES.length === 0) { const TEMPLATES_URL = 'https://static.4d-ps.com/assets/qodly-templates.json'; const { data: templates, status } = await fetch(TEMPLATES_URL); if (status !== 200) { throw new Error('Failed to fetch templates'); } TEMPLATES.push(...templates); } return TEMPLATES; } export async function cacheTemplate(name) { const template = (await getTemplates()).find((t)=>t.name === name); if (!template) { throw new Error(`Template not found. Available templates: ${TEMPLATES.map((t)=>t.name).join(', ')}`); } const templatePath = resolve(cacheFolder, template.name); await mkdir(cacheFolder, { recursive: true }); if (!existsSync(templatePath)) { let created = false; const Spinner = Ora({ text: 'Cloning and caching template...', discardStdin: false }).start(); try { await exec(`git clone ${template.repo.ssh} ${template.name}`, { cwd: cacheFolder }); created = true; } catch (e) { // ignore } if (!created) { await exec(`git clone ${template.repo.https} ${template.name}`, { cwd: cacheFolder }); } await rm(resolve(templatePath, '.git'), { recursive: true }); Spinner.succeed(); } return template; } export class TemplateChooser { status = 'success'; answers = {}; question; constructor(question, _readLine, answers){ this.answers = answers; this.question = question; } async run() { const choices = (await getTemplates()).map((t)=>({ name: t.title, value: t.name })); const { template } = await inquirer.prompt({ type: 'list', name: 'template', message: this.question.message, choices }); await cacheTemplate(template); this.status = 'success'; return template; } } //# sourceMappingURL=TemplateChooser.js.map