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

✨ Autoload plugins #175

Merged
merged 4 commits into from
Feb 8, 2021
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
1 change: 1 addition & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ jobs:
- '@percy/dom'
- '@percy/config'
- '@percy/core'
- '@percy/cli'
- '@percy/cli-command'
- '@percy/cli-exec'
- '@percy/cli-snapshot'
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/bin/run
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#!/usr/bin/env node

require('@oclif/command').run()
require('@percy/cli').run()
.then(require('@oclif/command/flush'))
.catch(require('@oclif/errors/handle'))
45 changes: 43 additions & 2 deletions packages/cli/index.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,43 @@
// This package is a multi-command oclif CLI composed of plugins that provide
// various functionalities for taking Percy snapshots.
const { promises: fs } = require('fs');
const path = require('path');

// find plugins in a directory, matching a regexp, ignoring registered plugins
function findPlugins(dir, regexp, registered) {
return fs.readdir(dir).then(f => f.reduce((plugins, dirname) => {
if (dirname === 'cli' || !regexp.test(dirname)) return plugins;

let { name, oclif } = require(`${dir}/${dirname}/package.json`);

if (!registered.includes(name) && oclif && oclif.bin === 'percy') {
return plugins.concat(name);
} else {
return plugins;
}
}, []));
}

// automatically register/unregister plugins by altering the CLI's package.json within node_modules
async function autoRegisterPlugins() {
let pkgPath = path.resolve(__dirname, 'package.json');
let pkg = require(pkgPath);

let registered = pkg.oclif.plugins.filter(plugin => {
if (pkg.dependencies[plugin]) return true;
try { return !!require.resolve(plugin); } catch {}
return false;
});

let unregistered = await Promise.all([
findPlugins(path.resolve(__dirname, '..'), /^.*/, registered), // @percy/*
findPlugins(path.resolve(__dirname, '../..'), /^percy-cli-.*/, registered) // percy-cli-*
]).then(p => Array.from(new Set(p.flat())));

if (unregistered.length || registered.length !== pkg.oclif.plugins.length) {
pkg.oclif.plugins = registered.concat(unregistered);
await fs.writeFile(pkgPath, JSON.stringify(pkg, null, 2) + '\n');
}
}

// auto register plugins before running oclif
module.exports.run = () => autoRegisterPlugins()
.then(() => require('@oclif/command').run());
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very slick 💯

10 changes: 6 additions & 4 deletions packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,15 @@
},
"scripts": {
"lint": "eslint --ignore-path ../../.gitignore .",
"postbuild": "oclif-dev manifest"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So the manifest is only for linking with the plugins plugin?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The manifest is for telling OCLIF which commands the CLI / plugin contain. This CLI package not only doesn't export any commands itself, but it has no build step so the postbuild step never ran to generate the empty file to begin with.

"test": "cross-env NODE_ENV=test mocha",
"test:coverage": "nyc yarn test"
},
"publishConfig": {
"access": "public"
},
"mocha": {
"require": "../../scripts/babel-register"
},
"oclif": {
"bin": "percy",
"plugins": [
Expand All @@ -29,13 +33,11 @@
"@percy/cli-build",
"@percy/cli-snapshot",
"@percy/cli-upload",
"@oclif/plugin-help",
"@oclif/plugin-plugins"
"@oclif/plugin-help"
]
},
"dependencies": {
"@oclif/plugin-help": "^3.2.0",
"@oclif/plugin-plugins": "^1.9.0",
"@percy/cli-build": "^1.0.0-beta.34",
"@percy/cli-config": "^1.0.0-beta.34",
"@percy/cli-exec": "^1.0.0-beta.34",
Expand Down
2 changes: 2 additions & 0 deletions packages/cli/test/.eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
env:
mocha: true
51 changes: 51 additions & 0 deletions packages/cli/test/helpers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import path from 'path';
import mockRequire from 'mock-require';

export function pluginMocker() {
let pkgPath = path.resolve(__dirname, '../package.json');

let mock = ({ plugins, packages }) => {
for (let [name, dep] of Object.entries(plugins)) {
if (dep) mock.pkg.dependencies[name] = true;
mock.pkg.oclif.plugins.push(name);
}

for (let [name, plugin] of Object.entries(packages)) {
let dir = path.resolve(__dirname, name.startsWith('@percy') ? '../..' : '../../..');
let dirname = name.replace('@percy', '');

mock.dir[dir].push(dirname);
mockRequire(`${dir}/${dirname}/package.json`, plugin ? (
{ name, oclif: { bin: 'percy' } }
) : { name });
}
};

mock.pkg = {
oclif: { plugins: [] },
dependencies: {}
};

mock.dir = {
[path.resolve(__dirname, '../..')]: [],
[path.resolve(__dirname, '../../..')]: []
};

mockRequire(pkgPath, mock.pkg);
mockRequire('fs', {
...require('fs'),

promises: {
readdir: async dir => mock.dir[dir],
writeFile: async (path, contents) => {
if (path === pkgPath) {
mock.pkg = JSON.parse(contents);
}
}
}
});

return mock;
}

export { mockRequire };
80 changes: 80 additions & 0 deletions packages/cli/test/index.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import expect from 'expect';
import { pluginMocker, mockRequire } from './helpers';

describe('Plugin auto-registration', () => {
let mock, run;

beforeEach(() => {
mock = pluginMocker();
mockRequire('@oclif/command', { run() {} });
run = mockRequire.reRequire('..').run;
});

afterEach(() => {
mockRequire.stopAll();
});

it('adds unregistered plugins to the package.json', async () => {
mock({
plugins: {
'@percy/cli-exec': true
},
packages: {
'@percy/cli-config': true,
'@percy/cli-exec': true,
'@percy/core': false,
'@percy/storybook': true,
'percy-cli-custom': true,
'percy-cli-no': false,
'percy-custom': true
}
});

await run();

expect(mock.pkg.oclif.plugins).toEqual([
'@percy/cli-exec',
'@percy/cli-config',
'@percy/storybook',
'percy-cli-custom'
]);
});

it('removes missing plugins from the package.json', async () => {
mock({
plugins: {
'@percy/cli-exec': true,
'@percy/cli-other': false
},
packages: {
'@percy/cli-exec': true
}
});

await run();

expect(mock.pkg.oclif.plugins).toEqual([
'@percy/cli-exec'
]);
});

it('does nothing when plugins are registered', async () => {
mock({
plugins: {
'@percy/cli-exec': true,
'@percy/cli-other': true
},
packages: {
'@percy/cli-exec': true,
'@percy/cli-other': true
}
});

await run();

expect(mock.pkg.oclif.plugins).toEqual([
'@percy/cli-exec',
'@percy/cli-other'
]);
});
});
Loading