From b2f14afe4af1753b551f06bc2208d604214dfa0d Mon Sep 17 00:00:00 2001 From: haoxin Date: Sun, 1 Feb 2015 21:10:09 +0800 Subject: [PATCH] rewrite file only when file data changed also fix #597 --- js/lib/cli.js | 22 ++++++++++++---------- python/jsbeautifier/__init__.py | 8 +++++--- 2 files changed, 17 insertions(+), 13 deletions(-) diff --git a/js/lib/cli.js b/js/lib/cli.js index 1d25caad8..cf4ddedee 100755 --- a/js/lib/cli.js +++ b/js/lib/cli.js @@ -278,39 +278,41 @@ function processInputSync(filepath) { }); input.on('end', function() { - makePretty(data, config, outfile, writePretty); + makePretty(data, config, filepath, outfile, writePretty); }); } else { var dir = path.dirname(outfile); mkdirp.sync(dir); data = fs.readFileSync(filepath, 'utf8'); - makePretty(data, config, outfile, writePretty); + makePretty(data, config, filepath, outfile, writePretty); } } -function makePretty(code, config, outfile, callback) { +function makePretty(code, config, filepath, outfile, callback) { try { var fileType = getOutputType(outfile, config.type); var pretty = beautify[fileType](code, config); - callback(null, pretty, outfile, config); + callback(null, pretty, filepath, outfile, config, code); } catch (ex) { callback(ex); } } -function writePretty(err, pretty, outfile, config) { +function writePretty(err, pretty, filepath, outfile, config, code) { if (err) { console.error(err); process.exit(1); } if (outfile) { - try { - fs.writeFileSync(outfile, pretty, 'utf8'); - logToStdout('beautified ' + path.relative(process.cwd(), outfile), config); - } catch (ex) { - onOutputError(ex); + if (!(code === pretty && filepath === outfile)) { + try { + fs.writeFileSync(outfile, pretty, 'utf8'); + logToStdout('beautified ' + path.relative(process.cwd(), outfile), config); + } catch (ex) { + onOutputError(ex); + } } } else { process.stdout.write(pretty); diff --git a/python/jsbeautifier/__init__.py b/python/jsbeautifier/__init__.py index 68baabe7d..928f25277 100644 --- a/python/jsbeautifier/__init__.py +++ b/python/jsbeautifier/__init__.py @@ -1730,9 +1730,11 @@ def main(): if outfile == 'stdout': sys.stdout.write(beautify_file(file, js_options)) else: - mkdir_p(os.path.dirname(outfile)) - with open(outfile, 'w') as f: - f.write(beautify_file(file, js_options)) + result = beautify_file(file, js_options) + if not (result == ''.join(open(file).readlines()) and file == outfile): + mkdir_p(os.path.dirname(outfile)) + with open(outfile, 'w') as f: + f.write(result) except Exception as ex: print(ex, file=sys.stderr) return 1