数通智联化工云平台
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

87 lines
1.9 KiB

2 years ago
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';
import stripAnsi from 'strip-ansi';
2 years ago
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,
2 years ago
stripAnsi(lines.slice(0, toRemove).join('\n')).length + 1,
);
2 years ago
};
2 years ago
export function createLogUpdate(stream, {showCursor = false} = {}) {
2 years ago
let previousLineCount = 0;
let previousWidth = getWidth(stream);
let previousOutput = '';
2 years ago
const render = (...arguments_) => {
2 years ago
if (!showCursor) {
cliCursor.hide();
}
2 years ago
let output = arguments_.join(' ') + '\n';
2 years ago
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,
2 years ago
wordWrap: false,
2 years ago
});
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;
2 years ago
}
const logUpdate = createLogUpdate(process.stdout);
export default logUpdate;
2 years ago
2 years ago
export const logUpdateStderr = createLogUpdate(process.stderr);