From 4312a2b42583af54a0426cbdb752adec38d6c15e Mon Sep 17 00:00:00 2001 From: Yusuke Wada Date: Mon, 16 Oct 2023 07:55:21 +0900 Subject: [PATCH] feat: regexp for project name & array template names for `addHook` (#11) --- src/hook.ts | 24 ++++++++++++++++++++---- src/hooks/after-create.ts | 13 +++---------- 2 files changed, 23 insertions(+), 14 deletions(-) diff --git a/src/hook.ts b/src/hook.ts index ab8f106..a6662f1 100644 --- a/src/hook.ts +++ b/src/hook.ts @@ -4,10 +4,13 @@ export class Hook any> { this.#hookMap = new Map() } - addHook(templateName: string, hook: HookFunction) { - const hooks = this.#hookMap.get(templateName) || [] - hooks.push(hook) - this.#hookMap.set(templateName, hooks) + addHook(templateName: string | string[], hook: HookFunction) { + const names = Array.isArray(templateName) ? templateName : [templateName] + for (const name of names) { + const hooks = this.#hookMap.get(name) || [] + hooks.push(hook) + this.#hookMap.set(name, hooks) + } } applyHook( @@ -24,3 +27,16 @@ export class Hook any> { return results } } + +/** + * After Hook + */ + +type AfterHookOptions = { + projectName: string + directoryPath: string +} + +type AfterHookFunction = (options: AfterHookOptions) => void + +export const afterCreateHook = new Hook() diff --git a/src/hooks/after-create.ts b/src/hooks/after-create.ts index ec434a5..be33f8f 100644 --- a/src/hooks/after-create.ts +++ b/src/hooks/after-create.ts @@ -1,22 +1,15 @@ import { readFileSync, writeFileSync } from 'fs' import * as path from 'path' -import { Hook } from '../hook' +import { afterCreateHook } from '../hook' -type AfterHookOptions = { - projectName: string - directoryPath: string -} - -type AfterHookFunction = (options: AfterHookOptions) => void - -const afterCreateHook = new Hook() +const PROJECT_NAME = new RegExp(/%%PROJECT_NAME.*%%/g) afterCreateHook.addHook( 'cloudflare-workers', ({ projectName, directoryPath }) => { const wranglerPath = path.join(directoryPath, 'wrangler.toml') const wrangler = readFileSync(wranglerPath, 'utf-8') - const rewritten = wrangler.replaceAll('%%PROJECT_NAME%%', projectName) + const rewritten = wrangler.replaceAll(PROJECT_NAME, projectName) writeFileSync(wranglerPath, rewritten) } )