Skip to content

Commit

Permalink
Merge ba34e61 into 01ea2c5
Browse files Browse the repository at this point in the history
  • Loading branch information
bezoerb committed Jun 11, 2020
2 parents 01ea2c5 + ba34e61 commit 3d306f7
Show file tree
Hide file tree
Showing 8 changed files with 69 additions and 35 deletions.
8 changes: 4 additions & 4 deletions index.js
Expand Up @@ -3,11 +3,11 @@
'use strict';

const path = require('path');
const fs = require('fs-extra');
const through2 = require('through2');
const PluginError = require('plugin-error');
const replaceExtension = require('replace-ext');
const {create} = require('./src/core');
const {outputFileAsync} = require('./src/file');
const {getOptions} = require('./src/config');

/**
Expand All @@ -23,17 +23,17 @@ async function generate(params, cb) {
const result = await create(options);
// Store generated css
if (target.css) {
await fs.outputFile(path.resolve(base, target.css), result.css);
await outputFileAsync(path.resolve(base, target.css), result.css);
}

// Store generated html
if (target.html) {
await fs.outputFile(path.resolve(base, target.html), result.html);
await outputFileAsync(path.resolve(base, target.html), result.html);
}

// Store extracted css
if (target.uncritical) {
await fs.outputFile(path.resolve(base, target.uncritical), result.uncritical);
await outputFileAsync(path.resolve(base, target.uncritical), result.uncritical);
}

if (typeof cb === 'function') {
Expand Down
21 changes: 12 additions & 9 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Expand Up @@ -33,7 +33,6 @@
"css-url-parser": "^1.1.3",
"debug": "^4.1.1",
"find-up": "^4.1.0",
"fs-extra": "^9.0.0",
"get-stdin": "^8.0.0",
"globby": "^11.0.0",
"got": "^9.6.0",
Expand All @@ -42,6 +41,7 @@
"inline-critical": "^6.0.0",
"is-glob": "^4.0.1",
"lodash": "^4.17.15",
"make-dir": "^3.1.0",
"meow": "^7.0.1",
"oust": "^1.0.1",
"p-all": "^3.0.0",
Expand Down
29 changes: 23 additions & 6 deletions src/file.js
Expand Up @@ -3,8 +3,10 @@
const path = require('path');
const os = require('os');
const url = require('url');
const fs = require('fs-extra');
const fs = require('fs');
const {promisify} = require('util');
const findUp = require('find-up');
const makeDir = require('make-dir');
const globby = require('globby');
const isGlob = require('is-glob');
const postcss = require('postcss');
Expand All @@ -24,6 +26,20 @@ const BASE_WARNING = `${chalk.yellow('Warning:')} Missing base path. Consider 'b

const warn = (text) => process.stderr.write(chalk.yellow(`${text}${os.EOL}`));

const unlinkAsync = promisify(fs.unlink);
const readFileAsync = promisify(fs.readFile);
const writeFileAsync = promisify(fs.writeFile);

async function outputFileAsync(file, data) {
const dir = path.dirname(file);

if (!fs.existsSync(dir)) {
await makeDir(dir);
}

return writeFileAsync(file, data);
}

/**
* Fixup slashes in file paths for Windows and remove volume definition in front
* @param {string} str Path
Expand Down Expand Up @@ -155,7 +171,7 @@ async function fileExists(href, options = {}) {
const getCleanup = (files) => () =>
forEachAsync(files, (file) => {
try {
fs.remove(file);
unlinkAsync(file);
} catch (_) {
debug(`${file} was already deleted`);
}
Expand Down Expand Up @@ -651,7 +667,7 @@ async function vinylize(src, options = {}) {
} else if (filepath && fs.existsSync(filepath)) {
file.path = filepath;
file.virtualPath = filepath;
file.contents = await fs.readFile(filepath);
file.contents = await readFileAsync(filepath);
} else {
throw new FileNotFoundError(filepath);
}
Expand Down Expand Up @@ -800,22 +816,22 @@ async function preparePenthouseData(document) {
// when served from file://
const injected = htmlContent.replace(/(<head(?:\s[^>]*)?>)/gi, `$1<style>${document.css.toString()}</style>`);
// Write html to temp file
await fs.outputFile(file, injected);
await outputFileAsync(file, injected);

tmp.push(file);

// Write styles to first stylesheet
if (stylesheet) {
const filename = path.join(dir, stylesheet);
tmp.push(filename);
await fs.outputFile(filename, document.css);
await outputFileAsync(filename, document.css);
}

// Write empty string to rest of the linked stylesheets
await forEachAsync(canBeEmpty, (dummy) => {
const filename = path.join(dir, dummy);
tmp.push(filename);
fs.outputFile(filename, '');
outputFileAsync(filename, '');
});

return [getFileUri(file), getCleanup(tmp)];
Expand Down Expand Up @@ -913,4 +929,5 @@ module.exports = {
getStylesheet,
getDocument,
getDocumentFromSource,
outputFileAsync,
};
4 changes: 2 additions & 2 deletions test/blackbox.test.js
Expand Up @@ -6,7 +6,7 @@ const getPort = require('get-port');
const Vinyl = require('vinyl');
const nock = require('nock');
const async = require('async');
const fs = require('fs-extra');
const fs = require('fs');
const finalhandler = require('finalhandler');
const serveStatic = require('serve-static');
const nn = require('normalize-newline');
Expand Down Expand Up @@ -155,7 +155,7 @@ describe('generate (local)', () => {
},
(err) => {
expect(err).toBeInstanceOf(Error);
fs.remove(target, () => done());
fs.unlink(target, () => done());
}
);
});
Expand Down
19 changes: 11 additions & 8 deletions test/file.test.js
Expand Up @@ -4,8 +4,9 @@

const {createServer} = require('http');
const path = require('path');
const {promisify} = require('util');
const getPort = require('get-port');
const fs = require('fs-extra');
const fs = require('fs');
const Vinyl = require('vinyl');
const finalhandler = require('finalhandler');
const serveStatic = require('serve-static');
Expand All @@ -30,6 +31,8 @@ const {
} = require('../src/file');
const {read} = require('./helper');

const readFileAsync = promisify(fs.readFile);

// Setup static fileserver to mimic remote requests
let server;
let port;
Expand Down Expand Up @@ -159,7 +162,7 @@ test('Vinylize local file', async () => {
path.join(__dirname, 'fixtures/head.html'),
];

const contents = await Promise.all(files.map((f) => fs.readFile(f)));
const contents = await Promise.all(files.map((f) => readFileAsync(f)));
const result = await Promise.all(files.map((filepath) => vinylize({filepath})));

expect.hasAssertions();
Expand All @@ -184,7 +187,7 @@ test('Vinylize remote file', async () => {
'fixtures/images/critical.png',
];

const contents = await Promise.all(files.map((f) => fs.readFile(path.join(__dirname, f))));
const contents = await Promise.all(files.map((f) => readFileAsync(path.join(__dirname, f))));

const urls = files.map((f) => f.replace(/^fixtures/, `http://localhost:${port}`));
const result = await Promise.all(urls.map((filepath) => vinylize({filepath})));
Expand Down Expand Up @@ -362,7 +365,7 @@ test('Get document from source with rebase option', async () => {
for (const testdata of tests) {
const {filepath, expected} = testdata;
const rebase = {to: `/${normalizePath(path.relative(base, filepath))}`};
const source = await fs.readFile(filepath);
const source = await readFileAsync(filepath);
const file = await getDocumentFromSource(source, {rebase, base});
expect(file.virtualPath).toBe(expected);
}
Expand All @@ -372,10 +375,10 @@ test('Get document from source with rebase option', async () => {

test('Get document from source without path options', async () => {
const filepath = path.join(__dirname, 'fixtures/folder/subfolder/head.html');
const source = await fs.readFile(filepath);
const source = await readFileAsync(filepath);
const css = path.join(__dirname, 'fixtures/styles/image-relative.css');
const file = await getDocumentFromSource(source, {css});
const styles = await fs.readFile(css, 'utf8');
const styles = await readFileAsync(css, 'utf8');

// expect(file.path).toBe(undefined);
expect(file.css).toMatch(styles);
Expand Down Expand Up @@ -515,7 +518,7 @@ test('Get styles (without path)', async () => {
path.join(__dirname, 'fixtures/relative-different.html'),
path.join(__dirname, 'fixtures/remote-different.html'),
],
(file) => fs.readFile(file)
(file) => readFileAsync(file)
);

const tests = [
Expand Down Expand Up @@ -558,7 +561,7 @@ test('Does not rebase when rebase is disabled via option', async () => {
path.join(__dirname, 'fixtures/relative-different.html'),
path.join(__dirname, 'fixtures/remote-different.html'),
],
(file) => fs.readFile(file)
(file) => readFileAsync(file)
);

const tests = [
Expand Down
2 changes: 1 addition & 1 deletion test/helper/index.js
@@ -1,7 +1,7 @@
'use strict';

const path = require('path');
const fs = require('fs-extra');
const fs = require('fs');
const array = require('stream-array');
const Vinyl = require('vinyl');
const nn = require('normalize-newline');
Expand Down
19 changes: 15 additions & 4 deletions test/index.test.js
@@ -1,7 +1,8 @@
'use strict';

const path = require('path');
const fs = require('fs-extra');
const {promisify} = require('util');
const fs = require('fs');
const vinylStream = require('vinyl-source-stream');
const Vinyl = require('vinyl');
const PluginError = require('plugin-error');
Expand All @@ -14,6 +15,8 @@ const {generate, stream} = require('..');

jest.setTimeout(20000);

const unlinkAsync = promisify(fs.unlink);

let stderr;
beforeEach(() => {
stderr = jest.spyOn(process.stderr, 'write').mockImplementation(() => true);
Expand Down Expand Up @@ -102,7 +105,11 @@ test('Write all targets relative to base', async () => {
expect(html).toBe(data.html);
expect(css).toBe(data.css);

await fs.remove(base);
try {
await unlinkAsync(base);
} catch {
// file not there
}
});

test('Write all targets respecting absolute paths', async () => {
Expand All @@ -128,8 +135,12 @@ test('Write all targets respecting absolute paths', async () => {
expect(html).toBe(data.html);
expect(css).toBe(data.css);

await fs.remove(base);
await fs.remove(fileBase);
try {
await unlinkAsync(base);
await unlinkAsync(fileBase);
} catch {
// file already deleted
}
});

test('Reject with ConfigError on invalid config', () => {
Expand Down

0 comments on commit 3d306f7

Please sign in to comment.