UNPKG

@catladder/pipeline

Version:

Panter workflow for cloud CI/CD and DevOps

91 lines (81 loc) 2.43 kB
import { writeFile } from "fs/promises"; import { stringify } from "yaml"; import type { Config } from "../types"; import type { BaseHookContext } from "../types/hooks"; type WriteFileOptions = { commentChar: string; }; type StringifyOptions = Exclude< Parameters<typeof stringify>[2], null | undefined | string | number >; export const yamlStringifyOptions: StringifyOptions = { // prevents colapsing long command statements into multiple lines lineWidth: 0, // represent multi line commands as single line json strings doubleQuotedAsJSON: true, // Better readability when bash commands most often use double quotes singleQuote: true, }; export class FileWriter { public static create(config: Config) { return new FileWriter(config); } constructor(private readonly config: Config) { this.config = config; } protected async writeTheFile(path: string, content: string) { const transformedContent = await this.config.hooks?.transformFileBeforeWrite?.({ ...(await this.getBaseHookContext(path)), content, }); await writeFile(path, transformedContent ?? content, { encoding: "utf-8", }); } protected async getBaseHookContext(path: string): Promise<BaseHookContext> { const filename = path.split("/").pop() ?? ""; return { filename, path, extension: path.split(".").pop() ?? "", }; } public async writeGeneratedFile( path: string, content: string, options: WriteFileOptions, ) { await this.writeTheFile( path, [this.getAutoGeneratedHeader(options.commentChar), content].join("\n"), ); } public async writeYamlfile(path: string, data: any) { const dataTransformed = await this.config.hooks?.transformYamlBeforeWrite?.( { ...(await this.getBaseHookContext(path)), data, }, ); return this.writeGeneratedFile( path, stringify(dataTransformed ?? data, yamlStringifyOptions), { commentChar: "#", }, ); } protected getAutoGeneratedHeader(commentChar: string) { return [ "-------------------------------------------------", `🐱 🔨 This file is generated by catladder`, `🚨 Do not edit this file manually 🚨`, "-------------------------------------------------", ] .map((line) => `${commentChar} ${line}`) .join("\n") .concat("\n"); } }