Skip to content

Commit

Permalink
feature: supertape: formatter: time: add
Browse files Browse the repository at this point in the history
  • Loading branch information
coderaiser committed Dec 22, 2023
1 parent c62cedf commit 1e0cbdf
Show file tree
Hide file tree
Showing 13 changed files with 894 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,7 @@ There is a list of built-int `formatters` to customize output:
| Package | Version |
|--------|-------|
| [`@supertape/formatter-tap`](/packages/formatter-tap) | [![npm](https://img.shields.io/npm/v/@supertape/formatter-tap.svg?maxAge=86400)](https://www.npmjs.com/package/@supertape/formatter-tap) |
| [`@supertape/formatter-time`](/packages/formatter-time) | [![time](https://img.shields.io/npm/v/@supertape/formatter-time.svg?maxAge=86400)](https://www.npmjs.com/package/@supertape/formatter-time) |
| [`@supertape/formatter-fail`](/packages/formatter-fail) | [![npm](https://img.shields.io/npm/v/@supertape/formatter-fail.svg?maxAge=86400)](https://www.npmjs.com/package/@supertape/formatter-fail) |
| [`@supertape/formatter-short`](/packages/formatter-short) | [![npm](https://img.shields.io/npm/v/@supertape/formatter-short.svg?maxAge=86400)](https://www.npmjs.com/package/@supertape/formatter-short) |
| [`@supertape/formatter-progress-bar`](/packages/formatter-progress-bar) | [![npm](https://img.shields.io/npm/v/@supertape/formatter-progress-bar.svg?maxAge=86400)](https://www.npmjs.com/package/@supertape/formatter-progress-bar) |
Expand Down
10 changes: 10 additions & 0 deletions packages/formatter-time/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"extends": [
"plugin:n/recommended",
"plugin:putout/recommended"
],
"plugins": [
"n",
"putout"
]
}
8 changes: 8 additions & 0 deletions packages/formatter-time/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
*.swp
node_modules
.nyc_output
yarn-error.log
.*.swp

coverage
.idea
13 changes: 13 additions & 0 deletions packages/formatter-time/.madrun.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import {run} from 'madrun';

export default {
'test': () => `supertape 'lib/**/*.spec.js'`,
'watch:test': async () => `nodemon -w lib -w test -x "${await run('test')}"`,
'lint': () => 'putout .',
'fresh:lint': () => run('lint', '--fresh'),
'lint:fresh': () => run('lint', '--fresh'),
'fix:lint': () => run('lint', '--fix'),
'coverage': () => `c8 npm test`,
'report': () => 'c8 report --reporter=lcov',
'wisdom': () => run(['lint', 'coverage']),
};
8 changes: 8 additions & 0 deletions packages/formatter-time/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
.*
*.spec.js
test
yarn-error.log
coverage

fixture

9 changes: 9 additions & 0 deletions packages/formatter-time/.nycrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"check-coverage": true,
"all": true,
"exclude": [".*", "{bin,lib}/**/{fixture,*.spec.{js,mjs}}"],
"branches": 100,
"lines": 100,
"functions": 100,
"statements": 100
}
7 changes: 7 additions & 0 deletions packages/formatter-time/.putout.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"match": {
"*.md": {
"remove-unreachable-code": "off"
}
}
}
21 changes: 21 additions & 0 deletions packages/formatter-time/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) coderaiser

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
31 changes: 31 additions & 0 deletions packages/formatter-time/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# @supertape/formatter-time [![NPM version][NPMIMGURL]][NPMURL]

[NPMIMGURL]: https://img.shields.io/npm/v/@supertape/formatter-time.svg?style=flat&longCache=true
[NPMURL]: https://npmjs.org/package/@supertape/formatter-time "npm"

📼[`Supertape`](https://github.com/coderaiser/supertape) formatter shows progress bar.

## Install

```
npm i supertape @supertape/formatter-time
```

## Usage

```
supertape --format time lib
```

## Env Variables

- `CI=1` - disable progress bar
- `SUPERTAPE_TIME=1` - force enable/disable progress bar;
- `SUPERTAPE_TIME_COLOR` - set color of progress bar;
- `SUPERTAPE_TIME_MIN=100` - count of tests to show progress bar;
- `SUPERTAPE_TIME_STACK=1` - force show/hide stack on fail;
- `SUPERTAPE_TIME_CLOCK=⏳` - set clock icon;

## License

MIT
236 changes: 236 additions & 0 deletions packages/formatter-time/lib/time.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,236 @@
import {Writable} from 'node:stream';
import cliProgress from 'cli-progress';
import chalk from 'chalk';
import fullstore from 'fullstore';
import {isCI} from 'ci-info';
import process from 'node:process';
import {Timer} from 'timer-node';

global._isCI = isCI;

const OK = '👌';
const YELLOW = '#218bff';

const {red} = chalk;
const formatErrorsCount = (a) => a ? red(a) : OK;

const isStr = (a) => typeof a === 'string';

const {stderr} = process;

let SUPERTAPE_TIME;
let SUPERTAPE_TIME_MIN = 100;
let SUPERTAPE_TIME_COLOR;
let SUPERTAPE_TIME_STACK = 1;
let SUPERTAPE_TIME_CLOCK = '⏳';

export function createFormatter(bar) {
({
SUPERTAPE_TIME,
SUPERTAPE_TIME_MIN = 100,
SUPERTAPE_TIME_COLOR,
SUPERTAPE_TIME_STACK = 1,
SUPERTAPE_TIME_CLOCK = '⏳',
} = process.env);

const out = createOutput();
const store = fullstore();
const barStore = fullstore(bar);
const timerStore = fullstore();

return {
start: start({
barStore,
timerStore,
out,
}),
test: test({
store,
}),
testEnd: testEnd({
clock: SUPERTAPE_TIME_CLOCK,
barStore,
timerStore,
}),
fail: fail({
out,
store,
}),
end: end({
barStore,
out,
}),
};
}

export const start = ({barStore, timerStore, out}) => ({total}) => {
out('TAP version 13');

const color = SUPERTAPE_TIME_COLOR || YELLOW;
const {bar, timer} = _createProgress({
total,
color,
test: '',
});

barStore(bar);
timerStore(timer);
};

export const test = ({store}) => ({test}) => {
store(`# ${test}`);
};

export const testEnd = ({barStore, clock, timerStore}) => ({count, total, failed, test}) => {
const timer = timerStore();

barStore().increment({
count,
total,
test,
failed: formatErrorsCount(failed),
time: !timer ? '' : getTime({
clock,
timer: timerStore(),
}),
});
};

export const fail = ({out, store}) => ({at, count, message, operator, result, expected, output, errorStack}) => {
out('');
out(store());
out(`❌ not ok ${count} ${message}`);
out(' ---');
out(` operator: ${operator}`);

if (output)
out(output);

if (!isStr(output)) {
out(' expected: |-');
out(` ${expected}`);
out(' result: |-');
out(` ${result}`);
}

out(` ${at}`);

if (SUPERTAPE_TIME_STACK !== '0') {
out(' stack: |-');
out(errorStack);
}

out(' ...');
out('');
};

export const end = ({barStore, out}) => ({count, passed, failed, skiped}) => {
barStore().stop();

out('');

out(`1..${count}`);
out(`# tests ${count}`);
out(`# pass ${passed}`);

if (skiped)
out(`# ⚠️ skip ${skiped}`);

out('');

if (failed)
out(`# ❌ fail ${failed}`);

if (!failed)
out('# ✅ ok');

out('');
out('');

return `\r${out()}`;
};

function createOutput() {
let output = [];

return (...args) => {
const [line] = args;

if (!args.length) {
const result = output.join('\n');

output = [];

return result;
}

output.push(line);
};
}

const getColorFn = (color) => {
if (color.startsWith('#'))
return chalk.hex(color);

return chalk[color];
};

const defaultStreamOptions = {
total: Infinity,
};

const getStream = ({total} = defaultStreamOptions) => {
const is = total >= SUPERTAPE_TIME_MIN;

if (is && !global._isCI || SUPERTAPE_TIME === '1')
return stderr;

return new Writable();
};

export const _getStream = getStream;

function _createProgress({total, color, test}) {
const timer = new Timer({
label: 'supertape-timer',
});

const colorFn = getColorFn(color);
const bar = new cliProgress.SingleBar({
format: `${colorFn('{bar}')} {percentage}% | {failed} | {count}/{total} | {time} | {test}`,
barCompleteChar: '\u2588',
barIncompleteChar: '\u2591',
clearOnComplete: true,
stopOnComplete: true,
hideCursor: true,
stream: getStream({
total,
}),
}, cliProgress.Presets.react);

bar.start(total, 0, {
test,
total,
count: 0,
failed: OK,
time: getTime({
clock: SUPERTAPE_TIME_CLOCK,
timer,
}),
});

return {
bar,
timer,
};
}

export const maybeZero = (a) => a <= 9 ? '0' : '';

function getTime({clock, timer}) {
const {m, s} = timer.time();
const minute = `${maybeZero(m)}${m}`;
const second = `${maybeZero(s)}${s}`;

return `${clock} ${minute}:${second}`;
}
Loading

0 comments on commit 1e0cbdf

Please sign in to comment.