forked from sindresorhus/log-update
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
85 lines (68 loc) · 1.83 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import process from 'node:process';
import ansiEscapes from 'ansi-escapes';
import cliCursor from 'cli-cursor';
import wrapAnsi from 'wrap-ansi';
import sliceAnsi from 'slice-ansi';
const defaultTerminalHeight = 24;
const getWidth = stream => {
const {columns} = stream;
if (!columns) {
return 80;
}
return columns;
};
const fitToTerminalHeight = (stream, text) => {
const terminalHeight = stream.rows || defaultTerminalHeight;
const lines = text.split('\n');
const toRemove = lines.length - terminalHeight;
if (toRemove <= 0) {
return text;
}
return sliceAnsi(
text,
lines.slice(0, toRemove).join('\n').length + 1,
text.length);
};
export function createLogUpdate(stream, {showCursor = false} = {}) {
let previousLineCount = 0;
let previousWidth = getWidth(stream);
let previousOutput = '';
const render = (...arguments_) => {
if (!showCursor) {
cliCursor.hide();
}
let output = arguments_.join(' ') + '\n';
output = fitToTerminalHeight(stream, output);
const width = getWidth(stream);
if (output === previousOutput && previousWidth === width) {
return;
}
previousOutput = output;
previousWidth = width;
output = wrapAnsi(output, width, {
trim: false,
hard: true,
wordWrap: false,
});
stream.write(ansiEscapes.eraseLines(previousLineCount) + output);
previousLineCount = output.split('\n').length;
};
render.clear = () => {
stream.write(ansiEscapes.eraseLines(previousLineCount));
previousOutput = '';
previousWidth = getWidth(stream);
previousLineCount = 0;
};
render.done = () => {
previousOutput = '';
previousWidth = getWidth(stream);
previousLineCount = 0;
if (!showCursor) {
cliCursor.show();
}
};
return render;
}
const logUpdate = createLogUpdate(process.stdout);
export default logUpdate;
export const logUpdateStderr = createLogUpdate(process.stderr);