Skip to content

Commit

Permalink
Allow specifying reporters on the CLI (parcel-bundler#5905)
Browse files Browse the repository at this point in the history
  • Loading branch information
mischnic authored Mar 3, 2021
1 parent 806cc65 commit 6ce9e70
Show file tree
Hide file tree
Showing 19 changed files with 110 additions and 57 deletions.
6 changes: 1 addition & 5 deletions packages/configs/default/index.json
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,5 @@
"*.{jsonld,webmanifest}": "@parcel/packager-raw-url",
"*": "@parcel/packager-raw"
},
"resolvers": ["@parcel/resolver-default"],
"reporters": [
"@parcel/reporter-cli",
"@parcel/reporter-dev-server"
]
"resolvers": ["@parcel/resolver-default"]
}
2 changes: 0 additions & 2 deletions packages/configs/default/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,6 @@
"@parcel/optimizer-terser": "2.0.0-beta.1",
"@parcel/packager-js": "2.0.0-beta.1",
"@parcel/packager-raw": "2.0.0-beta.1",
"@parcel/reporter-cli": "2.0.0-beta.1",
"@parcel/reporter-dev-server": "2.0.0-beta.1",
"@parcel/resolver-default": "2.0.0-beta.1",
"@parcel/runtime-browser-hmr": "2.0.0-beta.1",
"@parcel/runtime-js": "2.0.0-beta.1",
Expand Down
17 changes: 3 additions & 14 deletions packages/core/core/src/BundlerRunner.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,9 @@
// @flow strict-local

import type {AbortSignal} from 'abortcontroller-polyfill/dist/cjs-ponyfill';
import type {
Bundle as IBundle,
Namer,
FilePath,
ConfigOutput,
} from '@parcel/types';
import type {Bundle as IBundle, Namer, ConfigOutput} from '@parcel/types';
import type WorkerFarm, {SharedReference} from '@parcel/workers';
import type ParcelConfig from './ParcelConfig';
import type ParcelConfig, {LoadedPlugin} from './ParcelConfig';
import type RequestTracker from './RequestTracker';
import type {Bundle as InternalBundle, ParcelOptions} from './types';

Expand Down Expand Up @@ -210,13 +205,7 @@ export default class BundlerRunner {
}

async nameBundle(
namers: Array<{|
name: string,
version: string,
plugin: Namer,
resolveFrom: FilePath,
keyPath: string,
|}>,
namers: Array<LoadedPlugin<Namer>>,
internalBundle: InternalBundle,
internalBundleGraph: InternalBundleGraph,
): Promise<void> {
Expand Down
2 changes: 1 addition & 1 deletion packages/core/core/src/ParcelConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export type LoadedPlugin<T> = {|
version: Semver,
plugin: T,
resolveFrom: FilePath,
keyPath: string,
keyPath?: string,
|};

export default class ParcelConfig {
Expand Down
2 changes: 1 addition & 1 deletion packages/core/core/src/Transformation.js
Original file line number Diff line number Diff line change
Expand Up @@ -859,7 +859,7 @@ type TransformerWithNameAndConfig = {|
name: PackageName,
plugin: Transformer,
config: ?Config,
configKeyPath: string,
configKeyPath?: string,
resolveFrom: FilePath,
|};

Expand Down
2 changes: 1 addition & 1 deletion packages/core/core/src/UncommittedAsset.js
Original file line number Diff line number Diff line change
Expand Up @@ -351,7 +351,7 @@ export default class UncommittedAsset {
result: TransformerResult,
plugin: PackageName,
configPath: FilePath,
configKeyPath: string,
configKeyPath?: string,
): UncommittedAsset {
let content = result.content ?? null;

Expand Down
30 changes: 17 additions & 13 deletions packages/core/core/src/loadParcelPlugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ const NODE_MODULES = `${path.sep}node_modules${path.sep}`;
export default async function loadPlugin<T>(
pluginName: PackageName,
configPath: FilePath,
keyPath: string,
keyPath?: string,
options: ParcelOptions,
): Promise<{|plugin: T, version: Semver, resolveFrom: FilePath|}> {
let resolveFrom = configPath;
Expand Down Expand Up @@ -105,18 +105,22 @@ export default async function loadPlugin<T>(
origin: '@parcel/core',
filePath: configPath,
language: 'json5',
codeFrame: {
code: configContents,
codeHighlights: generateJSONCodeHighlights(configContents, [
{
key: keyPath,
type: 'value',
message: md`Cannot find module "${pluginName}"${
alternatives[0] ? `, did you mean "${alternatives[0]}"?` : ''
}`,
},
]),
},
codeFrame: keyPath
? {
code: configContents,
codeHighlights: generateJSONCodeHighlights(configContents, [
{
key: keyPath,
type: 'value',
message: md`Cannot find module "${pluginName}"${
alternatives[0]
? `, did you mean "${alternatives[0]}"?`
: ''
}`,
},
]),
}
: undefined,
},
});
}
Expand Down
11 changes: 11 additions & 0 deletions packages/core/core/src/requests/ParcelConfigRequest.js
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,17 @@ export async function resolveParcelConfig(
contents,
options,
);

if (options.additionalReporters.length > 0) {
config.reporters = [
...options.additionalReporters.map(({packageName, resolveFrom}) => ({
packageName,
resolveFrom,
})),
...(config.reporters ?? []),
];
}

return {config, extendedFiles, usedDefault};
}

Expand Down
1 change: 1 addition & 0 deletions packages/core/core/src/resolveOptions.js
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ export default async function resolveOptions(
outputFS,
cache,
packageManager,
additionalReporters: initialOptions.additionalReporters ?? [],
instanceId: generateInstanceId(entries),
detailedReport: initialOptions.detailedReport,
defaultTargetOptions: {
Expand Down
6 changes: 5 additions & 1 deletion packages/core/core/src/types.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ import type {PackageManager} from '@parcel/package-manager';
export type ParcelPluginNode = {|
packageName: PackageName,
resolveFrom: FilePath,
keyPath: string,
keyPath?: string,
|};

export type PureParcelConfigPipeline = $ReadOnlyArray<ParcelPluginNode>;
Expand Down Expand Up @@ -196,6 +196,10 @@ export type ParcelOptions = {|
outputFS: FileSystem,
cache: Cache,
packageManager: PackageManager,
additionalReporters: Array<{|
packageName: ModuleSpecifier,
resolveFrom: FilePath,
|}>,

instanceId: string,

Expand Down
1 change: 1 addition & 0 deletions packages/core/core/src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ const ignoreOptions = new Set([
'shouldProfile',
'shouldPatchConsole',
'projectRoot',
'additionalReporters',
]);

export function optionsProxy(
Expand Down
1 change: 1 addition & 0 deletions packages/core/core/test/test-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ export const DEFAULT_OPTIONS: ParcelOptions = {
cache,
shouldPatchConsole: false,
packageManager: new NodePackageManager(inputFS),
additionalReporters: [],
instanceId: 'test',
defaultTargetOptions: {
shouldScopeHoist: false,
Expand Down
23 changes: 23 additions & 0 deletions packages/core/integration-tests/test/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,27 @@ describe('JS API', function() {

assert(await outputFS.exists(path.join(distDir, NAME)));
});

it('should run additional reports from the options', async function() {
let b = await bundle(
path.join(__dirname, '/integration/js-comment/index.js'),
{
additionalReporters: [
{
packageName: '@parcel/reporter-bundle-buddy',
resolveFrom: __dirname,
},
],
},
);

assertBundles(b, [
{
type: 'js',
assets: ['index.js'],
},
]);

assert(await outputFS.exists(path.join(distDir, 'bundle-buddy.json')));
});
});
2 changes: 1 addition & 1 deletion packages/core/package-manager/src/Yarn.js
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ export class Yarn implements PackageInstaller {
try {
return await promiseFromProcess(installProcess);
} catch (e) {
throw new Error('Yarn failed to install modules');
throw new Error('Yarn failed to install modules:' + e.message);
}
}
}
Expand Down
2 changes: 2 additions & 0 deletions packages/core/parcel/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
"@parcel/fs": "2.0.0-beta.1",
"@parcel/logger": "2.0.0-beta.1",
"@parcel/package-manager": "2.0.0-beta.1",
"@parcel/reporter-cli": "2.0.0-beta.1",
"@parcel/reporter-dev-server": "2.0.0-beta.1",
"@parcel/utils": "2.0.0-beta.1",
"chalk": "^4.1.0",
"commander": "^7.0.0",
Expand Down
30 changes: 26 additions & 4 deletions packages/core/parcel/src/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,10 +81,18 @@ const commonOptions = {
'--profile': 'enable build profiling',
'-V, --version': 'output the version number',
'--detailed-report [count]': [
'Print the asset timings and sizes in the build report',
'print the asset timings and sizes in the build report',
parseOptionInt,
'10',
],
'--reporter <name>': [
'additional reporters to run',
(val, acc) => {
acc.push(val);
return acc;
},
[],
],
};

var hmrOptions = {
Expand Down Expand Up @@ -201,17 +209,18 @@ async function run(
entries = entries.map(entry => path.resolve(entry));

if (entries.length === 0) {
// TODO move this into core, a glob could still lead to no entries
INTERNAL_ORIGINAL_CONSOLE.log('No entries found');
return;
}
let Parcel = require('@parcel/core').default;
let options = await normalizeOptions(command);
let fs = new NodeFS();
let options = await normalizeOptions(command, fs);
let packageManager = new NodePackageManager(fs);
let parcel = new Parcel({
entries,
packageManager,
// $FlowFixMe - flow doesn't know about the `paths` option (added in Node v8.9.0)
// $FlowFixMe[extra-arg] - flow doesn't know about the `paths` option (added in Node v8.9.0)
defaultConfig: require.resolve('@parcel/config-default', {
paths: [fs.cwd(), __dirname],
}),
Expand Down Expand Up @@ -358,7 +367,10 @@ function parseOptionInt(value) {
return parsedValue;
}

async function normalizeOptions(command): Promise<InitialParcelOptions> {
async function normalizeOptions(
command,
inputFS,
): Promise<InitialParcelOptions> {
let nodeEnv;
if (command.name() === 'build') {
nodeEnv = process.env.NODE_ENV || 'production';
Expand Down Expand Up @@ -423,6 +435,15 @@ async function normalizeOptions(command): Promise<InitialParcelOptions> {
command.detailedReport = '10';
}

let additionalReporters = [
{packageName: '@parcel/reporter-cli', resolveFrom: __filename},
{packageName: '@parcel/reporter-dev-server', resolveFrom: __filename},
...(command.reporter: Array<string>).map(packageName => ({
packageName,
resolveFrom: path.join(inputFS.cwd(), 'index'),
})),
];

let mode = command.name() === 'build' ? 'production' : 'development';
return {
shouldDisableCache: command.cache === false,
Expand All @@ -445,6 +466,7 @@ async function normalizeOptions(command): Promise<InitialParcelOptions> {
env: {
NODE_ENV: nodeEnv,
},
additionalReporters,
defaultTargetOptions: {
shouldOptimize:
command.optimize != null ? command.optimize : mode === 'production',
Expand Down
5 changes: 5 additions & 0 deletions packages/core/types/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,11 @@ export type InitialParcelOptions = {|
+engines?: Engines,
|},

+additionalReporters?: Array<{|
packageName: ModuleSpecifier,
resolveFrom: FilePath,
|}>,

// throwErrors
// global?
|};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,7 @@ import nullthrows from 'nullthrows';

export default (new Reporter({
async report({event, options}) {
if (
event.type !== 'buildSuccess' ||
process.env.PARCEL_BUNDLE_ANALYZER == null ||
// $FlowFixMe
process.env.PARCEL_BUNDLE_ANALYZER == false
) {
if (event.type !== 'buildSuccess') {
return;
}

Expand Down
17 changes: 9 additions & 8 deletions packages/reporters/bundle-buddy/src/BundleBuddyReporter.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,8 @@ import {Reporter} from '@parcel/plugin';
import path from 'path';

export default (new Reporter({
async report({event, options}) {
if (
event.type !== 'buildSuccess' ||
process.env.BUNDLE_BUDDY == null ||
// $FlowFixMe
process.env.BUNDLE_BUDDY == false
) {
async report({event, options, logger}) {
if (event.type !== 'buildSuccess') {
return;
}

Expand Down Expand Up @@ -48,9 +43,15 @@ export default (new Reporter({
}

await options.outputFS.writeFile(
`${targetDir}/bundle-buddy.json`,
path.join(targetDir, 'bundle-buddy.json'),
JSON.stringify(out),
);
logger.info({
message: `Wrote report to ${path.relative(
options.outputFS.cwd(),
path.join(targetDir, 'bundle-buddy.json'),
)}`,
});
}
},
}): Reporter);

0 comments on commit 6ce9e70

Please sign in to comment.