Skip to content

Refactor baseline read/write #3845

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

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
2,493 changes: 1,198 additions & 1,295 deletions package-lock.json

Large diffs are not rendered by default.

4 changes: 3 additions & 1 deletion packages/cli-utils/__mocks__/fs.ts
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
export { fs } from 'memfs';
const { vol } = require('memfs');

module.exports = vol;
4 changes: 2 additions & 2 deletions packages/cli-utils/__mocks__/fs/promises.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import { fs } from 'memfs';
const { vol } = require('memfs');

export default fs.promises;
module.exports = vol.promises;
2 changes: 1 addition & 1 deletion packages/cli-utils/src/__tests__/reports.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ const SOURCE_BASELINE = {
],
};

describe('generateAssets', () => {
describe('generateReports', () => {
test('should generate reports with default options', async () => {
const reports = await generateReports(SOURCE_CURRENT, {});

Expand Down
10 changes: 0 additions & 10 deletions packages/cli-utils/src/baseline.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import path from 'path';
import fs from 'fs/promises';
import findCacheDir from 'find-cache-dir';

export const BASELINE_STATS_DIR =
Expand Down Expand Up @@ -36,12 +35,3 @@ export const getBaselineRelativePath = (
const absoluteFilepath = getBaselinePath(outputPath, outputDir, filepath);
return path.relative(path.join(outputPath, outputDir), absoluteFilepath);
};

export async function readBaseline(baselineFilepath: string): Promise<object> {
const file = await fs.readFile(baselineFilepath, 'utf-8');
return JSON.parse(file);
}

export async function writeBaseline(data: JSON, baselineFilepath: string): Promise<void> {
return fs.writeFile(baselineFilepath, JSON.stringify(data));
}
23 changes: 19 additions & 4 deletions packages/cli-utils/src/fs.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,28 @@
import { createReadStream } from 'fs';
import { writeFile, stat } from 'fs/promises';
import { parser } from 'stream-json';
import { chain } from 'stream-chain';
import Asm from 'stream-json/Assembler';

export const readJSONStream = <T = unknown>(filepath: string): Promise<T> => {
const pipeline = chain([createReadStream(filepath), parser()]);
export const readJSONStream = async <T = unknown>(filepath: string): Promise<T> => {
// Check if the file exists and throw error before creating a stream
await stat(filepath);

const readStream = createReadStream(filepath);
const pipeline = chain([readStream, parser()]);
const asm = Asm.connectTo(pipeline);

return new Promise((fulfill) => {
asm.on('done', (data) => fulfill(data.current));
return new Promise((resolve, reject) => {
asm.on('done', (data) => {
if (data.current) {
resolve(data.current);
} else {
reject(new Error('Invalid JSON file'));
}
});
});
};

export async function writeJSON(filepath: string, data: Record<string, unknown>): Promise<void> {
return writeFile(filepath, JSON.stringify(data));
}
7 changes: 4 additions & 3 deletions packages/cli-utils/src/reports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import filter from '@bundle-stats/plugin-webpack-filter';

import * as TEXT from './text';
import { createArtifacts } from './create-artifacts';
import { getBaselinePath, getBaselineRelativePath, readBaseline } from './baseline';
import { readJSONStream } from './fs';
import { getBaselinePath, getBaselineRelativePath } from './baseline';

export function getReportInfo(report: any): any {
return report?.insights?.webpack?.assetsSizeTotal?.data;
Expand Down Expand Up @@ -110,8 +111,8 @@ export const generateReports = async (

if (compare) {
try {
const baselineStatsData = await readBaseline(baselineAbsolutePath);
baselineStats = filter(baselineStatsData);
const baselineStatsData = await readJSONStream(baselineAbsolutePath);
baselineStats = filter(baselineStatsData as any);

if (!options.silent) {
logger.info(`${TEXT.BASELINE_READING} ${baselinePath}`);
Expand Down
2 changes: 0 additions & 2 deletions packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,15 +57,13 @@
"@bundle-stats/utils": "^4.7.1",
"boxen": "^5.0.0",
"core-js": "^3.21.0",
"fs-extra": "^11.0.0",
"listr2": "^5.0.1",
"lodash": "^4.17.0",
"update-notifier": "^5.0.0",
"yargs": "^17.4.0"
},
"devDependencies": {
"@playwright/test": "1.38.1",
"@types/fs-extra": "^11.0.0",
"@types/listr": "^0.14.4",
"@types/yargs": "^17.0.20",
"http-server": "14.1.1",
Expand Down
19 changes: 5 additions & 14 deletions packages/cli/src/run.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
/* eslint-disable no-console */
import path from 'path';
import { outputFile } from 'fs-extra';
import { Listr } from 'listr2';
import { get } from 'lodash';
import boxen from 'boxen';
Expand All @@ -25,9 +24,8 @@ import {
getBaselinePath,
getBaselineRelativePath,
getReportInfo,
readBaseline,
readJSONStream,
writeBaseline,
writeJSON,
} from '@bundle-stats/cli-utils';

import LOCALES from './locales.json';
Expand Down Expand Up @@ -64,13 +62,6 @@ export default async function run(options: RunOptions): Promise<void> {
// Generate relative path relative to process.cwd()
const baselinePath = getBaselineRelativePath(process.cwd(), '', baselineAbsolutePath);

console.log({
dirname: __dirname,
cwd: process.cwd(),
baselineAbsolutePath,
baselinePath,
});

const tasks = new Listr([
{
title: 'Read Webpack stats files',
Expand Down Expand Up @@ -112,7 +103,7 @@ export default async function run(options: RunOptions): Promise<void> {
let baselineStats = {};

try {
baselineStats = await readBaseline(baselineAbsolutePath);
baselineStats = await readJSONStream(baselineAbsolutePath);
ctx.baselineStats = baselineStats;
} catch (err) {
return TEXT.BASELINE_MISSING;
Expand All @@ -125,9 +116,9 @@ export default async function run(options: RunOptions): Promise<void> {
title: 'Write baseline data',
task: (ctx, task) => {
const stats = get(ctx, 'sources[0]webpack');
const filteredWebpackStats = webpackFilter(stats) as JSON;
const filteredWebpackStats = webpackFilter(stats) as Record<string, unknown>;

return writeBaseline(filteredWebpackStats, baselineAbsolutePath).then(() => {
return writeJSON(baselineAbsolutePath, filteredWebpackStats).then(() => {
// eslint-disable-next-line no-param-reassign
task.title = `${task.title} (${baselinePath})`;
});
Expand Down Expand Up @@ -155,7 +146,7 @@ export default async function run(options: RunOptions): Promise<void> {
title: filename,
task: async () => {
const filepath = path.join(outDir, filename);
await outputFile(filepath, output);
await writeJSON(filepath, output);

ctx.output = [...(ctx.output ? ctx.output : []), filepath];
},
Expand Down