Skip to content

Commit

Permalink
Avoid writing to output files when no changes (#6550)
Browse files Browse the repository at this point in the history
* 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>
  • Loading branch information
g3offrey and RobinMalfait committed Jan 4, 2022
1 parent 722232c commit 0bcd628
Showing 1 changed file with 13 additions and 3 deletions.
16 changes: 13 additions & 3 deletions src/cli.js
Expand Up @@ -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

Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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)
)
})
Expand Down

0 comments on commit 0bcd628

Please sign in to comment.