@@ -4,6 +4,7 @@ import { program } from 'commander';
44import { readFileSync , writeFileSync } from 'fs' ;
55import { fileURLToPath } from 'url' ;
66import path from 'path' ;
7+ import chokidar from 'chokidar' ;
78import { generate } from '../index.js' ;
89
910const __filename = fileURLToPath ( import . meta. url ) ;
@@ -20,6 +21,7 @@ program
2021 . description ( 'Generate fetch client code' )
2122 . option ( '-i, --input <file>' , 'input specification file' )
2223 . option ( '-o, --output <file>' , 'output file path' )
24+ . option ( '-w, --watch' , 'watch input file for changes and regenerate automatically' )
2325 . action ( ( options ) => {
2426 if ( ! options . input ) {
2527 console . error ( 'Error: Input file is required' ) ;
@@ -31,18 +33,51 @@ program
3133 process . exit ( 1 ) ;
3234 }
3335
34- try {
35- console . log ( 'Generating fetch client...' ) ;
36- console . log ( 'Input:' , options . input ) ;
37- console . log ( 'Output:' , options . output ) ;
36+ const generateClient = ( ) => {
37+ try {
38+ console . log ( 'Generating fetch client...' ) ;
39+ console . log ( 'Input:' , options . input ) ;
40+ console . log ( 'Output:' , options . output ) ;
3841
39- const clientCode = generate ( options . input ) ;
40- writeFileSync ( options . output , clientCode , 'utf8' ) ;
42+ const clientCode = generate ( options . input ) ;
43+ writeFileSync ( options . output , clientCode , 'utf8' ) ;
44+
45+ console . log ( '✓ Fetch client generated successfully!' ) ;
46+ } catch ( error ) {
47+ console . error ( 'Error generating client:' , error . message ) ;
48+ if ( ! options . watch ) {
49+ process . exit ( 1 ) ;
50+ }
51+ }
52+ } ;
53+
54+ // Generate initially
55+ generateClient ( ) ;
56+
57+ // If watch flag is set, watch for changes
58+ if ( options . watch ) {
59+ console . log ( `Watching ${ options . input } for changes...` ) ;
4160
42- console . log ( '✓ Fetch client generated successfully!' ) ;
43- } catch ( error ) {
44- console . error ( 'Error generating client:' , error . message ) ;
45- process . exit ( 1 ) ;
61+ const watcher = chokidar . watch ( options . input , {
62+ persistent : true ,
63+ ignoreInitial : true
64+ } ) ;
65+
66+ watcher . on ( 'change' , ( ) => {
67+ console . log ( '\nFile changed, regenerating...' ) ;
68+ generateClient ( ) ;
69+ } ) ;
70+
71+ watcher . on ( 'error' , ( error ) => {
72+ console . error ( 'Watcher error:' , error ) ;
73+ } ) ;
74+
75+ // Keep the process alive
76+ process . on ( 'SIGINT' , ( ) => {
77+ console . log ( '\nStopping file watcher...' ) ;
78+ watcher . close ( ) ;
79+ process . exit ( 0 ) ;
80+ } ) ;
4681 }
4782 } ) ;
4883
0 commit comments