deno.land / x / lume@v2.1.4 / cli / create.ts
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113import { stringify } from "../deps/yaml.ts";import { dirname, join, toFileUrl } from "../deps/path.ts";import { ensureDir } from "../deps/fs.ts";import { isGenerator } from "../core/utils/generator.ts";import { isUrl } from "../core/utils/path.ts";import { log } from "../core/utils/log.ts";import { createSite } from "./run.ts";
import type Site from "../core/site.ts";
/** Run an archetype */export async function create( config: string | undefined, name: string, args: string[],) { // deno-lint-ignore no-explicit-any let fn: any; const site = await createSite(config);
try { const mod = name.startsWith(".") ? await import(toFileUrl(join(Deno.cwd(), name)).href) : isUrl(name) ? await import(name) : await Promise.any([ import(toFileUrl(site.src(`_archetypes/${name}.ts`)).href), import(toFileUrl(site.src(`_archetypes/${name}.js`)).href), ]);
if (mod?.default) { fn = mod.default; } } catch (cause) { throw new Error(`Archetype "${name}" not found or is errored.`, { cause, }); }
if (typeof fn !== "function") { throw new Error(`Archetype "${name}" is not a function.`); }
if (isGenerator(fn)) { for await (const archetype of fn(...args) as Generator<Archetype>) { await saveArchetype(site, archetype); } } else { const archetype = fn(...args) as Archetype; await saveArchetype(site, archetype); }}
async function saveArchetype(site: Site, archetype: Archetype) { const { path, content } = archetype;
if (!path) { throw new Error("Archetype path is required."); } if (!content) { throw new Error("Archetype content is required."); }
if (typeof content === "string" || content instanceof Uint8Array) { return await saveFile(site.src(path), content); }
if (path.endsWith(".json")) { return await saveFile( site.src(path), JSON.stringify(content, null, 2) + "\n", ); }
if (path.endsWith(".yaml") || path.endsWith(".yml")) { return await saveFile( site.src(path), stringify(content) + "\n", ); }
const { content: body, ...frontmatter } = content;
return await saveFile( site.src(path), `---\n${stringify(frontmatter)}---\n${body || ""}\n`, );}
async function saveFile(path: string, content: string | Uint8Array) { await ensureDir(dirname(path));
try { content instanceof Uint8Array ? await Deno.writeFile(path, content, { createNew: true }) : await Deno.writeTextFile(path, content, { createNew: true });
log.info(`✔️ Created file: <gray>${path}</gray>`); } catch (error) { if (error instanceof Deno.errors.AlreadyExists) { log.warn(`⚠️ File already exists: <gray>${path}</gray>`); } else { throw error; } }}
/** Definition used to create a new Page */export interface Archetype { path: string; content: string | Record<string, unknown> | Uint8Array;}
Version Info