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

feat(monosize): add --fixture argument to measure command to target specific fixture files #75

Merged
merged 4 commits into from
Jul 24, 2024
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
7 changes: 7 additions & 0 deletions change/monosize-190af040-06c8-4534-88ab-f97941ef976d.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"type": "patch",
"comment": "feat: implement --fixtures argument for measure CLI command",
"packageName": "monosize",
"email": "ben.keen@gmail.com",
"dependentChangeType": "patch"
}
9 changes: 8 additions & 1 deletion packages/monosize/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
- [Commands](#commands)
- [`measure`](#measure)
- [Options](#options)
- [Examples](#examples)
- [`compare-reports`](#compare-reports)
- [Options](#options-1)
- [`upload-report`](#upload-report)
Expand Down Expand Up @@ -152,7 +153,7 @@ To store reference results and run comparisons you need to use a storage adapter
### `measure`

```sh
monosize measure [--debug] [--artifacts-location] [--quiet]
monosize measure [--debug] [--artifacts-location] [--fixtures] [--quiet]
```

Builds fixtures and produces artifacts. For each fixture:
Expand All @@ -166,6 +167,12 @@ Produces a report file (`dist/bundle-size/monosize.json`) that is used by other
#### Options

- `artifacts-location` - defines relative path from the package root where the artifact files will be stored (`monosize.json` & bundler output). If specified, `--report-files-glob` in `monosize collect-reports` & `monosize upload-reports` should be set accordingly.
- `fixtures` - optional argument to pass a fixture filename or globbing pattern. If not specified, all fixture files matching a `*.fixture.js` pattern will be measured.

#### Examples

`monosize measure --fixtures ba*` - matches any fixtures with filenames starting with `ba`
`monosize measure --fixtures Fixture.fixture.js` - matches a fixture with the exact filename

### `compare-reports`

Expand Down
15 changes: 13 additions & 2 deletions packages/monosize/src/commands/measure.mts
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,11 @@ import type { BuildResult } from '../types.mjs';
export type MeasureOptions = CliOptions & {
debug: boolean;
'artifacts-location': string;
fixtures: string;
};

async function measure(options: MeasureOptions) {
const { debug = false, quiet, 'artifacts-location': artifactsLocation } = options;
const { debug = false, quiet, 'artifacts-location': artifactsLocation, fixtures: fixturesGlob } = options;

const startTime = process.hrtime();
const artifactsDir = path.resolve(process.cwd(), artifactsLocation);
Expand All @@ -39,11 +40,16 @@ async function measure(options: MeasureOptions) {
console.log(`${pc.blue('[i]')} artifacts dir is cleared`);
}

const fixtures = glob.sync('bundle-size/*.fixture.js', {
const fixtures = glob.sync(`bundle-size/${fixturesGlob}`, {
absolute: true,
cwd: process.cwd(),
});

if (!fixtures.length && fixturesGlob) {
console.error(`${pc.red('[e]')} No matching fixtures found for globbing pattern '${fixturesGlob}'`);
process.exit(1);
}

if (!quiet) {
console.log(`${pc.blue('[i]')} Measuring bundle size for ${fixtures.length} fixture(s)...`);
console.log(fixtures.map(fixture => ` - ${fixture}`).join('\n'));
Expand Down Expand Up @@ -105,6 +111,11 @@ const api: CommandModule<Record<string, unknown>, MeasureOptions> = {
'Relative path to the package root where the artifact files will be stored (monosize.json & bundler output). If specified, "--report-files-glob" in "monosize collect-reports" & "monosize upload-reports" should be set accordingly.',
default: 'dist/bundle-size',
},
fixtures: {
type: 'string',
description: 'Filename glob pattern to target whatever fixture files you want to measure.',
default: '*.fixture.js'
}
},
};

Expand Down
81 changes: 69 additions & 12 deletions packages/monosize/src/commands/measure.test.mts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import fs from 'node:fs/promises';
import path from 'node:path';
import tmp from 'tmp';
import { beforeEach, describe, expect, it, vitest } from 'vitest';

import api, { type MeasureOptions } from './measure.mjs';

const buildFixture = vitest.hoisted(() =>
Expand All @@ -23,6 +22,12 @@ vitest.mock('../utils/readConfig', () => ({
}),
}));

vitest.mock('picocolors', () => ({
default: ({
red: () => ''
})
}));

async function setup(fixtures: { [key: string]: string }) {
const packageDir = tmp.dirSync({ unsafeCleanup: true });

Expand All @@ -40,24 +45,28 @@ async function setup(fixtures: { [key: string]: string }) {
packageDir: packageDir.name,
};
}
const getMockedFixtures = (...fixtureNames: string[]) => (
fixtureNames.reduce((acc, item) => ({
...acc,
[`${item}.fixture.js`]: `
console.log("${item}");
export default { name: '${item}' };
`
}), {})
);

// eslint-disable-next-line @typescript-eslint/no-empty-function
const noop = () => {};

describe('measure', () => {
beforeEach(() => {
vitest.clearAllMocks();
});

it('builds fixtures and created a report', async () => {
const { packageDir } = await setup({
'foo.fixture.js': `
console.log("foo");
export default { name: 'foo' };
`,
'bar.fixture.js': `
console.log("bar");
export default { name: 'bar' };
`,
});
const options: MeasureOptions = { quiet: true, debug: false, 'artifacts-location': 'output' };
const { packageDir } = await setup(getMockedFixtures('foo', 'bar'));
const options: MeasureOptions = { quiet: true, debug: false, 'artifacts-location': 'output', fixtures: '*.fixture.js' };

// eslint-disable-next-line @typescript-eslint/no-explicit-any
await api.handler(options as any);

Expand Down Expand Up @@ -89,5 +98,53 @@ describe('measure', () => {
gzippedSize: expect.any(Number),
},
]);
});

it('builds single targeted fixture when full filename passed', async () => {
const { packageDir } = await setup(getMockedFixtures('foo', 'bar', 'baz'));
const options: MeasureOptions = { quiet: true, debug: false, 'artifacts-location': 'output', fixtures: 'foo.fixture.js' };
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await api.handler(options as any);

// Fixtures

expect(await fs.readdir(path.resolve(packageDir, 'output'))).toEqual([
'foo.fixture.js',
'foo.output.js',
'monosize.json',
]);
});

it('builds only targeted fixtures with pattern passed', async () => {
const { packageDir } = await setup(getMockedFixtures('foo', 'bar', 'baz'));
const options: MeasureOptions = { quiet: true, debug: false, 'artifacts-location': 'output', fixtures: 'ba*' };

// eslint-disable-next-line @typescript-eslint/no-explicit-any
await api.handler(options as any);

// Fixtures

expect(await fs.readdir(path.resolve(packageDir, 'output'))).toEqual([
'bar.fixture.js',
'bar.output.js',
'baz.fixture.js',
'baz.output.js',
'monosize.json',
]);
});

it('returns exit code of 1 and displays message when fixtures argument fails to match any fixture filename', async () => {
const errorLog = vitest.spyOn(console, 'error').mockImplementation(noop);
const mockExit = vitest.spyOn(process, 'exit').mockImplementation(noop as any);

await setup({});
const options: MeasureOptions = { quiet: true, debug: false, 'artifacts-location': 'output', fixtures: 'invalid-filename.js' };

// eslint-disable-next-line @typescript-eslint/no-explicit-any
await api.handler(options as any);

expect(errorLog.mock.calls[0][0]).toMatchInlineSnapshot(`" No matching fixtures found for globbing pattern 'invalid-filename.js'"`);
expect(mockExit).toHaveBeenCalledWith(1);
});

});
Loading