Skip to content

Commit

Permalink
feat: Add --watch support (#107)
Browse files Browse the repository at this point in the history
fixes #104

<!-- ps-id: 9ee09974-f388-4657-a4ae-4b2ebb490df5 -->
  • Loading branch information
Coobaha authored Nov 19, 2023
1 parent 26e449b commit 72f0107
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 21 deletions.
22 changes: 16 additions & 6 deletions generator/gen.bin.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,37 @@
#!/usr/bin/env node
import yargs from 'yargs';

// @ts-ignore
import { hideBin } from 'yargs/helpers';
import gen from './gen';
import { glob } from 'glob';
import { watcher } from './watcher';

yargs(hideBin(process.argv))
.command<{ files: string }>(
.command(
'gen [files]',
'Generates json schemas next to corresponding ts files',
(yargs) => {
(yargs) =>
yargs
.positional('files', {
describe: 'glob pattern of files',
type: 'string',
demandOption: true,
})
.demandOption(['files']);
},
.option('watch', {
alias: 'w',
type: 'boolean',
description: 'Watch files for changes',
})
.demandOption(['files']),
async (argv) => {
const files = await glob(argv.files);
if (argv.watch) {
console.log('Watching for changes...');
watcher(argv.files);
return;
}

console.log('Generating schemas...');
const files = await glob(argv.files);
await gen({ files });
},
)
Expand Down
30 changes: 30 additions & 0 deletions generator/watcher.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import chokidar from 'chokidar';
import gen from './gen';
import path from 'node:path';
import fsp from 'node:fs/promises';

export function watcher(files: string | string[]) {
const watcher = chokidar.watch(files);
watcher.on('change', async (file: string) => {
await gen({ files: [file] });
});
watcher.on('add', async (file: string) => {
await gen({ files: [file] });
});
watcher.on('unlink', async (file: string) => {
const jsonFile = path.parse(file);
const schema = path.format({
...jsonFile,
base: path.basename(jsonFile.base, jsonFile.ext) + '.gen.json',
ext: '.json',
});
const exists = await fsp
.stat(schema)
.then(() => true)
.catch(() => false);

if (exists) {
await fsp.rm(schema);
}
});
}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
},
"dependencies": {
"@types/json-schema": "^7.0.13",
"chokidar": "3.5.3",
"crypto-js": "^4.1.1",
"glob": "^10.3.4",
"json-schema-merge-allof": "^0.8.1",
Expand Down
18 changes: 3 additions & 15 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 72f0107

Please sign in to comment.