Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: regexp for project name & array template name for addHook #11

Merged
merged 1 commit into from
Oct 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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