diff --git a/src/cli.ts b/src/cli.ts index 5f477e1..928b087 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -36,7 +36,11 @@ import { installMcpConfig, setupIdeIntegration, } from "./mcp/index.js"; -import { executeBatchUpgrade, scanOutdatedDependencies } from "./outdated/index.js"; +import { + executeBatchUpgrade, + formatOutdatedReport, + scanOutdatedDependencies, +} from "./outdated/index.js"; import { parsePackageSpec } from "./purl/parser.js"; import { RegistryVerifier } from "./registry/index.js"; import { evaluateSandboxGate, runEphemeralTry } from "./sandbox/index.js"; @@ -394,46 +398,7 @@ async function main(): Promise { `All ${report.totalScanned} dependencies across ecosystems are up to date! (${report.durationMs}ms)`, ); } else { - console.log( - `\nFound \x1b[1m${report.outdatedCount}\x1b[0m outdated package(s) across ${report.totalScanned} scanned (${report.durationMs}ms):\n`, - ); - - // Print formatted table - const headers = ["Package", "Current", "Latest", "Type", "Ecosystem", "Location"]; - const colWidths = [24, 12, 12, 10, 12, 16]; - - const pad = (str: string, width: number) => str.padEnd(width).slice(0, width); - const headerRow = headers.map((h, i) => pad(h, colWidths[i])).join(" "); - console.log(`\x1b[4m${headerRow}\x1b[0m`); - - for (const item of report.packages) { - const diffTag = item.diff.toUpperCase(); - let coloredDiff = diffTag; - if (item.diff === "major") coloredDiff = `\x1b[31m${diffTag}\x1b[0m`; - else if (item.diff === "minor") coloredDiff = `\x1b[33m${diffTag}\x1b[0m`; - else if (item.diff === "patch") coloredDiff = `\x1b[32m${diffTag}\x1b[0m`; - - const row = [ - pad(item.name, colWidths[0]), - pad(item.current, colWidths[1]), - pad(item.latest, colWidths[2]), - pad(coloredDiff, colWidths[3] + (coloredDiff.length - diffTag.length)), - pad(item.ecosystem, colWidths[4]), - pad(item.memberPath, colWidths[5]), - ].join(" "); - - console.log(row); - } - - console.log( - "\n\x1b[90mLegend: \x1b[31mMAJOR\x1b[90m (Breaking) | \x1b[33mMINOR\x1b[90m (Features) | \x1b[32mPATCH\x1b[90m (Bug Fixes)\x1b[0m", - ); - console.log( - `Summary: ${report.majorCount} major, ${report.minorCount} minor, ${report.patchCount} patch updates available.`, - ); - console.log( - `Run '\x1b[1mpoly upgrade\x1b[0m' to automatically upgrade manifests and synchronize poly.lock.\n`, - ); + console.log(formatOutdatedReport(report)); } } break; diff --git a/src/outdated/formatter.ts b/src/outdated/formatter.ts new file mode 100644 index 0000000..249e165 --- /dev/null +++ b/src/outdated/formatter.ts @@ -0,0 +1,119 @@ +import type { OutdatedScanReport, SemverDiff } from "./types.js"; + +export interface OutdatedFormatOptions { + color?: boolean; +} + +const ANSI_ESCAPE_PATTERN = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`, "g"); + +const HEADERS = ["Package", "Current", "Latest", "Type", "Ecosystem", "Location"] as const; + +const DIFF_COLORS: Record = { + major: "\x1b[31m", + minor: "\x1b[33m", + patch: "\x1b[32m", + prerelease: "\x1b[36m", + unknown: "\x1b[90m", +}; + +/** + * Strips ANSI SGR escape sequences from a string so visible width can be measured accurately. + */ +export function stripAnsi(text: string): string { + return text.replace(ANSI_ESCAPE_PATTERN, ""); +} + +/** + * Determines whether ANSI color output should be enabled, respecting NO_COLOR. + */ +export function isColorEnabled(colorOverride?: boolean): boolean { + if (colorOverride !== undefined) { + return colorOverride; + } + const noColor = process.env.NO_COLOR; + return noColor === undefined || noColor === ""; +} + +function style(text: string, ansiCode: string, useColor: boolean): string { + return useColor ? `${ansiCode}${text}\x1b[0m` : text; +} + +function padVisible(text: string, targetWidth: number): string { + const visibleLen = stripAnsi(text).length; + const padding = Math.max(0, targetWidth - visibleLen); + return `${text}${" ".repeat(padding)}`; +} + +function formatDiffTag(diff: SemverDiff, useColor: boolean): string { + const tag = diff.toUpperCase(); + if (!useColor) { + return tag; + } + const colorCode = DIFF_COLORS[diff]; + return colorCode ? `${colorCode}${tag}\x1b[0m` : tag; +} + +/** + * Formats an OutdatedScanReport into an aligned table, legend, and summary string. + */ +export function formatOutdatedReport( + report: OutdatedScanReport, + options: OutdatedFormatOptions = {}, +): string { + const useColor = isColorEnabled(options.color); + const lines: string[] = []; + + const countText = style(String(report.outdatedCount), "\x1b[1m", useColor); + lines.push( + `\nFound ${countText} outdated package(s) across ${report.totalScanned} scanned (${report.durationMs}ms):\n`, + ); + + const rawRows = report.packages.map((item) => [ + item.name, + item.current, + item.latest, + formatDiffTag(item.diff, useColor), + item.ecosystem, + item.memberPath, + ]); + + const colWidths = HEADERS.map((header, colIdx) => { + let maxWidth = header.length; + for (const row of rawRows) { + const cellWidth = stripAnsi(row[colIdx] ?? "").length; + if (cellWidth > maxWidth) { + maxWidth = cellWidth; + } + } + return maxWidth; + }); + + const formatRow = (cells: readonly string[]): string => + cells + .map((cell, idx) => (idx < cells.length - 1 ? padVisible(cell, colWidths[idx]) : cell)) + .join(" "); + + const headerRow = formatRow(HEADERS); + lines.push(style(headerRow, "\x1b[4m", useColor)); + + for (const row of rawRows) { + lines.push(formatRow(row)); + } + + if (useColor) { + lines.push( + "\n\x1b[90mLegend: \x1b[31mMAJOR\x1b[90m (Breaking) | \x1b[33mMINOR\x1b[90m (Features) | \x1b[32mPATCH\x1b[90m (Bug Fixes)\x1b[0m", + ); + } else { + lines.push("\nLegend: MAJOR (Breaking) | MINOR (Features) | PATCH (Bug Fixes)"); + } + + lines.push( + `Summary: ${report.majorCount} major, ${report.minorCount} minor, ${report.patchCount} patch updates available.`, + ); + + const upgradeCmd = style("poly upgrade", "\x1b[1m", useColor); + lines.push(`Run '${upgradeCmd}' to automatically upgrade manifests and synchronize poly.lock.\n`); + + return lines.join("\n"); +} diff --git a/src/outdated/index.ts b/src/outdated/index.ts index 2b2ea39..11b2d57 100644 --- a/src/outdated/index.ts +++ b/src/outdated/index.ts @@ -2,3 +2,4 @@ export * from "./types.js"; export * from "./semver.js"; export * from "./checker.js"; export * from "./upgrader.js"; +export * from "./formatter.js"; diff --git a/tests/outdated.test.ts b/tests/outdated.test.ts index 7209566..e5c7aee 100644 --- a/tests/outdated.test.ts +++ b/tests/outdated.test.ts @@ -3,7 +3,9 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import test from "node:test"; +import { formatOutdatedReport, isColorEnabled, stripAnsi } from "../src/outdated/formatter.js"; import { cleanVersion, compareSemver, parseSemver } from "../src/outdated/semver.js"; +import type { OutdatedScanReport } from "../src/outdated/types.js"; import { executeBatchUpgrade, patchManifestVersion } from "../src/outdated/upgrader.js"; test("Outdated Intelligence - Semver Parsing & Comparison", async (t) => { @@ -121,3 +123,115 @@ test("Outdated Intelligence - Manifest Patching", async (t) => { // Cleanup fs.rmSync(tmpDir, { recursive: true, force: true }); }); + +test("Outdated Intelligence - Table Formatting & NO_COLOR", async (t) => { + const sampleReport: OutdatedScanReport = { + totalScanned: 12, + outdatedCount: 3, + majorCount: 1, + minorCount: 1, + patchCount: 1, + durationMs: 42, + packages: [ + { + name: "@organization/very-long-scoped-package-name", + ecosystem: "npm", + current: "1.2.3", + latest: "2.0.0-alpha.12", + diff: "major", + memberPath: "apps/web-frontend", + }, + { + name: "github.com/gin-gonic/gin", + ecosystem: "go", + current: "1.9.0", + latest: "1.10.0", + diff: "minor", + memberPath: "services/backend-api/worker", + }, + { + name: "zod", + ecosystem: "npm", + current: "3.22.0", + latest: "3.22.4", + diff: "patch", + memberPath: ".", + }, + ], + }; + + await t.test("aligns columns dynamically without truncating long values", () => { + const output = formatOutdatedReport(sampleReport, { color: true }); + const plainLines = stripAnsi(output).split("\n"); + + const headerLine = plainLines.find((line) => line.startsWith("Package")); + assert.ok(headerLine, "Expected header line to be present"); + + const currentCol = headerLine.indexOf("Current"); + const latestCol = headerLine.indexOf("Latest"); + const typeCol = headerLine.indexOf("Type"); + const ecoCol = headerLine.indexOf("Ecosystem"); + const locCol = headerLine.indexOf("Location"); + + assert.ok(currentCol > 0); + assert.ok(latestCol > currentCol); + assert.ok(typeCol > latestCol); + assert.ok(ecoCol > typeCol); + assert.ok(locCol > ecoCol); + + const row1 = plainLines.find((line) => + line.startsWith("@organization/very-long-scoped-package-name"), + ); + const row2 = plainLines.find((line) => line.startsWith("github.com/gin-gonic/gin")); + const row3 = plainLines.find((line) => line.startsWith("zod ")); + + assert.ok(row1, "Long scoped package name should not be truncated"); + assert.ok(row2, "Go module path should not be truncated"); + assert.ok(row3, "Short package row should be present"); + + assert.equal(row1.indexOf("1.2.3", currentCol), currentCol); + assert.equal(row1.indexOf("2.0.0-alpha.12", latestCol), latestCol); + assert.equal(row1.indexOf("MAJOR", typeCol), typeCol); + assert.equal(row1.indexOf("npm", ecoCol), ecoCol); + assert.equal(row1.indexOf("apps/web-frontend", locCol), locCol); + + assert.equal(row2.indexOf("1.9.0", currentCol), currentCol); + assert.equal(row2.indexOf("1.10.0", latestCol), latestCol); + assert.equal(row2.indexOf("MINOR", typeCol), typeCol); + assert.equal(row2.indexOf("go", ecoCol), ecoCol); + assert.equal(row2.indexOf("services/backend-api/worker", locCol), locCol); + + assert.equal(row3.indexOf("3.22.0", currentCol), currentCol); + assert.equal(row3.indexOf("3.22.4", latestCol), latestCol); + assert.equal(row3.indexOf("PATCH", typeCol), typeCol); + assert.equal(row3.indexOf("npm", ecoCol), ecoCol); + assert.equal(row3.indexOf(".", locCol), locCol); + }); + + await t.test("includes ANSI colors when color is enabled", () => { + const output = formatOutdatedReport(sampleReport, { color: true }); + assert.ok(output.includes("\x1b[31mMAJOR\x1b[0m")); + assert.ok(output.includes("\x1b[33mMINOR\x1b[0m")); + assert.ok(output.includes("\x1b[32mPATCH\x1b[0m")); + }); + + await t.test("strips all ANSI escape sequences when NO_COLOR=1 is set", () => { + const prevNoColor = process.env.NO_COLOR; + process.env.NO_COLOR = "1"; + try { + assert.equal(isColorEnabled(), false); + const output = formatOutdatedReport(sampleReport); + const ansiPattern = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`); + assert.equal(ansiPattern.test(output), false, "Expected zero ANSI escape sequences"); + assert.ok(output.includes("@organization/very-long-scoped-package-name")); + assert.ok(output.includes("Legend: MAJOR (Breaking) | MINOR (Features) | PATCH (Bug Fixes)")); + assert.ok(output.includes("Summary: 1 major, 1 minor, 1 patch updates available.")); + } finally { + if (prevNoColor === undefined) { + Reflect.deleteProperty(process.env, "NO_COLOR"); + } else { + process.env.NO_COLOR = prevNoColor; + } + } + }); +});