Avoid writing to output files when no changes (#6550)

* fix(cli): avoid write same output when no changes

* generalize outputFile

This function will check a cache, it will only write the file if:
- The modified timestamps changed since last time we wrote something.
  This is useful to know if something changed by another tool or
  manually without diffing the full file.
- The contents changed.

* further simplify checks

Turns out that reading files and comparing them is fairly fast and there
is no huge benefit over only using the Stats of the file and keeping
track of that information.

Thanks @kentcdodds!

Co-authored-by: Robin Malfait <malfait.robin@gmail.com>
This commit is contained in:
Geoffrey 2022-01-04 16:29:16 +01:00 committed by GitHub
parent 722232cb2e
commit 0bcd628ec3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -41,6 +41,15 @@ function formatNodes(root) {
}
}
async function outputFile(file, contents) {
if (fs.existsSync(file) && (await fs.promises.readFile(file, 'utf8')) === contents) {
return // Skip writing the file
}
// Write the file
await fs.promises.writeFile(file, contents, 'utf8')
}
function help({ message, usage, commands, options }) {
let indent = 2
@ -534,6 +543,7 @@ async function build() {
if (!output) {
return process.stdout.write(result.css)
}
return Promise.all(
[
fs.promises.writeFile(output, result.css, () => true),
@ -664,10 +674,10 @@ async function build() {
return process.stdout.write(result.css)
}
await Promise.all(
return Promise.all(
[
fs.promises.writeFile(output, result.css, () => true),
result.map && fs.writeFile(output + '.map', result.map.toString(), () => true),
outputFile(output, result.css),
result.map && outputFile(output + '.map', result.map.toString()),
].filter(Boolean)
)
})