Skip to content

Commit

Permalink
feat: only save files if they are unchanged
Browse files Browse the repository at this point in the history
  • Loading branch information
kentcdodds committed Nov 29, 2021
1 parent c7cc0bb commit 86d1f11
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 2 deletions.
11 changes: 9 additions & 2 deletions index.js
Expand Up @@ -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')

Expand All @@ -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) {
Expand Down
3 changes: 3 additions & 0 deletions test/fixtures/unchanged-input.css
@@ -0,0 +1,3 @@
body {
color: red;
}
5 changes: 5 additions & 0 deletions test/fixtures/unchanged-output.css

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

17 changes: 17 additions & 0 deletions 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)
})

0 comments on commit 86d1f11

Please sign in to comment.