Skip to content

Commit

Permalink
feat(builder): gen support watch mode
Browse files Browse the repository at this point in the history
  • Loading branch information
bytemain committed Sep 5, 2023
1 parent 8ad21f5 commit 7f9393e
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 21 deletions.
4 changes: 1 addition & 3 deletions libs/cfworker-builder/lib/commander/index.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import mri from 'mri';

class Commander {
export default class Commander {
commandMap = new Map();
addSubCommand(subCommand, options) {
this.commandMap.set(subCommand, options);
Expand Down Expand Up @@ -34,5 +34,3 @@ Good bye~
);
}
}

export default Commander;
48 changes: 31 additions & 17 deletions libs/cfworker-builder/lib/gen-toml.mjs
Original file line number Diff line number Diff line change
@@ -1,30 +1,44 @@
import 'dotenv/config';

import { readFileSync, writeFileSync } from 'fs';
import { readFileSync, writeFileSync, watch as _watch } from 'fs';

import MagicString from 'magic-string';

const text = readFileSync('./wrangler.tpl.toml').toString();
const tplFilePath = './wrangler.tpl.toml';
const targetFilePath = './wrangler.toml';

const magic = new MagicString(text);
export function run() {
const text = readFileSync(tplFilePath).toString();

const regex = /{{(.+?)}}/gm;
const magic = new MagicString(text);

const matches = text.matchAll(regex);
const regex = /{{(.+?)}}/gm;

if (!matches) {
process.exit(0);
}
const matches = text.matchAll(regex);

if (!matches) {
return;
}

for (const match of matches) {
const key = match[1];
const v = process.env[key];
if (v && match.index) {
magic.update(match.index, match.index + match[0].length, v);
console.log(`"${key}" will be replaced to "[redacted]"`);
} else {
console.warn(`env variable "${key}" not found.`);
for (const match of matches) {
const key = match[1];
const v = process.env[key];
if (v && match.index) {
magic.update(match.index, match.index + match[0].length, v);
console.log(`"${key}" will be replaced to "[redacted]"`);
} else {
console.warn(`env variable "${key}" not found.`);
}
}

writeFileSync(targetFilePath, magic.toString());
}

writeFileSync('./wrangler.toml', magic.toString());
export function watch() {
console.log('watching template file changes...');

_watch(tplFilePath, {}, () => {
console.log(`${tplFilePath} changed.`);
run();
});
}
6 changes: 5 additions & 1 deletion libs/cfworker-builder/lib/index.mjs
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import Commander from './commander/index.mjs';
import { run, watch } from './gen-toml.mjs';

const commander = new Commander();
commander.addSubCommand('gen-toml', {
handler: (_, argv) => {
console.log(_);
console.log(argv);
import('./gen-toml.mjs');
run();
if (argv.watch) {
watch();
}
},
help: 'generate wrangler.toml',
});
Expand Down

0 comments on commit 7f9393e

Please sign in to comment.