From 2f0680ca16c48bd53265b2b42359d7b5eed77ecf Mon Sep 17 00:00:00 2001 From: Futago-za Ryuu Date: Sat, 17 Mar 2018 04:27:09 +0000 Subject: [PATCH] Restore orignal output on generation fail If the output file already exists, and the parser generator fails, the result is a empty file. This commit tries to avoid this pitfall. --- bin/peg.js | 44 +++++++++++++++++++++++++++++++------------- 1 file changed, 31 insertions(+), 13 deletions(-) diff --git a/bin/peg.js b/bin/peg.js index 7e05881..f8e3361 100644 --- a/bin/peg.js +++ b/bin/peg.js @@ -24,6 +24,12 @@ function readStream( inputStream, callback ) { } +function closeStream( stream ) { + + if ( stream !== process.stdin || stream !== process.stdout ) stream.end(); + +} + function abort( message ) { console.error( message ); @@ -33,36 +39,45 @@ function abort( message ) { // Main -let inputStream, outputStream; +let inputStream, outputStream, orignalContent; + +const inputFile = options.inputFile; +const outputFile = options.outputFile; options.parser = options.parser || {}; -if ( options.inputFile === "-" ) { +if ( inputFile === "-" ) { process.stdin.resume(); inputStream = process.stdin; inputStream.on( "error", () => { - abort( `Can't read from file "${ options.inputFile }".` ); + abort( `Can't read from file "${ inputFile }".` ); } ); } else { - inputStream = fs.createReadStream( options.inputFile ); - options.parser.filename = options.inputFile; + inputStream = fs.createReadStream( inputFile ); + options.parser.filename = inputFile; } -if ( options.outputFile === "-" ) { +if ( outputFile === "-" ) { outputStream = process.stdout; } else { - outputStream = fs.createWriteStream( options.outputFile ); + if ( fs.existsSync( outputFile ) ) { + + orignalContent = fs.readFileSync( outputFile, "utf8" ); + + } + + outputStream = fs.createWriteStream( outputFile ); outputStream.on( "error", () => { - abort( `Can't write to file "${ options.outputFile }".` ); + abort( `Can't write to file "${ outputFile }".` ); } ); @@ -89,15 +104,18 @@ readStream( inputStream, input => { } - return abort( e.message ); + if ( orignalContent ) { - } + closeStream( outputStream ); + fs.writeFileSync( outputFile, orignalContent, "utf8" ); - outputStream.write( source ); - if ( outputStream !== process.stdout ) { + } - outputStream.end(); + return abort( e.message ); } + outputStream.write( source ); + closeStream( outputStream ); + } );