From 86d1f119dce3d8020b2e3f54cb9f2dba9a13b058 Mon Sep 17 00:00:00 2001 From: "Kent C. Dodds" Date: Mon, 29 Nov 2021 15:12:39 -0700 Subject: [PATCH] feat: only save files if they are unchanged Closes #320 --- index.js | 11 +++++++++-- test/fixtures/unchanged-input.css | 3 +++ test/fixtures/unchanged-output.css | 5 +++++ test/unchanged.js | 17 +++++++++++++++++ 4 files changed, 34 insertions(+), 2 deletions(-) create mode 100644 test/fixtures/unchanged-input.css create mode 100644 test/fixtures/unchanged-output.css create mode 100644 test/unchanged.js diff --git a/index.js b/index.js index a5286f7..615638c 100755 --- a/index.js +++ b/index.js @@ -250,11 +250,11 @@ function css(css, file) { const tasks = [] if (options.to) { - tasks.push(fs.outputFile(options.to, result.css)) + tasks.push(outputFile(options.to, result.css)) if (result.map) { const mapfile = getMapfile(options) - tasks.push(fs.outputFile(mapfile, result.map.toString())) + tasks.push(outputFile(mapfile, result.map.toString())) } } else process.stdout.write(result.css, 'utf8') @@ -278,6 +278,13 @@ function css(css, file) { .catch((err) => { throw err }) + + async function outputFile(file, string) { + const fileExists = await fs.pathExists(file) + const currentValue = fileExists ? await fs.readFile(file, 'utf8') : null + if (currentValue === string) return + return fs.outputFile(file, string) + } } function dependencies(results) { diff --git a/test/fixtures/unchanged-input.css b/test/fixtures/unchanged-input.css new file mode 100644 index 0000000..60f1eab --- /dev/null +++ b/test/fixtures/unchanged-input.css @@ -0,0 +1,3 @@ +body { + color: red; +} diff --git a/test/fixtures/unchanged-output.css b/test/fixtures/unchanged-output.css new file mode 100644 index 0000000..6521159 --- /dev/null +++ b/test/fixtures/unchanged-output.css @@ -0,0 +1,5 @@ +body { + color: red; +} + +/*# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInVuY2hhbmdlZC1pbnB1dC5jc3MiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEiLCJmaWxlIjoidW5jaGFuZ2VkLW91dHB1dC5jc3MiLCJzb3VyY2VzQ29udGVudCI6WyJib2R5IHtcbiAgY29sb3I6IHJlZDtcbn1cbiJdfQ== */ \ No newline at end of file diff --git a/test/unchanged.js b/test/unchanged.js new file mode 100644 index 0000000..4598530 --- /dev/null +++ b/test/unchanged.js @@ -0,0 +1,17 @@ +import fs from 'fs-extra' +import test from 'ava' + +import cli from './helpers/cli.js' + +test('files are not saved if the contents are the same', async (t) => { + const input = 'test/fixtures/unchanged-input.css' + const output = 'test/fixtures/unchanged-output.css' + const intialStat = await fs.stat(output) + + const { error, stderr } = await cli([input, '-o', output]) + + t.falsy(error, stderr) + + const finalStat = await fs.stat(output) + t.is(finalStat.mtimeMs, intialStat.mtimeMs) +})