Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
thecrypticace committed Aug 26, 2022
1 parent cce8b07 commit 28c4002
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions src/cli.js
Expand Up @@ -891,6 +891,36 @@ async function build() {
}
})

/**
* When rapidly saving files atomically a couple of situations can happen:
* - The file is missing since the external program has deleted it by the time we've gotten around to reading it from the earlier save.
* - The file is being written to by the external program by the time we're going to read it and is thus treated as busy because a lock is held.
*
* To work around this we retry reading the file a handful of times with a delay between each attempt
*
* @param {string} path
* @param {number} tries
* @returns {string}
* @throws {Error} If the file is still missing or busy after the specified number of tries
*/
async function readFileWithRetries(path, tries = 5) {
for (let n = 0; n < tries; n++) {
try {
return await fs.promises.readFile(path, 'utf8')
} catch (err) {
if (n < tries) {
if (err.code === 'ENOENT' || err.code === 'EBUSY') {
await new Promise((resolve) => setTimeout(resolve, 10))

continue
}
}

throw err
}
}
}

// Restore watching any files that are "removed"
// This can happen when a file is pseudo-atomically replaced (a copy is created, overwritten, the old one is unlinked, and the new one is renamed)
// TODO: An an optimization we should allow removal when the config changes
Expand Down

0 comments on commit 28c4002

Please sign in to comment.