2020-11-04 13:15:38 +00:00
|
|
|
import { relative, dirname, resolve } from 'path'
|
2020-11-03 22:14:32 +00:00
|
|
|
import { readFile, writeFile, mkdirp } from 'fs-extra'
|
2020-11-01 23:17:44 +00:00
|
|
|
import jiti from 'jiti'
|
2020-11-05 21:23:24 +00:00
|
|
|
import { SLSOptions, UnresolvedPath } from './config'
|
2020-11-01 23:17:44 +00:00
|
|
|
|
2020-11-02 14:42:27 +00:00
|
|
|
const pwd = process.cwd()
|
|
|
|
|
2020-11-05 12:26:00 +00:00
|
|
|
export const hl = (str: string) => '`' + str + '`'
|
2020-11-01 23:17:44 +00:00
|
|
|
|
2020-11-05 12:26:00 +00:00
|
|
|
export function prettyPath (p: string, highlight = true) {
|
2020-11-02 14:42:27 +00:00
|
|
|
p = relative(pwd, p)
|
2020-11-01 23:17:44 +00:00
|
|
|
return highlight ? hl(p) : p
|
|
|
|
}
|
|
|
|
|
2020-11-05 12:26:00 +00:00
|
|
|
export async function loadTemplate (src: string) {
|
2020-11-03 22:14:32 +00:00
|
|
|
const contents = await readFile(src, 'utf-8')
|
2020-11-05 12:26:00 +00:00
|
|
|
return (params: Record<string, string>) => contents.replace(/{{ (\w+) }}/g, `${params.$1}`)
|
2020-11-03 22:14:32 +00:00
|
|
|
}
|
|
|
|
|
2020-11-05 12:26:00 +00:00
|
|
|
export async function renderTemplate (src: string, dst: string, params: any) {
|
2020-11-03 22:14:32 +00:00
|
|
|
const tmpl = await loadTemplate(src)
|
|
|
|
const rendered = tmpl(params)
|
|
|
|
await mkdirp(dirname(dst))
|
|
|
|
await writeFile(dst, rendered)
|
|
|
|
}
|
|
|
|
|
2020-11-05 21:56:40 +00:00
|
|
|
export async function compileTemplateToJS (src: string) {
|
2020-11-03 22:14:32 +00:00
|
|
|
const contents = await readFile(src, 'utf-8')
|
|
|
|
// eslint-disable-next-line no-template-curly-in-string
|
2020-11-05 21:56:40 +00:00
|
|
|
return `export default (params) => \`${contents.replace(/{{ (\w+) }}/g, '${params.$1}')}\``
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function writeFileP (path, contents) {
|
|
|
|
await mkdirp(dirname(path))
|
|
|
|
await writeFile(path, contents)
|
2020-11-03 22:14:32 +00:00
|
|
|
}
|
|
|
|
|
2020-11-05 12:26:00 +00:00
|
|
|
export const jitiImport = (dir: string, path: string) => jiti(dir)(path)
|
|
|
|
export const tryImport = (dir: string, path: string) => { try { return jitiImport(dir, path) } catch (_err) { } }
|
2020-11-04 13:15:38 +00:00
|
|
|
|
2020-11-05 21:23:24 +00:00
|
|
|
export function resolvePath (options: SLSOptions, path: UnresolvedPath, resolveBase: string = '') {
|
|
|
|
return resolve(resolveBase, typeof path === 'string' ? path : path(options))
|
|
|
|
}
|
|
|
|
|
2020-11-04 13:15:38 +00:00
|
|
|
export const LIB_DIR = resolve(__dirname, '../lib')
|
|
|
|
export const RUNTIME_DIR = resolve(LIB_DIR, 'runtime')
|