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(utils): add file size logging #65

Merged
merged 22 commits into from
Oct 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
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
526 changes: 525 additions & 1 deletion package-lock.json

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@
"vitest": "~0.32.0"
},
"optionalDependencies": {
"@esbuild/darwin-arm64": "^0.19.4",
"@nx/nx-darwin-arm64": "^16.9.1",
"@nx/nx-darwin-x64": "^16.9.1",
BioPhoton marked this conversation as resolved.
Show resolved Hide resolved
"@nx/nx-linux-x64-gnu": "16.7.4"
},
"config": {
Expand Down
5 changes: 4 additions & 1 deletion packages/cli/src/lib/collect/command-object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
CollectOptions,
CollectOutputError,
persistReport,
logPersistedResults,
} from '@quality-metrics/utils';
import { CommandModule } from 'yargs';
import * as packageJson from '../../../package.json';
Expand All @@ -19,7 +20,9 @@ export function yargsCollectCommandObject() {
version: packageJson.version,
};

await persistReport(report, config);
const persistResults = await persistReport(report, config);

logPersistedResults(persistResults);

// validate report
report.plugins.forEach(plugin => {
Expand Down
1 change: 1 addition & 0 deletions packages/utils/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,5 @@ export {
persistReport,
PersistDirError,
PersistError,
logPersistedResults,
} from './lib/collect/implementation/persist';
62 changes: 56 additions & 6 deletions packages/utils/src/lib/collect/implementation/persist.spec.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { logPersistedResults, persistReport } from './persist';
import { readFileSync, unlinkSync } from 'fs';
import { Report } from '@quality-metrics/models';
import {
MEMFS_VOLUME,
dummyConfig,
dummyReport,
MEMFS_VOLUME,
mockPersistConfig,
} from '@quality-metrics/models/testing';
import { readFileSync, unlinkSync } from 'fs';
import { vol } from 'memfs';
import { join } from 'path';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { mockConsole, unmockConsole } from './mock/helper.mock';
import { persistReport } from './persist';

vi.mock('fs', async () => {
const memfs: typeof import('memfs') = await vi.importActual('memfs');
Expand All @@ -35,10 +35,9 @@ const readReport = (format: 'json' | 'md') => {
};

const config = dummyConfig(MEMFS_VOLUME);
let logs: string[] = [];

describe('persistReport', () => {
let logs: string[] = [];

beforeEach(async () => {
vol.reset();
vol.fromJSON(
Expand Down Expand Up @@ -143,3 +142,54 @@ describe('persistReport', () => {
// TODO: should throw PersistDirError
// TODO: should throw PersistError
});

describe('logPersistedResults', () => {
beforeEach(async () => {
vol.reset();
vol.fromJSON(
{
[reportPath('json')]: '',
[reportPath('md')]: '',
},
MEMFS_VOLUME,
);
unlinkSync(reportPath('json'));
unlinkSync(reportPath('md'));

logs = [];
mockConsole(msg => logs.push(msg));
});

afterEach(() => {
logs = [];
unmockConsole();
});

it('should log report sizes correctly`', async () => {
logPersistedResults([{ status: 'fulfilled', value: ['out.json', 10000] }]);
expect(logs.length).toBe(2);
expect(logs).toContain('Generated reports successfully: ');
expect(logs).toContain('- out.json (9.77 kB)');
});

it('should log fails correctly`', async () => {
logPersistedResults([{ status: 'rejected', reason: 'fail' }]);
expect(logs.length).toBe(2);

expect(logs).toContain('Generated reports failed: ');
expect(logs).toContain('- fail');
});

it('should log report sizes and fails correctly`', async () => {
logPersistedResults([
{ status: 'fulfilled', value: ['out.json', 10000] },
{ status: 'rejected', reason: 'fail' },
]);
expect(logs.length).toBe(4);
expect(logs).toContain('Generated reports successfully: ');
expect(logs).toContain('- out.json (9.77 kB)');

expect(logs).toContain('Generated reports failed: ');
expect(logs).toContain('- fail');
});
});
42 changes: 39 additions & 3 deletions packages/utils/src/lib/collect/implementation/persist.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { existsSync, mkdirSync } from 'fs';
import { writeFile } from 'fs/promises';
import { writeFile, stat } from 'fs/promises';
import { join } from 'path';
import chalk from 'chalk';
import { CoreConfig, Report } from '@quality-metrics/models';
import { formatBytes } from './utils';
import { reportToStdout } from './report-to-stdout';
import { reportToMd } from './report-to-md';

Expand All @@ -17,7 +19,12 @@ export class PersistError extends Error {
}
}

export async function persistReport(report: Report, config: CoreConfig) {
export type PersistResult = PromiseSettledResult<readonly [string, number]>[];

export async function persistReport(
report: Report,
config: CoreConfig,
): Promise<PersistResult> {
const { persist } = config;
const outputPath = persist.outputPath;
let { format } = persist;
Expand Down Expand Up @@ -54,7 +61,8 @@ export async function persistReport(report: Report, config: CoreConfig) {
return (
writeFile(reportPath, content)
// return reportPath instead of void
.then(() => reportPath)
.then(() => stat(reportPath))
.then(stats => [reportPath, stats.size] as const)
.catch(e => {
console.warn(e);
throw new PersistError(reportPath);
Expand All @@ -63,3 +71,31 @@ export async function persistReport(report: Report, config: CoreConfig) {
}),
);
}

export function logPersistedResults(persistResult: PersistResult) {
const succeededPersistedResults = persistResult.filter(
(result): result is PromiseFulfilledResult<[string, number]> =>
result.status === 'fulfilled',
);

if (succeededPersistedResults.length) {
console.log(`Generated reports successfully: `);
succeededPersistedResults.forEach(res => {
const [fileName, size] = res.value;
console.log(
`- ${chalk.bold(fileName)} (${chalk.gray(formatBytes(size))})`,
);
});
}

const failedPersistedResults = persistResult.filter(
(result): result is PromiseRejectedResult => result.status === 'rejected',
);

if (failedPersistedResults.length) {
console.log(`Generated reports failed: `);
failedPersistedResults.forEach(result => {
console.log(`- ${chalk.bold(result.reason)}`);
});
}
}
48 changes: 47 additions & 1 deletion packages/utils/src/lib/collect/implementation/utils.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect } from 'vitest';
import { calcDuration, countWeightedRefs, sumRefs } from './utils';
import { calcDuration, formatBytes, countWeightedRefs, sumRefs } from './utils';
import { CategoryConfig } from '@quality-metrics/models';

describe('calcDuration', () => {
Expand Down Expand Up @@ -60,3 +60,49 @@ describe('sumRefs', () => {
expect(sumRefs(refs)).toBe(11);
});
});

describe('formatBytes', () => {
it('should log file sizes in Bytes`', async () => {
expect(formatBytes(1000)).toBe('1000 B');
});

it('should log file sizes in KB`', async () => {
expect(formatBytes(10000)).toBe('9.77 kB');
});

it('should log file sizes in MB`', async () => {
expect(formatBytes(10000000)).toBe('9.54 MB');
});

it('should log file sizes in bytes`', async () => {
expect(formatBytes(10000000000)).toBe('9.31 GB');
});

it('should log file sizes in TB`', async () => {
expect(formatBytes(10000000000000)).toBe('9.09 TB');
});

it('should log file sizes in PB`', async () => {
expect(formatBytes(10000000000000000)).toBe('8.88 PB');
});

it('should log file sizes in EB`', async () => {
expect(formatBytes(10000000000000000000)).toBe('8.67 EB');
});

it('should log file sizes in ZB`', async () => {
expect(formatBytes(10000000000000000000000)).toBe('8.47 ZB');
});

it('should log file sizes in YB`', async () => {
expect(formatBytes(10000000000000000000000000)).toBe('8.27 YB');
});

it('should log file sizes correctly with correct decimal`', async () => {
expect(formatBytes(10000, 1)).toBe('9.8 kB');
});

it('should log file sizes of 0 if no size is given`', async () => {
expect(formatBytes(0)).toBe('0 B');
});
BioPhoton marked this conversation as resolved.
Show resolved Hide resolved
});
12 changes: 12 additions & 0 deletions packages/utils/src/lib/collect/implementation/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,18 @@ export function countWeightedRefs(refs: CategoryConfig['refs']) {
.reduce((sum, { weight }) => sum + weight, 0);
}

export function formatBytes(bytes: number, decimals = 2) {
if (!+bytes) return '0 B';

const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

const i = Math.floor(Math.log(bytes) / Math.log(k));

return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`;
}

export function calcDuration(start: number, stop?: number): number {
stop = stop !== undefined ? stop : performance.now();
return Math.floor(stop - start);
Expand Down