Skip to content

Commit

Permalink
babel-register: Don鈥檛 rewrite the cache if it鈥檚 not dirty
Browse files Browse the repository at this point in the history
This saves time and avoids unnecessary SSD wear.

Signed-off-by: Anders Kaseorg <andersk@mit.edu>
  • Loading branch information
andersk committed Feb 17, 2021
1 parent 0e06a38 commit 0555576
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 4 deletions.
13 changes: 12 additions & 1 deletion packages/babel-register/src/cache.js
Expand Up @@ -13,6 +13,8 @@ const DEFAULT_FILENAME = path.join(
const FILENAME: string = process.env.BABEL_CACHE_PATH || DEFAULT_FILENAME;
let data: Object = {};

let cacheDirty = false;

let cacheDisabled = false;

function isCacheDisabled() {
Expand All @@ -23,7 +25,9 @@ function isCacheDisabled() {
*/

export function save() {
if (isCacheDisabled()) return;
if (isCacheDisabled() || !cacheDirty) return;
cacheDirty = false;

let serialised: string = "{}";

try {
Expand Down Expand Up @@ -112,6 +116,13 @@ export function get(): Object {
return data;
}

/**
* Set the cache dirty bit.
*/
export function setDirty() {
cacheDirty = true;
}

/**
* Clear the cache object.
*/
Expand Down
1 change: 1 addition & 0 deletions packages/babel-register/src/node.js
Expand Up @@ -69,6 +69,7 @@ function compile(code, filename) {
if (cache) {
cache[cacheKey] = cached;
cached.mtime = mtime(filename);
registerCache.setDirty();
}
}

Expand Down
17 changes: 14 additions & 3 deletions packages/babel-register/test/cache.js
Expand Up @@ -30,7 +30,7 @@ function resetCache() {

describe("@babel/register - caching", () => {
describe("cache", () => {
let load, get, save;
let load, get, setDirty, save;
let consoleWarnSpy;

beforeEach(() => {
Expand All @@ -40,6 +40,7 @@ describe("@babel/register - caching", () => {

load = cache.load;
get = cache.get;
setDirty = cache.setDirty;
save = cache.save;

consoleWarnSpy = jest.spyOn(console, "warn").mockImplementation(() => {});
Expand Down Expand Up @@ -73,15 +74,24 @@ describe("@babel/register - caching", () => {
expect(get()).toEqual({});
});

it("should create the cache on save", () => {
it("should not create the cache if not dirty", () => {
save();

expect(fs.existsSync(testCacheFilename)).toBe(false);
expect(get()).toEqual({});
});

it("should create the cache on save if dirty", () => {
setDirty();
save();

expect(fs.existsSync(testCacheFilename)).toBe(true);
expect(get()).toEqual({});
});

it("should create the cache after load", cb => {
it("should create the cache after dirty", cb => {
load();
setDirty();

process.nextTick(() => {
expect(fs.existsSync(testCacheFilename)).toBe(true);
Expand All @@ -107,6 +117,7 @@ describe("@babel/register - caching", () => {
writeCache({ foo: "bar" }, 0o466);

load();
setDirty();

expect(get()).toEqual({ foo: "bar" });
process.nextTick(() => {
Expand Down

0 comments on commit 0555576

Please sign in to comment.