The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
fix(cli): improve command output readability (#27423)
Weiko0d66dd1b29bc
diff --git a/packages/twenty-cli/src/app/deployment/format-apply-summary.ts b/packages/twenty-cli/src/app/deployment/format-apply-summary.tsindex c066651d674..3e14e8c885e 100644--- a/packages/twenty-cli/src/app/deployment/format-apply-summary.ts+++ b/packages/twenty-cli/src/app/deployment/format-apply-summary.ts@@ -5,7 +5,21 @@ import { formatAppDuration } from '@/app/format-app-duration';import { type AppPlanSummary } from '@/app/deployment/types/app-plan.type';import { type AppUploadProgress } from '@/app/deployment/types/app-upload-progress.type';import { formatDataValue } from '@/data/format-data-value';-import { dimText, formatSuccessLine } from '@/output/style';+import { colorText, dimText, formatSuccessLine } from '@/output/style';++const formatChangeCount = ({+ count,+ label,+ color,+}: {+ count: number;+ label: string;+ color: 'green' | 'yellow' | 'red';+}) => {+ const text = `${count} ${label}`;++ return count === 0 ? dimText(text) : colorText(color, text);+};export const formatApplySummary = ({applicationName,@@ -25,17 +39,31 @@ export const formatApplySummary = ({durationMilliseconds: number;}) => {const changes = isDefined(summary)- ? `${summary.create} added · ${summary.update} changed · ${summary.delete} deleted`- : 'changes not reported';+ ? [+ formatChangeCount({+ count: summary.create,+ label: 'added',+ color: 'green',+ }),+ formatChangeCount({+ count: summary.update,+ label: 'changed',+ color: 'yellow',+ }),+ formatChangeCount({+ count: summary.delete,+ label: 'deleted',+ color: 'red',+ }),+ ].join(dimText(' · '))+ : dimText('changes not reported');const fileLabel = upload.fileCount === 1 ? 'file' : 'files';return [formatSuccessLine(`Applied ${formatDataValue(applicationName)} to ${apiUrl} ${dimText(`in ${formatAppDuration(durationMilliseconds)}`)}`,),- dimText(- ` ${changes} · ${upload.fileCount} ${fileLabel} uploaded (${formatBytes(upload.byteCount)})`,- ),+ ` ${changes}${dimText(` · ${upload.fileCount} ${fileLabel} uploaded (${formatBytes(upload.byteCount)})`)}`,isRegistrationCreated? dimText(' Registered the app and installed it in this workspace.'): '',diff --git a/packages/twenty-cli/src/app/exec/format-function-execution.ts b/packages/twenty-cli/src/app/exec/format-function-execution.tsindex de760cb81bb..cf2d36dd8c1 100644--- a/packages/twenty-cli/src/app/exec/format-function-execution.ts+++ b/packages/twenty-cli/src/app/exec/format-function-execution.ts@@ -1,5 +1,7 @@import { type AppFunctionExecution } from '@/app/exec/execute-app-function';import { formatDataValue } from '@/data/format-data-value';+import { formatDetails } from '@/output/format-details';+import { boldText, colorText, dimText } from '@/output/style';const formatExecutionValue = (value: unknown) =>JSON.stringify(value, null, 2).replace(@@ -8,18 +10,37 @@ const formatExecutionValue = (value: unknown) =>`\\u${character.charCodeAt(0).toString(16).padStart(4, '0')}`,);-export const formatFunctionExecution = (result: AppFunctionExecution) =>+export const formatFunctionExecution = (+ result: AppFunctionExecution,+ stream: NodeJS.WriteStream = process.stdout,+) =>[- `Function: ${formatDataValue(result.functionName)}`,- `Status: ${formatDataValue(result.status)}`,- `Duration: ${result.durationMilliseconds}ms`,+ formatDetails(+ [+ ['Function', formatDataValue(result.functionName)],+ [+ 'Status',+ colorText(+ result.status === 'SUCCESS' ? 'green' : 'red',+ formatDataValue(result.status),+ stream,+ ),+ ],+ ['Duration', dimText(`${result.durationMilliseconds}ms`, stream)],+ ],+ stream,+ ),...(result.data !== null- ? ['Data:', formatExecutionValue(result.data)]+ ? ['', boldText('Data:', stream), formatExecutionValue(result.data)]: []),...(result.error !== null- ? ['Error:', formatExecutionValue(result.error)]+ ? ['', boldText('Error:', stream), formatExecutionValue(result.error)]: []),...(result.logs.length > 0- ? ['Logs:', ...result.logs.split('\n').map(formatDataValue)]+ ? [+ '',+ boldText('Logs:', stream),+ ...result.logs.split('\n').map(formatDataValue),+ ]: []),].join('\n');diff --git a/packages/twenty-cli/src/app/format-app-init-summary.ts b/packages/twenty-cli/src/app/format-app-init-summary.tsindex 1d8f8c27102..3025e83cd3e 100644--- a/packages/twenty-cli/src/app/format-app-init-summary.ts+++ b/packages/twenty-cli/src/app/format-app-init-summary.ts@@ -1,6 +1,11 @@import { type AppInitNextStep } from '@/app/types/app-init-next-step.type';import { formatList } from '@/output/format-list';-import { dimText, formatSuccessLine } from '@/output/style';+import {+ boldText,+ commandText,+ dimText,+ formatSuccessLine,+} from '@/output/style';export const formatAppInitSummary = ({appName,@@ -25,10 +30,10 @@ export const formatAppInitSummary = ({` ${formatList(packageNames)} pinned to ${packageVersion}. Nothing was installed.`,),'',- 'Next steps',+ boldText('Next steps'),...nextSteps.map(({ command, description }) =>- ` ${command.padEnd(commandWidth)} ${dimText(`# ${description}`)}`,+ ` ${commandText(command.padEnd(commandWidth))} ${dimText(`# ${description}`)}`,),].join('\n');};diff --git a/packages/twenty-cli/src/commands/app/__tests__/app-exec.spec.ts b/packages/twenty-cli/src/commands/app/__tests__/app-exec.spec.tsindex 7c5cfbc9292..fa2c4401497 100644--- a/packages/twenty-cli/src/commands/app/__tests__/app-exec.spec.ts+++ b/packages/twenty-cli/src/commands/app/__tests__/app-exec.spec.ts@@ -1,7 +1,9 @@import { mkdtemp, rm, writeFile } from 'node:fs/promises';import { tmpdir } from 'node:os';import { join } from 'node:path';+import { WriteStream } from 'node:tty';+import { isDefined } from 'twenty-shared/utils';import {afterAll,afterEach,@@ -129,7 +131,10 @@ beforeEach(() => {});setManifest();});-afterEach(() => vi.clearAllMocks());+afterEach(() => {+ vi.clearAllMocks();+ vi.unstubAllEnvs();+});afterAll(async () => server.close());describe('twenty app exec', () => {@@ -399,11 +404,121 @@ describe('twenty app exec', () => {};const result = await run('--name', 'helloWorld');expect(result.exitCode).toBe(1);- expect(result.stderr).toContain('Status: ERROR');+ expect(result.stderr).toContain('Status ERROR');expect(result.stderr).toContain('Oops');expect(result.stderr).toContain('Hello from the function');});+ it.each([+ {+ status: 'SUCCESS',+ stdoutIsTTY: true,+ stderrIsTTY: false,+ noColor: false,+ },+ { status: 'ERROR', stdoutIsTTY: false, stderrIsTTY: true, noColor: false },+ { status: 'ERROR', stdoutIsTTY: true, stderrIsTTY: false, noColor: false },+ { status: 'ERROR', stdoutIsTTY: false, stderrIsTTY: true, noColor: true },+ ])(+ 'styles $status on its destination stream (stdout terminal: $stdoutIsTTY, stderr terminal: $stderrIsTTY, NO_COLOR: $noColor)',+ async ({ status, stdoutIsTTY, stderrIsTTY, noColor }) => {+ vi.stubEnv('FORCE_COLOR', undefined);+ vi.stubEnv('NO_COLOR', noColor ? '1' : undefined);+ vi.stubEnv('NODE_DISABLE_COLORS', undefined);+ vi.stubEnv('CI', undefined);+ vi.stubEnv('TERM', 'xterm-256color');+ executionResult = {+ data: {+ executeOneLogicFunction: {+ ...EXECUTION,+ status,+ error: status === 'ERROR' ? { errorMessage: 'Oops' } : null,+ },+ },+ };+ const descriptors = [process.stdout, process.stderr].map((stream) => ({+ stream,+ properties: {+ isTTY: Object.getOwnPropertyDescriptor(stream, 'isTTY'),+ getColorDepth: Object.getOwnPropertyDescriptor(+ stream,+ 'getColorDepth',+ ),+ },+ }));++ try {+ for (const { stream } of descriptors) {+ Object.defineProperties(stream, {+ isTTY: {+ configurable: true,+ value: stream === process.stdout ? stdoutIsTTY : stderrIsTTY,+ },+ getColorDepth: {+ configurable: true,+ value: WriteStream.prototype.getColorDepth,+ },+ });+ }++ const result = await run('--name', 'helloWorld');+ const output = status === 'SUCCESS' ? result.stdout : result.stderr;+ const isTerminal = status === 'SUCCESS' ? stdoutIsTTY : stderrIsTTY;++ expect(result.exitCode).toBe(status === 'SUCCESS' ? 0 : 1);+ expect(output).toContain('Hello from the function');++ if (isTerminal && !noColor) {+ expect(output).toContain(+ status === 'SUCCESS'+ ? '\u001b[32mSUCCESS\u001b[39m'+ : '\u001b[31mERROR\u001b[39m',+ );+ expect(output).toContain('\u001b[1mLogs:\u001b[22m');+ } else {+ expect(output).toContain(`Status ${status}`);+ expect(output).not.toContain('\u001b[');+ }++ if (status === 'ERROR') {+ expect(result.stdout).toBe('');+ }+ } finally {+ for (const { stream, properties } of descriptors) {+ for (const [name, descriptor] of Object.entries(properties)) {+ if (isDefined(descriptor)) {+ Object.defineProperty(stream, name, descriptor);+ } else {+ Reflect.deleteProperty(stream, name);+ }+ }+ }+ }+ },+ );++ it.each(['SUCCESS', 'ERROR'])(+ 'keeps %s JSON output free of ANSI when colors are forced',+ async (status) => {+ vi.stubEnv('NO_COLOR', undefined);+ vi.stubEnv('FORCE_COLOR', '1');+ executionResult = {+ data: {+ executeOneLogicFunction: {+ ...EXECUTION,+ status,+ error: status === 'ERROR' ? { errorMessage: 'Oops' } : null,+ },+ },+ };++ const result = await runJson('--name', 'helloWorld');++ expect(result.exitCode).toBe(status === 'SUCCESS' ? 0 : 1);+ expect(JSON.stringify(result.envelope)).not.toContain('\\u001b');+ },+ );+it('preserves permission errors without retrying execution', async () => {executionResult = {errors: [diff --git a/packages/twenty-cli/src/commands/app/add/run-app-add-command.ts b/packages/twenty-cli/src/commands/app/add/run-app-add-command.tsindex 4a685b322c2..61d80c74b5c 100644--- a/packages/twenty-cli/src/commands/app/add/run-app-add-command.ts+++ b/packages/twenty-cli/src/commands/app/add/run-app-add-command.ts@@ -8,7 +8,7 @@ import { resolveAppProject } from '@/app/project/resolve-app-project';import { readStringOption } from '@/catalog/read-command-values';import { type CommandRun } from '@/catalog/types/command-run.type';import { CliError } from '@/output/cli-error';-import { formatSuccessLine } from '@/output/style';+import { commandText, formatSuccessLine } from '@/output/style';export const runAppAddCommand: CommandRun = async (context) => {const { options, signal, output } = context;@@ -60,7 +60,7 @@ export const runAppAddCommand: CommandRun = async (context) => {]: []),'',- 'Review with twenty app plan, then run twenty app apply.',+ `Review with ${commandText('twenty app plan')}, then run ${commandText('twenty app apply')}.`,].join('\n'),};};diff --git a/packages/twenty-cli/src/commands/app/exec/run-app-exec-command.ts b/packages/twenty-cli/src/commands/app/exec/run-app-exec-command.tsindex 864c7b96df0..43325574bfb 100644--- a/packages/twenty-cli/src/commands/app/exec/run-app-exec-command.ts+++ b/packages/twenty-cli/src/commands/app/exec/run-app-exec-command.ts@@ -53,7 +53,10 @@ export const runAppExecCommand: CommandRun<TargetCommandContext> = async (`Executing ${formatDataValue(name)} on ${target.apiUrl}…`,),});- const human = formatFunctionExecution(result);+ const human = formatFunctionExecution(+ result,+ result.status === 'SUCCESS' ? process.stdout : process.stderr,+ );if (result.status !== 'SUCCESS') {if (outputMode === 'human') {diff --git a/packages/twenty-cli/src/commands/app/pull/run-app-pull-command.ts b/packages/twenty-cli/src/commands/app/pull/run-app-pull-command.tsindex a364c972e4b..86d87565b76 100644--- a/packages/twenty-cli/src/commands/app/pull/run-app-pull-command.ts+++ b/packages/twenty-cli/src/commands/app/pull/run-app-pull-command.ts@@ -20,7 +20,7 @@ import { type TargetCommandContext } from '@/catalog/types/target-command-conteximport { formatDataValue } from '@/data/format-data-value';import { CliError } from '@/output/cli-error';import { EXIT_CODE } from '@/output/constants/exit-code.constant';-import { formatSuccessLine } from '@/output/style';+import { commandText, formatSuccessLine } from '@/output/style';export const runAppPullCommand: CommandRun<TargetCommandContext> = async ({options,@@ -235,7 +235,7 @@ export const runAppPullCommand: CommandRun<TargetCommandContext> = async ({),]: []),- 'Run twenty app typecheck to check the generated definitions.',+ `Run ${commandText('twenty app typecheck')} to check the generated definitions.`,].filter(Boolean).join('\n'),diff --git a/packages/twenty-cli/src/commands/auth/logout/run-auth-logout-command.ts b/packages/twenty-cli/src/commands/auth/logout/run-auth-logout-command.tsindex bd5824a52c3..677a76bae25 100644--- a/packages/twenty-cli/src/commands/auth/logout/run-auth-logout-command.ts+++ b/packages/twenty-cli/src/commands/auth/logout/run-auth-logout-command.ts@@ -6,7 +6,7 @@ import { readConfig } from '@/config/read-config';import { updateConfig } from '@/config/update-config';import { CliError } from '@/output/cli-error';import { EXIT_CODE } from '@/output/constants/exit-code.constant';-import { dimText, formatSuccessLine } from '@/output/style';+import { commandText, dimText, formatSuccessLine } from '@/output/style';import { TARGET_ENVIRONMENT_VARIABLE } from '@/target/constants/target-environment-variable.constant';import { findRemote } from '@/target/find-remote';import { selectTarget } from '@/target/select-target';@@ -64,9 +64,7 @@ export const runAuthLogoutCommand: CommandRun = async ({human: hadCredentials? [formatSuccessLine(`Signed out of ${remoteName}.`),- dimText(- ` The remote stays; sign in with twenty auth login --remote ${remoteName} --with-token`,- ),+ `${dimText(' The remote stays; sign in with ')}${commandText(`twenty auth login --remote ${remoteName} --with-token`)}`,].join('\n'): `${remoteName} was already signed out.`,};diff --git a/packages/twenty-cli/src/commands/auth/status/run-auth-status-command.ts b/packages/twenty-cli/src/commands/auth/status/run-auth-status-command.tsindex f8ca3101296..71aed670559 100644--- a/packages/twenty-cli/src/commands/auth/status/run-auth-status-command.ts+++ b/packages/twenty-cli/src/commands/auth/status/run-auth-status-command.ts@@ -7,7 +7,7 @@ import { getConfigPath } from '@/config/get-config-path';import { readConfig } from '@/config/read-config';import { getAccessTokenExpiry } from '@/oauth/is-access-token-expiring';import { formatDetails } from '@/output/format-details';-import { dimText } from '@/output/style';+import { colorText, dimText } from '@/output/style';import { TARGET_ENVIRONMENT_VARIABLE } from '@/target/constants/target-environment-variable.constant';import { fetchSignedInIdentity } from '@/transport/metadata/fetch-signed-in-identity';@@ -44,6 +44,7 @@ export const runAuthStatusCommand: CommandRun<TargetCommandContext> = async ({const credentialsLabel = isDefined(identity.email)? `${identity.email} ${dimText(`via ${CREDENTIAL_KIND_LABELS[target.credentialKind]}`)}`: CREDENTIAL_KIND_LABELS[target.credentialKind];+ const statusLabel = colorText('green', 'valid');return {data: {@@ -66,8 +67,8 @@ export const runAuthStatusCommand: CommandRun<TargetCommandContext> = async ({['Status',isDefined(sessionExpiry)- ? `valid ${dimText(`· renews itself, current token expires in ${formatTimeLeft(sessionExpiry)}`)}`- : 'valid',+ ? `${statusLabel} ${dimText(`· renews itself, current token expires in ${formatTimeLeft(sessionExpiry)}`)}`+ : statusLabel,],]),};diff --git a/packages/twenty-cli/src/commands/commands/run-commands-command.ts b/packages/twenty-cli/src/commands/commands/run-commands-command.tsindex 7a147ab48c9..0e7e895b282 100644--- a/packages/twenty-cli/src/commands/commands/run-commands-command.ts+++ b/packages/twenty-cli/src/commands/commands/run-commands-command.ts@@ -4,7 +4,7 @@ import { COMMAND_CATALOG } from '@/catalog/command-catalog';import { getCommandName } from '@/catalog/get-command-name';import { type CommandRun } from '@/catalog/types/command-run.type';import { formatTable } from '@/output/format-table';-import { dimText } from '@/output/style';+import { commandText, dimText } from '@/output/style';import { GLOBAL_FLAGS } from '@/program/constants/global-flags.constant';export const runCommandsCommand: CommandRun = async () => {@@ -37,7 +37,7 @@ export const runCommandsCommand: CommandRun = async () => {{ header: 'DESCRIPTION', value: (command) => command.description },],}),- dimText(`${commands.length} commands · details: twenty <command> --help`),+ `${dimText(`${commands.length} commands · details: `)}${commandText('twenty <command> --help')}`,].join('\n'),};};diff --git a/packages/twenty-cli/src/commands/metadata/object/describe/run-metadata-object-describe-command.ts b/packages/twenty-cli/src/commands/metadata/object/describe/run-metadata-object-describe-command.tsindex ba85a2a7315..77d63476547 100644--- a/packages/twenty-cli/src/commands/metadata/object/describe/run-metadata-object-describe-command.ts+++ b/packages/twenty-cli/src/commands/metadata/object/describe/run-metadata-object-describe-command.ts@@ -7,6 +7,7 @@ import { formatDataValue } from '@/data/format-data-value';import { fetchMetadataInspection } from '@/metadata/fetch-metadata-inspection';import { formatMetadataOwner } from '@/metadata/format-metadata-owner';import { formatDetails } from '@/output/format-details';+import { commandText } from '@/output/style';export const runMetadataObjectDescribeCommand: CommandRun<TargetCommandContext@@ -38,7 +39,7 @@ export const runMetadataObjectDescribeCommand: CommandRun<['System', String(object.isSystem)],['Searchable', String(object.isSearchable)],]),- `Fields: twenty metadata field list ${object.namePlural}`,+ `Fields: ${commandText(`twenty metadata field list ${object.namePlural}`)}`,].join('\n\n'),};};diff --git a/packages/twenty-cli/src/commands/remote/list/run-remote-list-command.ts b/packages/twenty-cli/src/commands/remote/list/run-remote-list-command.tsindex bcb4abe56e5..001a5470aa1 100644--- a/packages/twenty-cli/src/commands/remote/list/run-remote-list-command.ts+++ b/packages/twenty-cli/src/commands/remote/list/run-remote-list-command.ts@@ -6,7 +6,7 @@ import { getConfigPath } from '@/config/get-config-path';import { getCredentialKind } from '@/config/get-credential-kind';import { readConfig } from '@/config/read-config';import { formatTable } from '@/output/format-table';-import { colorText, dimText } from '@/output/style';+import { colorText, commandText, dimText } from '@/output/style';export const runRemoteListCommand: CommandRun = async () => {const config = await readConfig(getConfigPath());@@ -25,7 +25,7 @@ export const runRemoteListCommand: CommandRun = async () => {if (remotes.length === 0) {return {data: { remotes, defaultRemote: null },- human: `No saved remotes. ${dimText('Sign in with: twenty auth login --with-token --url <url> --name <name>')}`,+ human: `No saved remotes. ${dimText('Sign in with: ')}${commandText('twenty auth login --with-token --url <url> --name <name>')}`,};}diff --git a/packages/twenty-cli/src/data/format-data-page.ts b/packages/twenty-cli/src/data/format-data-page.tsindex ee9b1403d1a..48da54e391c 100644--- a/packages/twenty-cli/src/data/format-data-page.ts+++ b/packages/twenty-cli/src/data/format-data-page.ts@@ -4,6 +4,7 @@ import { type readDataListOptions } from '@/data/read-data-list-options';import { type DataPage, type DataRecord } from '@/data/types/data-page.type';import { TABLE_LAYOUT } from '@/output/constants/table-layout.constant';import { formatTable } from '@/output/format-table';+import { dimText } from '@/output/style';const PRIORITIZED_TABLE_FIELDS = ['id', 'name'];@@ -68,7 +69,9 @@ export const formatDataPage = ({});const footer = `${page.records.length} of ${page.totalCount} records`;- return page.pageInfo.hasNextPage- ? `${table}\n${footer} · --all for every page · --json for the next cursor`- : `${table}\n${footer}`;+ return `${table}\n${dimText(+ page.pageInfo.hasNextPage+ ? `${footer} · --all for every page · --json for the next cursor`+ : footer,+ )}`;};diff --git a/packages/twenty-cli/src/output/format-details.ts b/packages/twenty-cli/src/output/format-details.tsindex 7a293f7ec3a..0da5ec27236 100644--- a/packages/twenty-cli/src/output/format-details.ts+++ b/packages/twenty-cli/src/output/format-details.ts@@ -1,9 +1,15 @@import { dimText } from '@/output/style';-export const formatDetails = (rows: [label: string, value: string][]) => {+export const formatDetails = (+ rows: [label: string, value: string][],+ stream: NodeJS.WriteStream = process.stdout,+) => {const labelWidth = Math.max(...rows.map(([label]) => label.length));return rows- .map(([label, value]) => `${dimText(label.padEnd(labelWidth))} ${value}`)+ .map(+ ([label, value]) =>+ `${dimText(label.padEnd(labelWidth), stream)} ${value}`,+ ).join('\n');};diff --git a/packages/twenty-cli/src/output/format-table.ts b/packages/twenty-cli/src/output/format-table.tsindex f3339cd3650..fbb969b84ee 100644--- a/packages/twenty-cli/src/output/format-table.ts+++ b/packages/twenty-cli/src/output/format-table.ts@@ -1,7 +1,7 @@import { stripVTControlCharacters } from 'node:util';import { TABLE_LAYOUT } from '@/output/constants/table-layout.constant';-import { dimText } from '@/output/style';+import { boldText } from '@/output/style';type TableColumn<TRow> = {header: string;@@ -53,7 +53,7 @@ export const formatTable = <TRow>({.join(TABLE_LAYOUT.COLUMN_GAP)}`.trimEnd();return [- dimText(formatRow(columns.map((column) => column.header))),+ boldText(formatRow(columns.map((column) => column.header))),...cells.map(formatRow),].join('\n');};diff --git a/packages/twenty-cli/src/output/style.ts b/packages/twenty-cli/src/output/style.tsindex 64b978415e1..8f1f7d9aa3d 100644--- a/packages/twenty-cli/src/output/style.ts+++ b/packages/twenty-cli/src/output/style.ts@@ -11,6 +11,8 @@ export const colorText = (stream: NodeJS.WriteStream = process.stdout,) => styleText(color, text, { stream });+export const commandText = (command: string) => colorText('cyan', command);+export const boldText = (text: string,stream: NodeJS.WriteStream = process.stdout,