Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Caching #14

Merged
merged 2 commits into from
Apr 11, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,14 @@ using [`watchify`][watchify], you will want to add the [`relateify`][relateify]
transform in order to ensure that changes to CSS files rebuild the appropriate
JS files.

## Caching

This module caches the results of the compilation of CSS files and stores the
cache in a directory under `/tmp/bptp-UNIQUE_ID`. The cache is only invalidated
when the CSS file contents change and not when the `postcss.config.js` file
changes (due to limitations at the time of implementation). Try removing the
cache if you're not seeing expected changes.

## Prior Art

This plugin is based of the work of:
Expand Down
5 changes: 3 additions & 2 deletions src/plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,10 @@ import {
// exceeds certain platform limits. for this reason, we're writing to /tmp
// instead of using os.tmpdir (which can, on platforms like darwin, be quite
// long & per-process).
const projectId = process.cwd().toLowerCase().replace(/[^a-z]/g, '');
const projectId = process.cwd().toLowerCase().replace(/[^a-z]/ig, '');
const socketName = `bptp-${projectId}.sock`;
const socketPath = join('/tmp', socketName);
const tmpPath = join('/tmp', `bptp-${projectId}`);

const nodeExecutable = process.argv[0];
const clientExcutable = join(__dirname, 'postcss-client.js');
Expand All @@ -27,7 +28,7 @@ const serverExcutable = join(__dirname, 'postcss-server.js');
let server;

const startServer = () => {
server = spawn(nodeExecutable, [serverExcutable, socketPath], {
server = spawn(nodeExecutable, [serverExcutable, socketPath, tmpPath], {
env: process.env, // eslint-disable-line no-process-env
stdio: 'inherit',
});
Expand Down
48 changes: 44 additions & 4 deletions src/postcss-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,17 @@ import net from 'net';
import fs from 'fs';
import path from 'path';
import util from 'util';
import crypto from 'crypto';
import makeDebug from 'debug';
import postcss from 'postcss';
import loadConfig from 'postcss-load-config';
import type { Socket, Server } from 'net';

const debug = makeDebug('babel-plugin-transform-postcss');
const streams = { stderr: process.stderr }; // overwritable by tests
const md5 = (data: string) => (
crypto.createHash('md5').update(data).digest('hex')
);
const error = (...args: any) => {
let prefix = 'babel-plugin-transform-postcss: ';
const message = util.format(...args);
Expand All @@ -22,7 +26,18 @@ const error = (...args: any) => {
streams.stderr.write(`${prefix}${message}\n`);
};

const main = async function main(socketPath: string): Promise<Server> {
const main = async function main(
socketPath: string,
tmpPath: string,
): Promise<Server> {

try { fs.mkdirSync(tmpPath); } // eslint-disable-line no-sync
catch (err) {
if (err.code !== 'EEXIST') {
throw err;
}
}

const options = { allowHalfOpen: true };
const server = net.createServer(options, (connection: Socket) => {
let data: string = '';
Expand All @@ -33,24 +48,49 @@ const main = async function main(socketPath: string): Promise<Server> {

connection.on('end', async (): Promise<void> => {
try {
let tokens;
let tokens, cache;
const { cssFile } = JSON.parse(data);
const cachePath =
`${path.join(tmpPath, cssFile.replace(/[^a-z]/ig, ''))}.cache`;
const source = // eslint-disable-next-line no-sync
fs.readFileSync(cssFile, 'utf8');
const hash = md5(source);

// eslint-disable-next-line no-sync
try { cache = JSON.parse(fs.readFileSync(cachePath, 'utf8')); }
catch (err) {
if (err.code !== 'ENOENT') {
throw err;
}
}

if (cache && cache.hash === hash) {
connection.end(JSON.stringify(cache.tokens));

return;
}

const extractModules = (_, resultTokens: any) => {
tokens = resultTokens;
};
const { plugins, options: postcssOpts } =
await loadConfig({ extractModules }, path.dirname(cssFile));

// eslint-disable-next-line no-sync
const source = fs.readFileSync(cssFile, 'utf8');
const runner = postcss(plugins);

await runner.process(source, Object.assign({
from: cssFile,
to: cssFile, // eslint-disable-line id-length
}, postcssOpts));

cache = {
hash,
tokens,
};

// eslint-disable-next-line no-sync
fs.writeFileSync(cachePath, JSON.stringify(cache));

connection.end(JSON.stringify(tokens));
}
catch (err) {
Expand Down
5 changes: 3 additions & 2 deletions test/plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,13 @@ describe('babel-plugin-transform-postcss', () => {
expect(childProcess.spawn).to.have.been.calledOnce;

const [executable, args, opts] = childProcess.spawn.getCall(0).args;
const [jsExecutable, socketPath] = args;
const [jsExecutable, socketPath, socketTmp] = args;

expect(executable).to.match(/node$/);
expect(args.length).to.eql(2);
expect(args.length).to.eql(3);
expect(jsExecutable).to.endWith('/postcss-server.js');
expect(socketPath).to.match(/^\/tmp.*\.sock$/);
expect(socketTmp).to.match(/^\/tmp/);
expect(opts).to.eql({
env: process.env, // eslint-disable-line no-process-env
stdio: 'inherit',
Expand Down
76 changes: 72 additions & 4 deletions test/postcss-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,11 @@ import { Server } from 'net';

const testSocket = join(__dirname, 'tmp.sock');
const testOutput = join(__dirname, 'tmp.out');
const testTmp = join(__dirname, 'tmp');

describe('postcss-server', () => {
let server, originalStderr;
const invokeMain = async () => { server = await main(testSocket); };
const invokeMain = async () => { server = await main(testSocket, testTmp); };
const closeServer = async() => {
await new Promise((resolve: () => void, reject: (Error) => void) => {
server.close((err: ?Error) => {
Expand All @@ -51,10 +52,17 @@ describe('postcss-server', () => {
beforeEach(() => {
originalStderr = streams.stderr;
streams.stderr = fs.createWriteStream(testOutput);
fs.mkdirSync(testTmp);
});
afterEach(() => {
streams.stderr = originalStderr;
fs.unlinkSync(testOutput);

for (const file of fs.readdirSync(testTmp)) {
fs.unlinkSync(path.join(testTmp, file));
}

fs.rmdirSync(testTmp);
});

describe('main(...testArgs)', () => {
Expand All @@ -79,6 +87,7 @@ describe('postcss-server', () => {
expect(fs.existsSync(testSocket)).to.be.false;
});

const simpleCSSFile = join(__dirname, 'fixtures', 'simple.css');
const sendMessage = async (
json: {
cssFile: string,
Expand Down Expand Up @@ -106,7 +115,7 @@ describe('postcss-server', () => {

it('accepts JSON details and extracts PostCSS modules', async () => {
const response = await sendMessage({
cssFile: join(__dirname, 'fixtures', 'simple.css'),
cssFile: simpleCSSFile,
});

expect(JSON.parse(response)).to.eql({ simple: '_simple_jvai8_1' });
Expand All @@ -120,6 +129,50 @@ describe('postcss-server', () => {
expect(response).to.eql('');
});

describe('with a cached result', () => {
beforeEach(() => {
const name = simpleCSSFile.replace(/[^a-z]/ig, '');

fs.writeFileSync(path.join(testTmp, `${name}.cache`), JSON.stringify({
hash: 'e773de66362a5c384076b75ac292038b',
tokens: { simple: '_simple_cached' },
}));
});

it('accepts JSON details and extracts PostCSS modules', async () => {
const response = await sendMessage({
cssFile: simpleCSSFile,
});

expect(JSON.parse(response)).to.eql({ simple: '_simple_cached' });
});
});

describe('with an invalid cache', () => {
let response;

beforeEach(() => {
const name = simpleCSSFile.replace(/[^a-z]/ig, '');

fs.writeFileSync(path.join(testTmp, `${name}.cache`), 'not-json');
});
beforeEach(async () => {
response = await sendMessage({
cssFile: simpleCSSFile,
});
});
beforeEach(closeStderr);

it('does not contain a response', () => {
expect(response).to.eql('');
});

it('logs a useful message', () => {
expect(fs.readFileSync(testOutput, 'utf8'))
.to.match(/JSON/i);
});
});

describe('with a missing CSS file', () => {
let response;

Expand All @@ -143,7 +196,7 @@ describe('postcss-server', () => {
describe('with a missing config file', () => {
let response;

beforeEach(() => stub(path, 'dirname', () => process.cwd()));
beforeEach(() => stub(path, 'dirname').callsFake(() => process.cwd()));
afterEach(() => path.dirname.restore());

beforeEach(async () => {
Expand All @@ -167,7 +220,7 @@ describe('postcss-server', () => {

describe('when listen fails', () => {
beforeEach(() => {
stub(Server.prototype, 'listen', function errorHandler() {
stub(Server.prototype, 'listen').callsFake(function errorHandler() {
this.emit('error', new Error('test failure'));
});
});
Expand Down Expand Up @@ -218,4 +271,19 @@ describe('postcss-server', () => {
});

});

describe('when making a directory fails', () => {
beforeEach(() => { stub(fs, 'mkdirSync').throws('Error with no code'); });
afterEach(() => { fs.mkdirSync.restore(); });

it('errors when invoking main', async () => {
let error;

try { await invokeMain(); }
catch (err) { error = err; }

expect(error).to.match(/Error with no code/);
});
});

});