|
| 1 | +import { readJson } from 'fs-extra'; |
| 2 | +import { Metrics } from './types'; |
| 3 | + |
| 4 | +const formatFileSize = (size: number, target = 'KB') => { |
| 5 | + if (target === 'KB') { |
| 6 | + size = size / 1024; |
| 7 | + } else if (target === 'MB') { |
| 8 | + size = size / 1024 / 1024; |
| 9 | + } |
| 10 | + return Number(size.toFixed(2)); |
| 11 | +}; |
| 12 | + |
| 13 | +const formatSecond = (ms: number) => Number((ms / 1000).toFixed(2)); |
| 14 | + |
| 15 | +function formatValue(value: number, property: string) { |
| 16 | + if (property.endsWith('Time')) { |
| 17 | + return String(formatSecond(value)) + 's'; |
| 18 | + } else if (property === 'installSize') { |
| 19 | + return String(formatFileSize(value, 'MB')) + 'MB'; |
| 20 | + } else if (property.endsWith('Size')) { |
| 21 | + return String(formatFileSize(value)) + 'KB'; |
| 22 | + } else { |
| 23 | + return String(value); |
| 24 | + } |
| 25 | +} |
| 26 | + |
| 27 | +function generateTable( |
| 28 | + base: Record<string, number>, |
| 29 | + current: Record<string, number>, |
| 30 | +) { |
| 31 | + const properties = Object.keys(base); |
| 32 | + |
| 33 | + const maxPropertyLength = Math.max(...properties.map(p => p.length)); |
| 34 | + |
| 35 | + const table = [ |
| 36 | + `| Metric${' '.repeat(maxPropertyLength - 6)} | Base${' '.repeat( |
| 37 | + 6, |
| 38 | + )} | Current${' '.repeat(3)} | %${' '.repeat(9)} |`, |
| 39 | + `|${'-'.repeat(maxPropertyLength + 2)}|${'-'.repeat(12)}|${'-'.repeat( |
| 40 | + 12, |
| 41 | + )}|${'-'.repeat(12)}|`, |
| 42 | + ]; |
| 43 | + |
| 44 | + properties.forEach(property => { |
| 45 | + if (property === 'time') return; |
| 46 | + const percent = |
| 47 | + ((current[property] - base[property]) * 100) / base[property]; |
| 48 | + const formattedPercent = |
| 49 | + percent > 0 ? `+${percent.toFixed(2)}%` : `${percent.toFixed(2)}%`; |
| 50 | + |
| 51 | + const row = `| ${property.padEnd(maxPropertyLength)} | ${formatValue( |
| 52 | + base[property], |
| 53 | + property, |
| 54 | + ).padEnd(10)} | ${formatValue(current[property], property).padEnd( |
| 55 | + 10, |
| 56 | + )} | ${formattedPercent.padEnd(10)} |`; |
| 57 | + table.push(row); |
| 58 | + }); |
| 59 | + |
| 60 | + return table.join('\n'); |
| 61 | +} |
| 62 | + |
| 63 | +export async function compare(jsonPath: string) { |
| 64 | + const allMetrics: Metrics[] = await readJson(jsonPath); |
| 65 | + const keys = Object.keys(allMetrics); |
| 66 | + const currentKey = keys[keys.length - 1]; |
| 67 | + const baseKey = keys[keys.length - 2]; |
| 68 | + const current = allMetrics[currentKey as any]; |
| 69 | + const base = allMetrics[baseKey as any]; |
| 70 | + |
| 71 | + const formatTable = generateTable(base, current); |
| 72 | + console.log(formatTable); |
| 73 | +} |
0 commit comments