Skip to content

Commit 1ab72ed

Browse files
authored
refactor: improve format internal method (#439)
* refactor: improve `format` internal method * refactor: improve log colors * chore: improve dynamic logs * chore: fix missing logs * chore: fix missing logs * chore: improve `bg` usage
1 parent 9962a02 commit 1ab72ed

File tree

17 files changed

+271
-88
lines changed

17 files changed

+271
-88
lines changed

src/bin/index.ts

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -95,11 +95,11 @@ const options: Configs = {
9595

9696
if (debug) {
9797
hr();
98-
write(`${format.bg(104, 'Debug Enabled')}\n`);
99-
write(`${format.italic(format.info('…'))} ${format.bold('Paths')}`);
98+
write(`${format(' Debug Enabled ').bg('brightBlue')}\n`);
99+
write(`${format('…').info().italic()} ${format('Paths').bold()}`);
100100
console.table(dirs);
101101
write('\n');
102-
write(`${format.italic(format.info('…'))} ${format.bold('Options')}`);
102+
write(`${format('…').info().italic()} ${format('Options').bold()}`);
103103
console.dir(options, { depth: null, colors: true });
104104
}
105105

@@ -160,7 +160,9 @@ Promise.all(tasks).then(() => {
160160
});
161161

162162
hr();
163-
write(`${format.bold('Watching:')} ${format.underline(dirs.join(', '))}`);
163+
write(
164+
`${format('Watching:').bold()} ${format(dirs.join(', ')).underline()}`
165+
);
164166
}
165167
});
166168
});

src/helpers/format.ts

Lines changed: 71 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
/* c8 ignore start */
1+
/* c8 ignore next */
22
import { padStart } from '../polyfills/pad.js';
33

44
export const backgroundColor = {
@@ -19,26 +19,77 @@ export const backgroundColor = {
1919
brightCyan: 106,
2020
} as const;
2121

22-
export const format = {
23-
counter: (current: number, total: number, pad = '0') => {
22+
export class Formatter {
23+
private parts: string = '';
24+
private text: string;
25+
26+
constructor(text: string) {
27+
this.text = text;
28+
}
29+
30+
static create(text: string) {
31+
return new Formatter(text);
32+
}
33+
34+
counter(current: number, total: number, pad = '0') {
2435
const totalDigits = String(total).length;
25-
return padStart(String(current), totalDigits, pad);
26-
},
27-
dim: (value: string) => `\x1b[2m${value}\x1b[0m`,
28-
bold: (value: string) => `\x1b[1m${value}\x1b[0m`,
29-
underline: (value: string) => `\x1b[4m${value}\x1b[0m`,
30-
info: (value: string) => `\x1b[94m${value}\x1b[0m`,
31-
italic: (value: string) => `\x1b[3m${value}\x1b[0m`,
32-
success: (value: string) => `\x1b[32m${value}\x1b[0m`,
33-
fail: (value: string) => `\x1b[91m${value}\x1b[0m`,
34-
bg: (bg: number, text: string) => {
35-
const padding = ' '.repeat(1);
36-
const paddedText = `${padding}${text}${padding}`;
37-
38-
return `\x1b[${bg}m\x1b[1m${paddedText}\x1b[0m`;
39-
},
40-
};
36+
const formattedCounter = padStart(String(current), totalDigits, pad);
37+
this.parts += formattedCounter;
38+
return this;
39+
}
40+
41+
dim() {
42+
this.parts += '\x1b[2m';
43+
return this;
44+
}
45+
46+
bold() {
47+
this.parts += '\x1b[1m';
48+
return this;
49+
}
50+
51+
underline() {
52+
this.parts += '\x1b[4m';
53+
return this;
54+
}
55+
56+
info() {
57+
this.parts += '\x1b[94m';
58+
return this;
59+
}
60+
61+
italic() {
62+
this.parts += '\x1b[3m';
63+
return this;
64+
}
65+
66+
success() {
67+
this.parts += '\x1b[32m';
68+
return this;
69+
}
70+
71+
fail() {
72+
this.parts += '\x1b[91m';
73+
return this;
74+
}
75+
76+
gray() {
77+
this.parts += '\x1b[90m';
78+
return this;
79+
}
80+
81+
bg(color: keyof typeof backgroundColor) {
82+
this.parts += `\x1b[${backgroundColor[color]}m\x1b[1m`;
83+
return this;
84+
}
85+
86+
[Symbol.toPrimitive]() {
87+
return `${this.parts}${this.text}\x1b[0m`;
88+
}
89+
}
90+
91+
export const format = (text: string) => Formatter.create(text);
4192

93+
/* c8 ignore next */
4294
export const getLargestStringLength = (arr: string[]): number =>
4395
arr.reduce((max, current) => Math.max(max, current.length), 0);
44-
/* c8 ignore stop */

src/helpers/get-arg.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,5 +77,4 @@ export const argToArray = (arg: string, prefix = '--') => {
7777
.map((a) => a.trim())
7878
.filter((a) => a);
7979
};
80-
8180
/* c8 ignore stop */

src/helpers/get-runtime.ts

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
/* c8 ignore start */
2-
32
import { version } from 'node:process';
43
import type { Configs } from '../@types/poku.js';
54

@@ -38,5 +37,4 @@ export const getRuntime = (
3837

3938
export const nodeVersion =
4039
getRuntime() === 'node' ? Number(version.match(/v(\d+)\./)?.[1]) : undefined;
41-
4240
/* c8 ignore stop */

src/helpers/logs.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
/* c8 ignore start */
2-
32
import { stdout } from 'node:process';
43
import type { Configs } from '../@types/poku.js';
4+
import type { Formatter } from './format.js';
55

66
export const isQuiet = (configs?: Configs): boolean =>
77
typeof configs?.quiet === 'boolean' && Boolean(configs?.quiet);
88

99
export const isDebug = (configs?: Configs): boolean => Boolean(configs?.debug);
1010

11-
export const write = (data: string | Uint8Array) =>
11+
export const write = (data: string | Uint8Array | Formatter) =>
1212
stdout.write(`${String(data)}\n`);
1313

1414
export const printOutput = (options: {
@@ -39,5 +39,4 @@ export const printOutput = (options: {
3939

4040
write(mappedOutputs.join('\n'));
4141
};
42-
4342
/* c8 ignore stop */

src/helpers/parse-assertion.ts

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -89,9 +89,14 @@ export const parseAssertion = async (
8989
}
9090

9191
if (typeof options.message === 'string') {
92-
const message = isPoku
93-
? `${preIdentation}${format.bold(format.success(`✔ ${options.message}`))} ${format.dim(format.success(`› ${FILE}`))}`
94-
: `${preIdentation}${format.bold(format.success(`✔ ${options.message}`))}`;
92+
const message =
93+
isPoku &&
94+
!indentation.hasDescribe &&
95+
!indentation.hasIt &&
96+
!indentation.hasTest
97+
? /* c8 ignore next */
98+
`${preIdentation}${format(`${format(`✔ ${options.message}`).bold()} ${format(`› ${FILE}`).success().dim()}`).success()}`
99+
: `${preIdentation}${format(`✔ ${options.message}`).success().bold()}`;
95100

96101
write(message);
97102
}
@@ -112,33 +117,35 @@ export const parseAssertion = async (
112117

113118
const finalMessage =
114119
message?.trim().length > 0
115-
? format.bold(format.fail(`✘ ${message}`))
116-
: format.bold(format.fail('✘ No Message'));
120+
? format(`✘ ${message}`).fail().bold()
121+
: format('✘ No Message').fail().bold();
117122

118123
write(
119124
isPoku
120-
? `${preIdentation}${finalMessage} ${format.dim(format.fail(`› ${FILE}`))}`
125+
? `${preIdentation}${finalMessage} ${format(`› ${FILE}`).fail().dim()}`
121126
: `${preIdentation}${finalMessage}`
122127
);
123128

124-
file && write(`${format.dim(`${preIdentation} File`)} ${file}`);
125-
write(`${format.dim(`${preIdentation} Code`)} ${code}`);
126-
write(`${format.dim(`${preIdentation} Operator`)} ${operator}\n`);
129+
file && write(`${format(`${preIdentation} File`).dim()} ${file}`);
130+
write(`${format(`${preIdentation} Code`).dim()} ${code}`);
131+
write(`${format(`${preIdentation} Operator`).dim()} ${operator}\n`);
127132

128133
if (!options?.hideDiff) {
129134
const splitActual = parseResultType(actual).split('\n');
130135
const splitExpected = parseResultType(expected).split('\n');
131136

132-
write(format.dim(`${preIdentation} ${options?.actual || 'Actual'}:`));
137+
write(
138+
format(`${preIdentation} ${options?.actual || 'Actual'}:`).dim()
139+
);
133140
splitActual.forEach((line) =>
134-
write(`${preIdentation} ${format.bold(format.fail(line))}`)
141+
write(`${preIdentation} ${format(line).fail().bold()}`)
135142
);
136143

137144
write(
138-
`\n${preIdentation} ${format.dim(`${options?.expected || 'Expected'}:`)}`
145+
`\n${preIdentation} ${format(`${options?.expected || 'Expected'}:`).dim()}`
139146
);
140147
splitExpected.forEach((line) =>
141-
write(`${preIdentation} ${format.bold(format.success(line))}`)
148+
write(`${preIdentation} ${format(line).success().bold()}`)
142149
);
143150
}
144151

src/helpers/runner.ts

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
/* c8 ignore start */
2-
32
import { platform } from 'node:process';
43
import { extname } from 'node:path';
54
import { getRuntime } from './get-runtime.js';
@@ -60,5 +59,4 @@ export const scriptRunner = (runner: Runner): string[] => {
6059
// Node.js
6160
return [isWindows ? 'npm.cmd' : 'npm', 'run'];
6261
};
63-
6462
/* c8 ignore stop */

src/helpers/time.ts

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
/* c8 ignore start */
2-
32
import { padStart } from '../polyfills/pad.js';
43

54
export const setTime = (date: Date): string => {
@@ -16,5 +15,4 @@ export const toSecs = (milliseconds: string): string => {
1615

1716
return seconds;
1817
};
19-
2018
/* c8 ignore stop */

src/modules/describe.ts

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
/* c8 ignore next */
2-
import { hrtime } from 'node:process';
3-
import { format, backgroundColor } from '../helpers/format.js';
2+
import { hrtime, env } from 'node:process';
3+
import { format } from '../helpers/format.js';
44
import { write } from '../helpers/logs.js';
55
/* c8 ignore next */
66
import { indentation } from '../configs/indentation.js';
@@ -28,6 +28,9 @@ export async function describe(
2828
let cb: (() => unknown | Promise<unknown>) | undefined;
2929
let options: DescribeOptions | undefined;
3030

31+
const isPoku = typeof env?.FILE === 'string' && env?.FILE.length > 0;
32+
const FILE = env.FILE;
33+
3134
if (typeof arg1 === 'string') {
3235
title = arg1;
3336

@@ -43,13 +46,15 @@ export async function describe(
4346
indentation.hasDescribe = true;
4447

4548
const { background, icon } = options || {};
46-
const message = `${cb ? format.dim('◌') : icon || '☰'} ${cb ? format.dim(title) : format.bold(title) || ''}`;
49+
const message = `${cb ? format('◌').dim() : icon || '☰'} ${cb ? format(isPoku ? `${title}${format(`${FILE}`).italic().gray()}` : title).dim() : format(title).bold() || ''}`;
4750
const noBackground = !background;
4851

49-
if (noBackground) write(`${format.bold(message)}`);
52+
if (noBackground) write(format(message).bold());
5053
else {
5154
write(
52-
`${format.bg(backgroundColor[typeof background === 'string' ? background : 'grey'], message)}`
55+
format(` ${message} `).bg(
56+
typeof background === 'string' ? background : 'grey'
57+
)
5358
);
5459
}
5560
}
@@ -70,7 +75,7 @@ export async function describe(
7075

7176
indentation.hasDescribe = false;
7277
write(
73-
`${format.bold(format.success('●'))} ${format.bold(format.success(title))} ${format.dim(`› ${total}ms`)}`
78+
`${format(`● ${title}`).success().bold()} ${format(`› ${total}ms`).success().dim()}`
7479
);
7580
}
7681
/* c8 ignore stop */

src/modules/exit.ts

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,25 +16,23 @@ export const exit = (code: Code, quiet?: boolean) => {
1616
if (isPoku) {
1717
hr();
1818
write(
19-
` ${format.dim('Start at ›')} ${format.bold(format.dim(`${setTime(finalResults.started)}`))}`
19+
` ${format(`Start at › ${format(`${setTime(finalResults.started)}`).bold()}`).dim()}`
2020
);
2121
write(
22-
` ${format.dim('Duration ›')} ${format.bold(format.dim(`${finalResults.time}ms`))} ${`${format.dim(`(±${toSecs(finalResults.time)} seconds)`)}`}`
22+
` ${format('Duration ›').dim()} ${format(`${finalResults.time}ms`).bold().dim()} ${format(`(±${toSecs(finalResults.time)} seconds)`).dim()}`
2323
);
2424
write(
25-
` ${format.dim('Test Files ›')} ${format.bold(format.dim(`${fileResults.success.size + fileResults.fail.size}`))}`
25+
` ${format(`Test Files › ${format(String(fileResults.success.size + fileResults.fail.size)).bold()}`).dim()}`
2626
);
2727
hr();
2828
write(
29-
format.bg(42, `PASS › ${results.success}`) +
30-
' ' +
31-
format.bg(results.fail === 0 ? 100 : 41, `FAIL › ${results.fail}`)
29+
`${format(` PASS › ${results.success} `).bg('green')} ${format(` FAIL › ${results.fail} `).bg(results.fail === 0 ? 'grey' : 'red')}`
3230
);
3331
hr();
3432
}
3533

3634
write(
37-
`${format.dim('Exited with code')} ${format.bold(format?.[code === 0 ? 'success' : 'fail'](String(code)))}\n`
35+
`${format('Exited with code').dim()} ${format(String(code)).bold()[code === 0 ? 'success' : 'fail']()}\n`
3836
);
3937
});
4038

src/modules/it.ts

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/* c8 ignore next */
2-
import { hrtime } from 'node:process';
2+
import { hrtime, env } from 'node:process';
33
/* c8 ignore next */
44
import { each } from '../configs/each.js';
55
/* c8 ignore next */
@@ -25,6 +25,9 @@ export async function it(
2525
let message: string | undefined;
2626
let cb: () => unknown | Promise<unknown>;
2727

28+
const isPoku = typeof env?.FILE === 'string' && env?.FILE.length > 0;
29+
const FILE = env.FILE;
30+
2831
if (typeof each.before.cb === 'function' && each.before.test) {
2932
const beforeResult = each.before.cb();
3033

@@ -41,7 +44,9 @@ export async function it(
4144
if (message) {
4245
indentation.hasIt = true;
4346
write(
44-
`${indentation.hasDescribe ? ' ' : ''}${format.dim('◌')} ${format.dim(message)}`
47+
isPoku && !indentation.hasDescribe
48+
? `${indentation.hasDescribe ? ' ' : ''}${format(`◌ ${message}${format(`${FILE}`).italic().gray()}`).dim()}`
49+
: `${indentation.hasDescribe ? ' ' : ''}${format(`◌ ${message}`).dim()}`
4550
);
4651
}
4752
/* c8 ignore end */
@@ -65,7 +70,7 @@ export async function it(
6570

6671
indentation.hasIt = false;
6772
write(
68-
`${indentation.hasDescribe ? ' ' : ''}${format.bold(format.success('●'))} ${format.bold(format.success(message))} ${format.dim(`› ${total}ms`)}`
73+
`${indentation.hasDescribe ? ' ' : ''}${format(`● ${message}`).success().bold()} ${format(`› ${total}ms`).success().dim()}`
6974
);
7075
}
7176
/* c8 ignore stop */

0 commit comments

Comments
 (0)