Skip to content

Commit

Permalink
feat: regexp for project name & array template names for addHook (#11)
Browse files Browse the repository at this point in the history
  • Loading branch information
yusukebe authored Oct 15, 2023
1 parent 79469db commit 4312a2b
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 14 deletions.
24 changes: 20 additions & 4 deletions src/hook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,13 @@ export class Hook<HookFunction extends (...args: any[]) => any> {
this.#hookMap = new Map<string, HookFunction[]>()
}

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(
Expand All @@ -24,3 +27,16 @@ export class Hook<HookFunction extends (...args: any[]) => any> {
return results
}
}

/**
* After Hook
*/

type AfterHookOptions = {
projectName: string
directoryPath: string
}

type AfterHookFunction = (options: AfterHookOptions) => void

export const afterCreateHook = new Hook<AfterHookFunction>()
13 changes: 3 additions & 10 deletions src/hooks/after-create.ts
Original file line number Diff line number Diff line change
@@ -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<AfterHookFunction>()
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)
}
)
Expand Down

0 comments on commit 4312a2b

Please sign in to comment.