visual-exec 0.1.14 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2025 Joel Chen
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,99 @@
1
- # Visual Exec
1
+ [![NPM version][npm-image]][npm-url] [![Build Status][build-image]][build-url]
2
2
 
3
- Execute shell command and show output with in place logging and spinner.
3
+ # visual-exec
4
+
5
+ Run a shell command and show it as a live spinner line instead of a wall of output.
6
+
7
+ Output is captured while the command runs and the terminal shows a single updating line; on failure the captured output is logged so you can see what went wrong. The default logger detects CI and turns the in-place items off there, so build logs stay plain. Built on [visual-logger] and [xsh].
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ npm install visual-exec
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ ```js
18
+ import VisualExec from "visual-exec";
19
+
20
+ const ve = new VisualExec({
21
+ command: "npm install",
22
+ cwd: "/path/to/project",
23
+ displayTitle: "installing dependencies"
24
+ });
25
+
26
+ const { stdout, stderr } = await ve.execute();
27
+ ```
28
+
29
+ ## API
30
+
31
+ ### `new VisualExec(options)`
32
+
33
+ **Command**
34
+
35
+ | option | description |
36
+ | --- | --- |
37
+ | `command` | the command to run (required) |
38
+ | `cwd` | working directory |
39
+ | `maxBuffer` | max stdout/stderr buffer, default 10MB |
40
+
41
+ **Display**
42
+
43
+ | option | description |
44
+ | --- | --- |
45
+ | `displayTitle` | text shown on the spinner line while running |
46
+ | `logLabel` / `outputLabel` | labels used in log and output messages |
47
+ | `outputLevel` | log level for captured output, default `verbose` |
48
+ | `visualLogger` | a [visual-logger] instance to log through |
49
+ | `spinner` | spinner style |
50
+
51
+ **Failure handling**
52
+
53
+ | option | description |
54
+ | --- | --- |
55
+ | `forceStderr` | log stderr as error, default true |
56
+ | `checkStdoutError` | boolean or regex - treat matching stdout as an error, default true |
57
+
58
+ **Cancellation**
59
+
60
+ | option | description |
61
+ | --- | --- |
62
+ | `timeout` | milliseconds before the process is killed |
63
+ | `timeoutGrace` | ms between SIGTERM and SIGKILL, default 5000 |
64
+ | `onTimeout` | called just before killing |
65
+ | `signal` | an `AbortSignal` to cancel with |
66
+
67
+ **Consuming output**
68
+
69
+ | option | description |
70
+ | --- | --- |
71
+ | `onOutput(data, stream)` | called on each stdout/stderr chunk |
72
+ | `onComplete(output, exitCode)` | called when finished; its return value becomes `execute()`'s result on success |
73
+ | `outputFile` / `outputFileOptions` | stream output to a file (`append`, `includeStderr`, `timestamps`) |
74
+ | `progress` / `onProgress` | extract progress from output by regex or custom function |
75
+ | `matchers` | `[{ pattern, onMatch }]` run against output lines |
76
+
77
+ ### Methods
78
+
79
+ - **`execute(command?)`** - run it; resolves to `{ stdout, stderr }`, or to `onComplete`'s return value when one is given
80
+ - **`abort()`** / **`kill(signal?)`** - stop a running command
81
+
82
+ ### Errors
83
+
84
+ A failure throws a `VisualExecError` carrying `exitCode`, `signal`, `cwd`, `command`, `duration`, `lastLines`, `stdout` and `stderr`.
85
+
86
+ ### Also exported
87
+
88
+ `getDefaultLogger()`, and the output parsers `parsers`, `jsonLinesParser`, `keyValueParser`.
89
+
90
+ ## License
91
+
92
+ Licensed under the [Apache License, Version 2.0](./LICENSE).
93
+
94
+ [visual-logger]: https://github.com/jchip/fynjs/tree/main/packages/visual-logger
95
+ [xsh]: https://github.com/jchip/fynjs/tree/main/packages/xsh
96
+ [npm-image]: https://badge.fury.io/js/visual-exec.svg
97
+ [npm-url]: https://npmjs.org/package/visual-exec
98
+ [build-image]: https://github.com/jchip/fynjs/actions/workflows/ci.yml/badge.svg
99
+ [build-url]: https://github.com/jchip/fynjs/actions/workflows/ci.yml
@@ -0,0 +1,3 @@
1
+ import VisualLogger from "visual-logger";
2
+ export declare function getDefaultLogger(): VisualLogger;
3
+ export default getDefaultLogger;
@@ -0,0 +1,14 @@
1
+ import VisualLogger from "visual-logger";
2
+ import { isCI } from "ci-info";
3
+ let logger = null;
4
+ export function getDefaultLogger() {
5
+ if (!logger) {
6
+ logger = new VisualLogger();
7
+ if (isCI) {
8
+ logger.info("visual-exec: CI env detected");
9
+ logger.setItemType("none");
10
+ }
11
+ }
12
+ return logger;
13
+ }
14
+ export default getDefaultLogger;
@@ -0,0 +1,4 @@
1
+ export { VisualExec, VisualExecOptions, ExecOutput, ExecErrorContext, VisualExecError, parsers, jsonLinesParser, keyValueParser } from "./visual-exec.js";
2
+ export type { OnOutputCallback, OnCompleteCallback, OutputFileOptions, ProgressExtractor, OutputMatcher } from "./visual-exec.js";
3
+ export { getDefaultLogger } from "./get-default-logger.js";
4
+ export { VisualExec as default } from "./visual-exec.js";
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { VisualExec, parsers, jsonLinesParser, keyValueParser } from "./visual-exec.js";
2
+ export { getDefaultLogger } from "./get-default-logger.js";
3
+ export { VisualExec as default } from "./visual-exec.js";
@@ -0,0 +1,184 @@
1
+ import VisualLogger from "visual-logger";
2
+ export type OutputStream = "stdout" | "stderr";
3
+ /** Called on each chunk of stdout/stderr during execution */
4
+ export type OnOutputCallback = (data: string, stream: OutputStream) => void;
5
+ /** Called after command completes. Can return structured result passed through to execute() */
6
+ export type OnCompleteCallback = (output: ExecOutput, exitCode: number) => unknown;
7
+ export interface OutputFileOptions {
8
+ /** Append to existing file (default: false) */
9
+ append?: boolean;
10
+ /** Include stderr in output (default: true) */
11
+ includeStderr?: boolean;
12
+ /** Add timestamps per line (default: false) */
13
+ timestamps?: boolean;
14
+ }
15
+ export interface ProgressExtractor {
16
+ /** Regex with named groups: (?<current>\d+)/(?<total>\d+) or (?<percent>\d+)% */
17
+ pattern?: RegExp;
18
+ /** Custom extractor function */
19
+ extract?: (line: string) => {
20
+ current?: number;
21
+ total?: number;
22
+ percent?: number;
23
+ } | null;
24
+ /** Display format for progress */
25
+ format?: (p: {
26
+ current?: number;
27
+ total?: number;
28
+ percent?: number;
29
+ }) => string;
30
+ }
31
+ export interface OutputMatcher {
32
+ pattern: RegExp;
33
+ onMatch: (match: RegExpMatchArray) => void;
34
+ }
35
+ export interface VisualExecOptions {
36
+ /** The command to execute */
37
+ command: string;
38
+ /** Working directory for the command */
39
+ cwd?: string;
40
+ /** Visual logger instance to use */
41
+ visualLogger?: VisualLogger;
42
+ /** Spinner style to use */
43
+ spinner?: any;
44
+ /** Title displayed during execution */
45
+ displayTitle?: string;
46
+ /** Label used in log messages */
47
+ logLabel?: string;
48
+ /** Label used in output messages */
49
+ outputLabel?: string;
50
+ /** Log level for output (default: "verbose") */
51
+ outputLevel?: string;
52
+ /** Maximum buffer size for stdout/stderr (default: 10MB) */
53
+ maxBuffer?: number;
54
+ /** Force stderr output to be logged as error (default: true) */
55
+ forceStderr?: boolean;
56
+ /** Regex or boolean to check stdout for error patterns (default: true) */
57
+ checkStdoutError?: boolean | RegExp;
58
+ /** Timeout in milliseconds. Process killed if exceeded. */
59
+ timeout?: number;
60
+ /** Grace period in ms before SIGKILL after SIGTERM (default: 5000) */
61
+ timeoutGrace?: number;
62
+ /** Callback before killing on timeout */
63
+ onTimeout?: () => void;
64
+ /** Called on each chunk of stdout/stderr during execution */
65
+ onOutput?: OnOutputCallback;
66
+ /** Called after command completes. Return value passed through to execute() when exitCode is 0 */
67
+ onComplete?: OnCompleteCallback;
68
+ /** Stream output to file (path or stream) */
69
+ outputFile?: string | NodeJS.WritableStream;
70
+ /** Options for outputFile when path string */
71
+ outputFileOptions?: OutputFileOptions;
72
+ /** AbortSignal for cancellation (e.g. from AbortController) */
73
+ signal?: AbortSignal;
74
+ /** Progress extraction config */
75
+ progress?: ProgressExtractor;
76
+ /** Called when progress is extracted */
77
+ onProgress?: (progress: {
78
+ current?: number;
79
+ total?: number;
80
+ percent?: number;
81
+ }) => void;
82
+ /** Regex matchers for output lines */
83
+ matchers?: OutputMatcher[];
84
+ }
85
+ export interface ExecOutput {
86
+ stdout: string;
87
+ stderr: string;
88
+ }
89
+ export interface ExecErrorContext {
90
+ exitCode: number;
91
+ signal: string | null;
92
+ cwd: string;
93
+ command: string;
94
+ duration: number;
95
+ lastLines: string[];
96
+ stdout: string;
97
+ stderr: string;
98
+ }
99
+ export interface VisualExecError extends Error {
100
+ output?: ExecOutput;
101
+ code?: number;
102
+ exitCode?: number;
103
+ signal?: string | null;
104
+ cwd?: string;
105
+ command?: string;
106
+ duration?: number;
107
+ lastLines?: string[];
108
+ stdout?: string;
109
+ stderr?: string;
110
+ context?: ExecErrorContext;
111
+ }
112
+ interface ChildProcess {
113
+ stdout: NodeJS.ReadableStream;
114
+ stderr: NodeJS.ReadableStream;
115
+ promise: Promise<ExecOutput>;
116
+ child?: {
117
+ kill(signal?: string): boolean;
118
+ pid?: number;
119
+ };
120
+ }
121
+ /** JSON Lines parser - parses each line as JSON */
122
+ export declare function jsonLinesParser(line: string): unknown | null;
123
+ /** Key-value parser for key=value or key: value patterns */
124
+ export declare function keyValueParser(line: string): Record<string, string> | null;
125
+ export declare const parsers: {
126
+ jsonLines: typeof jsonLinesParser;
127
+ keyValue: typeof keyValueParser;
128
+ };
129
+ export declare class VisualExec {
130
+ private _title;
131
+ private _logLabel;
132
+ private _outputLabel;
133
+ private _command;
134
+ private _cwd;
135
+ private _logger;
136
+ private _outputLevel;
137
+ private _spinner;
138
+ private _maxBuffer;
139
+ private _forceStderr;
140
+ private _checkStdoutError;
141
+ private _startTime;
142
+ private _timeout?;
143
+ private _timeoutGrace;
144
+ private _onTimeout?;
145
+ private _onOutput?;
146
+ private _onComplete?;
147
+ private _outputFile?;
148
+ private _outputFileOptions;
149
+ private _signal?;
150
+ private _progress?;
151
+ private _onProgress?;
152
+ private _matchers?;
153
+ private _stdoutKey?;
154
+ private _stderrKey?;
155
+ private _updateStdout?;
156
+ private _updateStderr?;
157
+ private _child?;
158
+ private _rawChild?;
159
+ private _outputStream?;
160
+ private _aborted;
161
+ private _onStdoutData?;
162
+ private _onStderrData?;
163
+ constructor(options: VisualExecOptions);
164
+ private _makeTitle;
165
+ private _createOutputFileStream;
166
+ private _writeToOutputFile;
167
+ private _extractProgress;
168
+ private _updateDigest;
169
+ private _createDataHandler;
170
+ /** Abort/kill the running command */
171
+ abort(signal?: string): void;
172
+ /** Alias for abort() */
173
+ kill(signal?: string): void;
174
+ show(child: ChildProcess): Promise<ExecOutput | unknown>;
175
+ logResult(err: VisualExecError | null, output?: ExecOutput): void;
176
+ checkForErrors(text: string): RegExpMatchArray | null;
177
+ /**
178
+ * Log the final output. Can be overridden to customize output handling.
179
+ * Set to a no-op function to suppress output logging.
180
+ */
181
+ logFinalOutput(err: VisualExecError | null, output: ExecOutput): void;
182
+ execute(command?: string): Promise<ExecOutput | unknown>;
183
+ }
184
+ export default VisualExec;
@@ -0,0 +1,456 @@
1
+ import xsh from "xsh";
2
+ import chalk from "chalk";
3
+ import * as fs from "fs";
4
+ import * as path from "path";
5
+ import { getDefaultLogger } from "./get-default-logger.js";
6
+ import VisualLogger from "visual-logger";
7
+ import hasAnsi from "has-ansi";
8
+ import stripAnsi from "strip-ansi";
9
+ // Set xsh to use native Promise
10
+ xsh.Promise = Promise;
11
+ const ONE_MB = 1024 * 1024;
12
+ const TEN_MB = 10 * ONE_MB;
13
+ const DEFAULT_TIMEOUT_GRACE = 5000;
14
+ const DEFAULT_LAST_LINES = 10;
15
+ const MAX_OUTPUT_IN_ERROR = 50000;
16
+ function createTimeoutError(context, elapsed) {
17
+ const err = new Error(`Command timed out after ${elapsed}ms: ${context.command}`);
18
+ err.name = "TimeoutError";
19
+ err.context = { ...context, duration: elapsed };
20
+ return err;
21
+ }
22
+ function createAbortError(context) {
23
+ const err = new Error(`Command aborted: ${context.command}`);
24
+ err.name = "AbortError";
25
+ err.context = context;
26
+ return err;
27
+ }
28
+ function lastLines(text, n) {
29
+ if (!text)
30
+ return [];
31
+ const lines = text.split("\n").filter(Boolean);
32
+ return lines.slice(-n);
33
+ }
34
+ function enhanceError(err, context) {
35
+ err.exitCode = context.exitCode;
36
+ err.signal = context.signal;
37
+ err.cwd = context.cwd;
38
+ err.command = context.command;
39
+ err.duration = context.duration;
40
+ err.lastLines = context.lastLines;
41
+ err.context = context;
42
+ err.stdout = context.stdout.length > MAX_OUTPUT_IN_ERROR
43
+ ? context.stdout.slice(-MAX_OUTPUT_IN_ERROR)
44
+ : context.stdout;
45
+ err.stderr = context.stderr.length > MAX_OUTPUT_IN_ERROR
46
+ ? context.stderr.slice(-MAX_OUTPUT_IN_ERROR)
47
+ : context.stderr;
48
+ return err;
49
+ }
50
+ /** JSON Lines parser - parses each line as JSON */
51
+ export function jsonLinesParser(line) {
52
+ const trimmed = line.trim();
53
+ if (!trimmed || trimmed.startsWith("//"))
54
+ return null;
55
+ try {
56
+ return JSON.parse(trimmed);
57
+ }
58
+ catch (_a) {
59
+ return null;
60
+ }
61
+ }
62
+ /** Key-value parser for key=value or key: value patterns */
63
+ export function keyValueParser(line) {
64
+ const match = line.match(/^([^=:]+)[=:]\s*(.*)$/);
65
+ if (!match)
66
+ return null;
67
+ return { [match[1].trim()]: match[2].trim() };
68
+ }
69
+ export const parsers = {
70
+ jsonLines: jsonLinesParser,
71
+ keyValue: keyValueParser
72
+ };
73
+ export class VisualExec {
74
+ constructor(options) {
75
+ this._aborted = false;
76
+ const { command, cwd = process.cwd(), visualLogger, spinner = VisualLogger.spinners[1], displayTitle, logLabel, outputLabel, outputLevel = "verbose", maxBuffer = TEN_MB, forceStderr = true, checkStdoutError = true, timeout, timeoutGrace = DEFAULT_TIMEOUT_GRACE, onTimeout, onOutput, onComplete, outputFile, outputFileOptions = {}, signal, progress, onProgress, matchers } = options;
77
+ this._title = displayTitle || this._makeTitle(command);
78
+ this._logLabel = logLabel || this._title;
79
+ this._outputLabel = outputLabel || this._title;
80
+ this._command = command;
81
+ this._cwd = cwd || process.cwd();
82
+ this._logger = visualLogger || getDefaultLogger();
83
+ this._outputLevel = outputLevel;
84
+ this._spinner = spinner;
85
+ this._maxBuffer = maxBuffer;
86
+ this._forceStderr = forceStderr;
87
+ this._checkStdoutError =
88
+ checkStdoutError === true
89
+ ? /error|warn|fatal|unhandled|reject|exception|failure|fail|failed/i
90
+ : checkStdoutError;
91
+ this._startTime = Date.now();
92
+ this._timeout = timeout;
93
+ this._timeoutGrace = timeoutGrace;
94
+ this._onTimeout = onTimeout;
95
+ this._onOutput = onOutput;
96
+ this._onComplete = onComplete;
97
+ this._outputFile = outputFile;
98
+ this._outputFileOptions = {
99
+ append: false,
100
+ includeStderr: true,
101
+ timestamps: false,
102
+ ...outputFileOptions
103
+ };
104
+ this._signal = signal;
105
+ this._progress = progress;
106
+ this._onProgress = onProgress;
107
+ this._matchers = matchers;
108
+ }
109
+ _makeTitle(command) {
110
+ if (typeof command !== "string") {
111
+ command = "user command";
112
+ }
113
+ return `Running ${command}`;
114
+ }
115
+ _createOutputFileStream() {
116
+ if (typeof this._outputFile !== "string")
117
+ return undefined;
118
+ const flags = this._outputFileOptions.append ? "a" : "w";
119
+ const dir = path.dirname(this._outputFile);
120
+ if (!fs.existsSync(dir)) {
121
+ fs.mkdirSync(dir, { recursive: true });
122
+ }
123
+ return fs.createWriteStream(this._outputFile, { flags });
124
+ }
125
+ _writeToOutputFile(data, stream) {
126
+ var _a;
127
+ const streamOpt = this._outputFileOptions.includeStderr;
128
+ if (stream === "stderr" && !streamOpt)
129
+ return;
130
+ const line = this._outputFileOptions.timestamps
131
+ ? `[${new Date().toISOString()}] ${data}`
132
+ : data;
133
+ const out = (_a = this._outputStream) !== null && _a !== void 0 ? _a : (typeof this._outputFile === "object" ? this._outputFile : null);
134
+ if (out && typeof out.write === "function") {
135
+ out.write(line);
136
+ }
137
+ }
138
+ _extractProgress(line) {
139
+ const cfg = this._progress;
140
+ if (!cfg || !this._onProgress)
141
+ return;
142
+ let progress = null;
143
+ if (cfg.extract) {
144
+ progress = cfg.extract(line);
145
+ }
146
+ else if (cfg.pattern) {
147
+ const m = line.match(cfg.pattern);
148
+ if (m && m.groups) {
149
+ progress = {
150
+ current: m.groups.current ? parseInt(m.groups.current, 10) : undefined,
151
+ total: m.groups.total ? parseInt(m.groups.total, 10) : undefined,
152
+ percent: m.groups.percent ? parseInt(m.groups.percent, 10) : undefined
153
+ };
154
+ }
155
+ }
156
+ if (progress)
157
+ this._onProgress(progress);
158
+ }
159
+ _updateDigest(item, buf) {
160
+ const newBuf = item.buf + buf;
161
+ const lines = newBuf
162
+ .split("\n")
163
+ .map(x => x && x.trim())
164
+ .filter(x => x);
165
+ const stripLines = lines.map(x => (hasAnsi(x) ? stripAnsi(x) : x));
166
+ let length = 0;
167
+ let ix = stripLines.length - 1;
168
+ for (; ix >= 0; ix--) {
169
+ const line = stripLines[ix];
170
+ if (line) {
171
+ if (length + line.length < 100) {
172
+ length += line.length;
173
+ }
174
+ else {
175
+ break;
176
+ }
177
+ }
178
+ }
179
+ let msgs = ix >= 0 ? lines.slice(ix + 1) : lines;
180
+ if (msgs.length === 0) {
181
+ item.buf = lines[lines.length - 1] || "";
182
+ if (item.buf.length > 120) {
183
+ item.buf = stripLines[stripLines.length - 1].substr(0, 100);
184
+ }
185
+ msgs = [item.buf];
186
+ }
187
+ else {
188
+ item.buf = msgs.join("\n");
189
+ }
190
+ if (buf.endsWith("\n")) {
191
+ item.buf += "\n";
192
+ }
193
+ this._logger.updateItem(item.name, {
194
+ msg: msgs.join(chalk.blue.inverse("\\n")),
195
+ _save: false,
196
+ _render: false
197
+ });
198
+ }
199
+ _createDataHandler(stream) {
200
+ return (buf) => {
201
+ var _a;
202
+ const data = typeof buf === "string" ? buf : buf.toString();
203
+ if (this._onOutput)
204
+ this._onOutput(data, stream);
205
+ if (this._outputFile || this._outputStream)
206
+ this._writeToOutputFile(data, stream);
207
+ for (const line of data.split("\n")) {
208
+ if (line) {
209
+ this._extractProgress(line);
210
+ for (const m of (_a = this._matchers) !== null && _a !== void 0 ? _a : []) {
211
+ const match = line.match(m.pattern);
212
+ if (match)
213
+ m.onMatch(match);
214
+ }
215
+ }
216
+ }
217
+ };
218
+ }
219
+ /** Abort/kill the running command */
220
+ abort(signal = "SIGTERM") {
221
+ var _a;
222
+ this._aborted = true;
223
+ if ((_a = this._rawChild) === null || _a === void 0 ? void 0 : _a.pid) {
224
+ this._rawChild.kill(signal);
225
+ }
226
+ }
227
+ /** Alias for abort() */
228
+ kill(signal) {
229
+ this.abort(signal);
230
+ }
231
+ show(child) {
232
+ this._stdoutKey = Symbol("visual-exec-stdout");
233
+ this._stderrKey = Symbol("visual-exec-stderr");
234
+ this._rawChild = child.child;
235
+ this._logger.addItem({
236
+ name: this._stdoutKey,
237
+ color: "green",
238
+ display: `=== ${this._title}\nstdout`,
239
+ spinner: this._spinner
240
+ });
241
+ this._logger.addItem({
242
+ name: this._stderrKey,
243
+ color: "red",
244
+ display: `stderr`
245
+ });
246
+ const stdoutDigest = { name: this._stdoutKey, buf: "" };
247
+ const stderrDigest = { name: this._stderrKey, buf: "" };
248
+ this._updateStdout = (buf) => this._updateDigest(stdoutDigest, buf);
249
+ this._updateStderr = (buf) => this._updateDigest(stderrDigest, buf);
250
+ this._onStdoutData = (buf) => {
251
+ const data = typeof buf === "string" ? buf : buf.toString();
252
+ this._updateStdout(data);
253
+ this._createDataHandler("stdout")(buf);
254
+ };
255
+ this._onStderrData = (buf) => {
256
+ const data = typeof buf === "string" ? buf : buf.toString();
257
+ this._updateStderr(data);
258
+ this._createDataHandler("stderr")(buf);
259
+ };
260
+ child.stdout.on("data", this._onStdoutData);
261
+ child.stderr.on("data", this._onStderrData);
262
+ this._child = child;
263
+ if (typeof this._outputFile === "string") {
264
+ this._outputStream = this._createOutputFileStream();
265
+ }
266
+ else if (this._outputFile) {
267
+ this._outputStream = undefined;
268
+ }
269
+ let timeoutId;
270
+ const startTime = Date.now();
271
+ let execPromise = child.promise
272
+ .catch((err) => {
273
+ var _a, _b, _c, _d;
274
+ const output = (_a = err.output) !== null && _a !== void 0 ? _a : { stdout: "", stderr: "" };
275
+ const exitCode = (_c = (_b = err.exitCode) !== null && _b !== void 0 ? _b : err.code) !== null && _c !== void 0 ? _c : 1;
276
+ (_d = this._onComplete) === null || _d === void 0 ? void 0 : _d.call(this, output, exitCode);
277
+ this.logResult(err);
278
+ throw err;
279
+ })
280
+ .then((output) => {
281
+ var _a;
282
+ this.logResult(null, output);
283
+ const result = (_a = this._onComplete) === null || _a === void 0 ? void 0 : _a.call(this, output, 0);
284
+ return result !== undefined ? result : output;
285
+ });
286
+ if (this._timeout) {
287
+ const timeoutPromise = new Promise((_, reject) => {
288
+ timeoutId = setTimeout(() => {
289
+ var _a, _b, _c, _d;
290
+ if (this._aborted)
291
+ return;
292
+ (_a = this._onTimeout) === null || _a === void 0 ? void 0 : _a.call(this);
293
+ if ((_b = this._rawChild) === null || _b === void 0 ? void 0 : _b.pid) {
294
+ this._rawChild.kill("SIGTERM");
295
+ const grace = setTimeout(() => {
296
+ var _a;
297
+ if ((_a = this._rawChild) === null || _a === void 0 ? void 0 : _a.pid)
298
+ this._rawChild.kill("SIGKILL");
299
+ }, this._timeoutGrace);
300
+ (_d = (_c = grace).unref) === null || _d === void 0 ? void 0 : _d.call(_c);
301
+ }
302
+ reject(createTimeoutError({ command: this._command, cwd: this._cwd, exitCode: -1, signal: "SIGTERM" }, this._timeout));
303
+ }, this._timeout);
304
+ });
305
+ execPromise = Promise.race([execPromise, timeoutPromise]);
306
+ }
307
+ const cleanup = () => {
308
+ if (timeoutId)
309
+ clearTimeout(timeoutId);
310
+ const stream = this._outputStream;
311
+ this._outputStream = undefined;
312
+ // Only streams we opened are ours to close - a caller-supplied one stays open.
313
+ if (!(stream === null || stream === void 0 ? void 0 : stream.end)) {
314
+ return undefined;
315
+ }
316
+ // Already gone - a stream that errored destroys itself, and `close` will not fire a
317
+ // second time, so waiting on it here would hang execute() forever.
318
+ if (stream.destroyed || stream.closed) {
319
+ return undefined;
320
+ }
321
+ //
322
+ // `end()` starts the flush, it does not finish it, and `createWriteStream` opens the
323
+ // file asynchronously too. Resolving execute() without waiting meant a caller that
324
+ // awaited it could read a file that was still empty, or not yet created at all - the
325
+ // outputFile test failed with ENOENT under CI load while passing on a quiet machine.
326
+ //
327
+ return new Promise((resolve) => {
328
+ stream.once("close", () => resolve());
329
+ // a stream that errors still has to let execute() settle
330
+ stream.once("error", () => resolve());
331
+ stream.end();
332
+ });
333
+ };
334
+ if (this._signal) {
335
+ const abortPromise = new Promise((_, reject) => {
336
+ const handleAbort = () => {
337
+ this.abort();
338
+ reject(createAbortError({
339
+ command: this._command,
340
+ cwd: this._cwd,
341
+ exitCode: -1,
342
+ signal: "SIGTERM",
343
+ duration: Date.now() - startTime
344
+ }));
345
+ };
346
+ if (this._signal.aborted) {
347
+ handleAbort();
348
+ }
349
+ else {
350
+ this._signal.addEventListener("abort", handleAbort);
351
+ }
352
+ });
353
+ execPromise = Promise.race([execPromise, abortPromise]);
354
+ }
355
+ return execPromise.finally(cleanup);
356
+ }
357
+ logResult(err, output) {
358
+ const child = this._child;
359
+ this._logger.removeItem(this._stdoutKey);
360
+ this._logger.removeItem(this._stderrKey);
361
+ if (this._onStdoutData)
362
+ child.stdout.removeListener("data", this._onStdoutData);
363
+ if (this._onStderrData)
364
+ child.stderr.removeListener("data", this._onStderrData);
365
+ if (err) {
366
+ this._logger.error(`${chalk.red("Failed")} ${this._logLabel} - ${chalk.red(err.message)}`);
367
+ output = err.output;
368
+ }
369
+ else {
370
+ const time = ((Date.now() - this._startTime) / 1000).toFixed(2);
371
+ const dispTime = `${chalk.magenta(time)}secs`;
372
+ this._logger.info(`Done ${this._logLabel} ${dispTime} ${chalk.green("exit code 0")}`);
373
+ }
374
+ this.logFinalOutput(err, output);
375
+ }
376
+ checkForErrors(text) {
377
+ if (!this._checkStdoutError || !text)
378
+ return null;
379
+ if (this._checkStdoutError instanceof RegExp) {
380
+ return text.match(this._checkStdoutError);
381
+ }
382
+ return null;
383
+ }
384
+ /**
385
+ * Log the final output. Can be overridden to customize output handling.
386
+ * Set to a no-op function to suppress output logging.
387
+ */
388
+ logFinalOutput(err, output) {
389
+ const level = err || (this._forceStderr && (output === null || output === void 0 ? void 0 : output.stderr)) || this.checkForErrors((output === null || output === void 0 ? void 0 : output.stdout) || "")
390
+ ? "error"
391
+ : this._outputLevel;
392
+ if (!output || (!output.stdout && !output.stderr)) {
393
+ this._logger[level](`${chalk.green("No output")} from ${this._outputLabel}`);
394
+ return;
395
+ }
396
+ const colorize = (t) => t.replace(/ERR!/g, chalk.red("ERR!"));
397
+ const logs = [chalk.green(">>>"), `Start of output from ${this._outputLabel} ===`];
398
+ if (output.stdout) {
399
+ logs.push(`\n${colorize(output.stdout)}`);
400
+ }
401
+ if (output.stderr) {
402
+ logs.push(chalk.red("\n=== stderr ===\n") + colorize(output.stderr));
403
+ }
404
+ logs.push(chalk.blue("\n<<<"), `End of output from ${this._outputLabel} ---`);
405
+ this._logger.prefix(false)[level](...logs);
406
+ }
407
+ execute(command) {
408
+ this._startTime = Date.now();
409
+ this._aborted = false;
410
+ const cmd = command || this._command;
411
+ const result = xsh.exec({
412
+ silent: true,
413
+ cwd: this._cwd,
414
+ env: Object.assign({}, process.env, { PWD: this._cwd }),
415
+ maxBuffer: this._maxBuffer
416
+ }, cmd);
417
+ const child = {
418
+ stdout: result.stdout,
419
+ stderr: result.stderr,
420
+ promise: result.promise,
421
+ child: result.child
422
+ };
423
+ const duration = () => Date.now() - this._startTime;
424
+ const baseContext = (output) => {
425
+ var _a, _b, _c, _d;
426
+ return ({
427
+ command: cmd,
428
+ cwd: this._cwd,
429
+ duration: duration(),
430
+ stdout: (_a = output === null || output === void 0 ? void 0 : output.stdout) !== null && _a !== void 0 ? _a : "",
431
+ stderr: (_b = output === null || output === void 0 ? void 0 : output.stderr) !== null && _b !== void 0 ? _b : "",
432
+ lastLines: lastLines([...((_c = output === null || output === void 0 ? void 0 : output.stdout) !== null && _c !== void 0 ? _c : "").split("\n"), ...((_d = output === null || output === void 0 ? void 0 : output.stderr) !== null && _d !== void 0 ? _d : "").split("\n")].join("\n"), DEFAULT_LAST_LINES)
433
+ });
434
+ };
435
+ child.promise = child.promise.catch((err) => {
436
+ var _a, _b, _c, _d, _e;
437
+ const output = (_a = err.output) !== null && _a !== void 0 ? _a : { stdout: "", stderr: "" };
438
+ const exitCode = (_b = err.code) !== null && _b !== void 0 ? _b : 1;
439
+ const signal = (_e = (_c = err.signal) !== null && _c !== void 0 ? _c : (((_d = result.child) === null || _d === void 0 ? void 0 : _d.killed) ? "SIGTERM" : null)) !== null && _e !== void 0 ? _e : null;
440
+ const context = {
441
+ ...baseContext(output),
442
+ exitCode,
443
+ signal,
444
+ cwd: this._cwd,
445
+ command: cmd,
446
+ duration: duration(),
447
+ lastLines: lastLines([...output.stdout.split("\n"), ...output.stderr.split("\n")].join("\n"), DEFAULT_LAST_LINES),
448
+ stdout: output.stdout,
449
+ stderr: output.stderr
450
+ };
451
+ return Promise.reject(enhanceError(err, context));
452
+ });
453
+ return this.show(child);
454
+ }
455
+ }
456
+ export default VisualExec;
package/package.json CHANGED
@@ -1,34 +1,56 @@
1
1
  {
2
2
  "name": "visual-exec",
3
- "version": "0.1.14",
4
- "description": "Visual shell exec",
5
- "main": "lib/visual-exec.js",
6
- "scripts": {},
3
+ "version": "1.0.0",
4
+ "homepage": "https://github.com/jchip/fynjs/tree/main/packages/visual-exec",
5
+ "description": "Visual shell exec with spinners and progress display",
6
+ "type": "module",
7
+ "types": "./dist/index.d.ts",
8
+ "main": "./dist/index.js",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "default": "./dist/index.js"
13
+ },
14
+ "./package.json": "./package.json"
15
+ },
16
+ "engines": {
17
+ "node": ">=22.12.0"
18
+ },
19
+ "scripts": {
20
+ "build": "rm -rf dist && tsc -p tsconfig.json",
21
+ "test": "vitest run",
22
+ "ci:check": "tsc --noEmit -p tsconfig.json && npm test",
23
+ "test:watch": "vitest",
24
+ "prepublishOnly": "xrun --serial build test",
25
+ "postpack": "publish-util-postpack"
26
+ },
27
+ "bugs": {
28
+ "url": "https://github.com/jchip/fynjs/issues"
29
+ },
7
30
  "repository": {
8
31
  "type": "git",
9
- "url": "https://github.com/jchip/visual-exec.git"
32
+ "url": "git+https://github.com/jchip/fynjs.git",
33
+ "directory": "packages/visual-exec"
10
34
  },
11
35
  "keywords": [
12
36
  "visual",
13
37
  "shell",
14
- "exec"
38
+ "exec",
39
+ "spinner",
40
+ "progress"
15
41
  ],
16
42
  "files": [
17
- "lib"
43
+ "dist"
18
44
  ],
19
45
  "author": "Joel Chen <joel123@gmail.com>",
20
46
  "license": "Apache-2.0",
21
47
  "dependencies": {
22
- "chalk": "^4.1.2",
23
- "ci-info": "^3.2.0",
24
- "has-ansi": "^4.0.1",
25
- "strip-ansi": "^6.0.0",
26
- "visual-logger": "^1.1.3",
27
- "xsh": "^0.4.5"
48
+ "chalk": "^6.0.0",
49
+ "ci-info": "^4.4.0",
50
+ "has-ansi": "^6.0.2",
51
+ "strip-ansi": "^7.2.0",
52
+ "visual-logger": "^2.0.0",
53
+ "xsh": "^1.0.0"
28
54
  },
29
- "prettier": {
30
- "printWidth": 100,
31
- "trailingComma": "none",
32
- "arrowParens": "avoid"
33
- }
55
+ "sideEffects": false
34
56
  }
@@ -1,19 +0,0 @@
1
- "use strict";
2
-
3
- const VisualLogger = require("visual-logger");
4
- const { isCI } = require("ci-info");
5
-
6
- let logger;
7
- const getLogger = () => {
8
- if (!logger) {
9
- logger = new VisualLogger();
10
-
11
- if (isCI) {
12
- logger.info("visual-exec: CI env detected");
13
- logger.setItemType("none");
14
- }
15
- }
16
- return logger;
17
- };
18
-
19
- module.exports = getLogger;
@@ -1,213 +0,0 @@
1
- "use strict";
2
-
3
- /* eslint-disable no-magic-numbers,no-eval,prefer-template */
4
-
5
- const xsh = require("xsh");
6
- const chalk = require("chalk");
7
- const getDefaultLogger = require("./get-default-logger");
8
- const VisualLogger = require("visual-logger");
9
- const hasAnsi = require("has-ansi");
10
- const stripAnsi = require("strip-ansi");
11
-
12
- xsh.Promise = Promise;
13
-
14
- const ONE_MB = 1024 * 1024;
15
- const TEN_MB = 10 * ONE_MB;
16
-
17
- class VisualExec {
18
- constructor({
19
- command,
20
- cwd = process.cwd(),
21
- visualLogger,
22
- spinner = VisualLogger.spinners[1],
23
- displayTitle = undefined,
24
- logLabel = undefined,
25
- outputLabel = undefined,
26
- outputLevel = "verbose",
27
- maxBuffer = TEN_MB,
28
- forceStderr = true,
29
- checkStdoutError = true
30
- }) {
31
- this._title = displayTitle || this._makeTitle(command);
32
- this._logLabel = logLabel || this._title;
33
- this._outputLabel = outputLabel || this._title;
34
- this._command = command;
35
- this._cwd = cwd || process.cwd();
36
- this._logger = visualLogger || getDefaultLogger();
37
- this._outputLevel = outputLevel;
38
- this._spinner = spinner;
39
- this._maxBuffer = maxBuffer;
40
- this._forceStderr = forceStderr;
41
- this._checkStdoutError =
42
- checkStdoutError === true
43
- ? /error|warn|fatal|unhandled|reject|exception|failure|fail|failed/i
44
- : checkStdoutError;
45
- this._startTime = Date.now();
46
- }
47
-
48
- _makeTitle(command) {
49
- if (typeof command !== "string") {
50
- command = "user command";
51
- }
52
-
53
- return `Running ${command}`;
54
- }
55
-
56
- /* eslint-disable max-statements */
57
- _updateDigest(item, buf) {
58
- const newBuf = item.buf + buf;
59
-
60
- const lines = newBuf
61
- .split("\n")
62
- .map(x => x && x.trim())
63
- .filter(x => x);
64
-
65
- const stripLines = lines.map(x => (hasAnsi(x) ? stripAnsi(x) : x));
66
-
67
- let length = 0;
68
-
69
- // gather as many lines from the end as possible that will fit in a single line, using
70
- // strings without ansi code to get real length
71
- let ix = stripLines.length - 1;
72
- for (; ix >= 0; ix--) {
73
- const line = stripLines[ix];
74
- if (line) {
75
- if (length + line.length < 100) {
76
- length += line.length;
77
- } else {
78
- break;
79
- }
80
- }
81
- }
82
-
83
- let msgs = ix >= 0 ? lines.slice(ix + 1) : lines;
84
- if (msgs.length === 0) {
85
- // even the last line is too long, save it, and display last line as is
86
- item.buf = lines[lines.length - 1] || "";
87
- // set some reasonable limit to avoid visual digest getting clobberred
88
- if (item.buf.length > 120) {
89
- // truncte stripped line only to avoid breaking ansi code
90
- item.buf = stripLines[stripLines.length - 1].substr(0, 100);
91
- }
92
- msgs = [item.buf];
93
- } else {
94
- item.buf = msgs.join("\n");
95
- }
96
-
97
- if (buf.endsWith("\n")) {
98
- item.buf += "\n";
99
- }
100
-
101
- this._logger.updateItem(item.name, {
102
- msg: msgs.join(chalk.blue.inverse("\\n")),
103
- _save: false,
104
- _render: false
105
- });
106
- }
107
-
108
- show(child) {
109
- this._stdoutKey = Symbol("visual-exec-stdout");
110
- this._stderrKey = Symbol("visual-exec-stderr");
111
-
112
- this._logger.addItem({
113
- name: this._stdoutKey,
114
- color: "green",
115
- display: `=== ${this._title}\nstdout`,
116
- spinner: this._spinner
117
- });
118
-
119
- this._logger.addItem({
120
- name: this._stderrKey,
121
- color: "red",
122
- display: `stderr`
123
- });
124
-
125
- const stdoutDigest = { name: this._stdoutKey, buf: "" };
126
- const stderrDigest = { name: this._stderrKey, buf: "" };
127
- this._updateStdout = buf => this._updateDigest(stdoutDigest, buf);
128
- this._updateStderr = buf => this._updateDigest(stderrDigest, buf);
129
-
130
- child.stdout.on("data", this._updateStdout);
131
- child.stderr.on("data", this._updateStderr);
132
-
133
- this._child = child;
134
-
135
- return child.promise
136
- .catch(err => {
137
- this.logResult(err);
138
- throw err;
139
- })
140
- .then(output => {
141
- this.logResult(null, output);
142
- return output;
143
- });
144
- }
145
-
146
- logResult(err, output) {
147
- const child = this._child;
148
-
149
- this._logger.removeItem(this._stdoutKey);
150
- this._logger.removeItem(this._stderrKey);
151
- child.stdout.removeListener("data", this._updateStdout);
152
- child.stderr.removeListener("data", this._updateStderr);
153
-
154
- if (err) {
155
- this._logger.error(`${chalk.red("Failed")} ${this._logLabel} - ${chalk.red(err.message)}`);
156
- output = err.output;
157
- } else {
158
- const time = ((Date.now() - this._startTime) / 1000).toFixed(2);
159
- const dispTime = `${chalk.magenta(time)}secs`;
160
- this._logger.info(`Done ${this._logLabel} ${dispTime} ${chalk.green("exit code 0")}`);
161
- }
162
-
163
- this.logFinalOutput(err, output);
164
- }
165
-
166
- checkForErrors(text) {
167
- return this._checkStdoutError && text && text.match(this._checkStdoutError);
168
- }
169
-
170
- logFinalOutput(err, output) {
171
- const level =
172
- err || (this._forceStderr && output.stderr) || this.checkForErrors(output.stdout)
173
- ? "error"
174
- : this._outputLevel;
175
-
176
- if (!output || (!output.stdout && !output.stderr)) {
177
- this._logger[level](`${chalk.green("No output")} from ${this._outputLabel}`);
178
- return;
179
- }
180
-
181
- const colorize = t => t.replace(/ERR!/g, chalk.red("ERR!"));
182
-
183
- const logs = [chalk.green(">>>"), `Start of output from ${this._outputLabel} ===`];
184
-
185
- if (output.stdout) {
186
- logs.push(`\n${colorize(output.stdout)}`);
187
- }
188
-
189
- if (output.stderr) {
190
- logs.push(chalk.red("\n=== stderr ===\n") + colorize(output.stderr));
191
- }
192
-
193
- logs.push(chalk.blue("\n<<<"), `End of output from ${this._outputLabel} ---`);
194
- this._logger.prefix(false)[level](...logs);
195
- }
196
-
197
- execute(command) {
198
- this._startTime = Date.now();
199
- const child = xsh.exec(
200
- {
201
- silent: true,
202
- cwd: this._cwd,
203
- env: Object.assign({}, process.env, { PWD: this._cwd }),
204
- maxBuffer: this._maxBuffer
205
- },
206
- command || this._command
207
- );
208
-
209
- return this.show(child);
210
- }
211
- }
212
-
213
- module.exports = VisualExec;