Skip to content

Commit

Permalink
Invalidate cache when dependencies included in parent change (#514)
Browse files Browse the repository at this point in the history
Some dependencies are pre-compiled into their parent assets, e.g. stylus imports. But we still need to invalidate the cache if any of those files change.

Now the FSCache looks for deps with `includedInParent: true`, and stores an mtime in the cache file. When reading from the cache, those deps are checked to see if they changed and if so, the parent asset is invalidated.
  • Loading branch information
devongovett committed Jan 8, 2018
1 parent 9143f4b commit b8e8973
Showing 1 changed file with 33 additions and 3 deletions.
36 changes: 33 additions & 3 deletions src/FSCache.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ const path = require('path');
const md5 = require('./utils/md5');
const objectHash = require('./utils/objectHash');
const pkg = require('../package.json');
const json5 = require('json5');

// These keys can affect the output, so if they differ, the cache should not match
const OPTION_KEYS = ['publicURL', 'minify', 'hmr'];
Expand All @@ -30,16 +29,42 @@ class FSCache {
return path.join(this.dir, hash + '.json');
}

async writeDepMtimes(data) {
// Write mtimes for each dependent file that is already compiled into this asset
for (let dep of data.dependencies) {
if (dep.includedInParent) {
let stats = await fs.stat(dep.name);
dep.mtime = stats.mtime.getTime();
}
}
}

async write(filename, data) {
try {
await this.ensureDirExists();
await this.writeDepMtimes(data);
await fs.writeFile(this.getCacheFile(filename), JSON.stringify(data));
this.invalidated.delete(filename);
} catch (err) {
console.error('Error writing to cache', err);
}
}

async checkDepMtimes(data) {
// Check mtimes for files that are already compiled into this asset
// If any of them changed, invalidate.
for (let dep of data.dependencies) {
if (dep.includedInParent) {
let stats = await fs.stat(dep.name);
if (stats.mtime > dep.mtime) {
return false;
}
}
}

return true;
}

async read(filename) {
if (this.invalidated.has(filename)) {
return null;
Expand All @@ -55,8 +80,13 @@ class FSCache {
return null;
}

let data = await fs.readFile(cacheFile);
return json5.parse(data);
let json = await fs.readFile(cacheFile);
let data = JSON.parse(json);
if (!await this.checkDepMtimes(data)) {
return null;
}

return data;
} catch (err) {
return null;
}
Expand Down

0 comments on commit b8e8973

Please sign in to comment.