Skip to content

Commit b06fa80

Browse files
authored
feat: only save files if they are unchanged (postcss#417)
Closes postcss#320
1 parent c7cc0bb commit b06fa80

File tree

4 files changed

+34
-2
lines changed

4 files changed

+34
-2
lines changed

index.js

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -250,11 +250,11 @@ function css(css, file) {
250250
const tasks = []
251251

252252
if (options.to) {
253-
tasks.push(fs.outputFile(options.to, result.css))
253+
tasks.push(outputFile(options.to, result.css))
254254

255255
if (result.map) {
256256
const mapfile = getMapfile(options)
257-
tasks.push(fs.outputFile(mapfile, result.map.toString()))
257+
tasks.push(outputFile(mapfile, result.map.toString()))
258258
}
259259
} else process.stdout.write(result.css, 'utf8')
260260

@@ -278,6 +278,13 @@ function css(css, file) {
278278
.catch((err) => {
279279
throw err
280280
})
281+
282+
async function outputFile(file, string) {
283+
const fileExists = await fs.pathExists(file)
284+
const currentValue = fileExists ? await fs.readFile(file, 'utf8') : null
285+
if (currentValue === string) return
286+
return fs.outputFile(file, string)
287+
}
281288
}
282289

283290
function dependencies(results) {

test/fixtures/unchanged-input.css

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
body {
2+
color: red;
3+
}

test/fixtures/unchanged-output.css

Lines changed: 5 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

test/unchanged.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import fs from 'fs-extra'
2+
import test from 'ava'
3+
4+
import cli from './helpers/cli.js'
5+
6+
test('files are not saved if the contents are the same', async (t) => {
7+
const input = 'test/fixtures/unchanged-input.css'
8+
const output = 'test/fixtures/unchanged-output.css'
9+
const intialStat = await fs.stat(output)
10+
11+
const { error, stderr } = await cli([input, '-o', output])
12+
13+
t.falsy(error, stderr)
14+
15+
const finalStat = await fs.stat(output)
16+
t.is(finalStat.mtimeMs, intialStat.mtimeMs)
17+
})

0 commit comments

Comments
 (0)