xsh 0.4.5 → 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 2017 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,5 +1,4 @@
1
- [![NPM version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url]
2
- [![Dependency Status][daviddm-image]][daviddm-url] [![devDependency Status][daviddm-dev-image]][daviddm-dev-url]
1
+ [![NPM version][npm-image]][npm-url]
3
2
 
4
3
  # xsh
5
4
 
@@ -13,12 +12,24 @@ npm install xsh --save-dev
13
12
 
14
13
  ## Usage
15
14
 
15
+ xsh >= 1.0.0 is an ES module written in TypeScript, requiring node >= 22.12.
16
+
17
+ ```js
18
+ import xsh from "xsh";
19
+
20
+ xsh.exec("echo hello");
21
+ ```
22
+
23
+ CJS consumers can still `require` it (node >= 22.12 `require(esm)`):
24
+
16
25
  ```js
17
26
  const xsh = require("xsh");
18
27
 
19
28
  xsh.exec("echo hello");
20
29
  ```
21
30
 
31
+ The shell commands under `xsh.$` come from [shelljs](https://www.npmjs.com/package/shelljs).
32
+
22
33
  ## API
23
34
 
24
35
  ### `Promise`
@@ -26,7 +37,9 @@ xsh.exec("echo hello");
26
37
  You can set a custom `Promise` with:
27
38
 
28
39
  ```js
29
- xsh.Promise = require("bluebird");
40
+ import AveAzul from "aveazul";
41
+
42
+ xsh.Promise = AveAzul;
30
43
  ```
31
44
 
32
45
  Or set to the native `Promise` with:
@@ -161,18 +174,12 @@ xsh.$.cd("/tmp");
161
174
 
162
175
  [shelljs]: https://github.com/shelljs/shelljs
163
176
 
164
- [travis-image]: https://travis-ci.org/jchip/xsh.svg?branch=master
165
177
 
166
- [travis-url]: https://travis-ci.org/jchip/xsh
167
178
 
168
179
  [npm-image]: https://badge.fury.io/js/xsh.svg
169
180
 
170
181
  [npm-url]: https://npmjs.org/package/xsh
171
182
 
172
- [daviddm-image]: https://david-dm.org/jchip/xsh/status.svg
173
183
 
174
- [daviddm-url]: https://david-dm.org/jchip/xsh
175
184
 
176
- [daviddm-dev-image]: https://david-dm.org/jchip/xsh/dev-status.svg
177
185
 
178
- [daviddm-dev-url]: https://david-dm.org/jchip/xsh?type=dev
@@ -0,0 +1,39 @@
1
+ /** an env container like `process.env` */
2
+ export type EnvContainer = Record<string, string | undefined>;
3
+ /**
4
+ * Find the key for the PATH variable in `env` - case insensitive fallback for
5
+ * platforms (Windows) where it's not exactly `PATH`.
6
+ */
7
+ export declare function findEnvKey(env: EnvContainer, key?: string): string | undefined;
8
+ export declare const envKey: string;
9
+ /**
10
+ * Add `p` to the front of PATH in `env`, removing any existing occurrences.
11
+ *
12
+ * @param p path to add
13
+ * @param env env container, a PATH string, or undefined for `process.env`
14
+ * @returns the updated PATH string
15
+ */
16
+ export declare function addToFront(p: string | null | undefined, env?: EnvContainer | string): string;
17
+ /**
18
+ * Add `p` to the end of PATH in `env`, removing any existing occurrences.
19
+ *
20
+ * @param p path to add
21
+ * @param env env container, a PATH string, or undefined for `process.env`
22
+ * @returns the updated PATH string
23
+ */
24
+ export declare function addToEnd(p?: string | null, env?: EnvContainer | string): string;
25
+ /**
26
+ * Add `p` to the end of PATH in `env` only if it's not already in there.
27
+ *
28
+ * @param p path to add
29
+ * @param env env container, a PATH string, or undefined for `process.env`
30
+ * @returns the updated PATH string
31
+ */
32
+ export declare function add(p?: string | null, env?: EnvContainer | string): string;
33
+ export declare const envPath: {
34
+ addToFront: typeof addToFront;
35
+ addToEnd: typeof addToEnd;
36
+ add: typeof add;
37
+ envKey: string;
38
+ findEnvKey: typeof findEnvKey;
39
+ };
@@ -0,0 +1,89 @@
1
+ import Path from "node:path";
2
+ const pathDelim = Path.delimiter;
3
+ const defaultEnvKey = process.platform === "win32" ? "Path" : "PATH";
4
+ /**
5
+ * Find the key for the PATH variable in `env` - case insensitive fallback for
6
+ * platforms (Windows) where it's not exactly `PATH`.
7
+ */
8
+ export function findEnvKey(env, key) {
9
+ if (!key || !Object.prototype.hasOwnProperty.call(env, key)) {
10
+ for (const x of Object.keys(env)) {
11
+ if (x.toLowerCase() === "path") {
12
+ key = x;
13
+ break;
14
+ }
15
+ }
16
+ }
17
+ return key;
18
+ }
19
+ export const envKey = findEnvKey(process.env, defaultEnvKey);
20
+ function check(env) {
21
+ // allow calls like this: envPath.add("addition_path", "existing_path");
22
+ if (typeof env === "string") {
23
+ env = { [envKey]: env };
24
+ }
25
+ else if (!env) {
26
+ env = process.env;
27
+ }
28
+ return env;
29
+ }
30
+ /**
31
+ * Add `p` to the front of PATH in `env`, removing any existing occurrences.
32
+ *
33
+ * @param p path to add
34
+ * @param env env container, a PATH string, or undefined for `process.env`
35
+ * @returns the updated PATH string
36
+ */
37
+ export function addToFront(p, env) {
38
+ env = check(env);
39
+ let update = env[envKey] || "";
40
+ if (typeof p === "string" && p) {
41
+ update = update.trim();
42
+ const paths = update.split(pathDelim).filter(x => x && x !== p);
43
+ paths.unshift(p);
44
+ update = paths.join(pathDelim);
45
+ }
46
+ env[envKey] = update;
47
+ return update;
48
+ }
49
+ /**
50
+ * Add `p` to the end of PATH in `env`, removing any existing occurrences.
51
+ *
52
+ * @param p path to add
53
+ * @param env env container, a PATH string, or undefined for `process.env`
54
+ * @returns the updated PATH string
55
+ */
56
+ export function addToEnd(p, env) {
57
+ env = check(env);
58
+ let update = env[envKey] || "";
59
+ if (typeof p === "string" && p) {
60
+ update = update.trim();
61
+ const paths = update.split(pathDelim).filter(x => x && x !== p);
62
+ paths.push(p);
63
+ update = paths.join(pathDelim);
64
+ }
65
+ env[envKey] = update;
66
+ return update;
67
+ }
68
+ /**
69
+ * Add `p` to the end of PATH in `env` only if it's not already in there.
70
+ *
71
+ * @param p path to add
72
+ * @param env env container, a PATH string, or undefined for `process.env`
73
+ * @returns the updated PATH string
74
+ */
75
+ export function add(p, env) {
76
+ env = check(env);
77
+ let update = env[envKey] || "";
78
+ if (typeof p === "string" && p) {
79
+ update = update.trim();
80
+ const paths = update.split(pathDelim).filter(x => x);
81
+ if (paths.indexOf(p) < 0) {
82
+ paths.push(p);
83
+ update = paths.join(pathDelim);
84
+ }
85
+ }
86
+ env[envKey] = update;
87
+ return update;
88
+ }
89
+ export const envPath = { addToFront, addToEnd, add, envKey, findEnvKey };
package/dist/env.d.ts ADDED
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Get an environment variable
3
+ *
4
+ * @param name env variable name
5
+ * @param valWhenUndef value to return if the variable is not defined
6
+ */
7
+ export declare function get(name: string, valWhenUndef?: string): string | undefined;
8
+ /**
9
+ * Get an environment variable as a boolean. `"true"`, `"1"`, `"yes"`, `"on"`
10
+ * (case insensitive) are `true`, anything else is `false`.
11
+ *
12
+ * @param name env variable name
13
+ * @param valWhenUndef value to return if the variable is not defined - must be
14
+ * a boolean, else `false` is returned
15
+ */
16
+ export declare function getAsBool(name: string, valWhenUndef?: unknown): boolean;
17
+ /**
18
+ * Get an environment variable as an integer.
19
+ *
20
+ * @param name env variable name
21
+ * @param valWhenUndef value to return if the variable is not defined or can't
22
+ * be parsed - must be a number, else `NaN` is returned
23
+ */
24
+ export declare function getAsInt(name: string, valWhenUndef?: unknown): number;
25
+ export declare const env: {
26
+ get: typeof get;
27
+ getAsBool: typeof getAsBool;
28
+ getAsInt: typeof getAsInt;
29
+ };
package/dist/env.js ADDED
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Get an environment variable
3
+ *
4
+ * @param name env variable name
5
+ * @param valWhenUndef value to return if the variable is not defined
6
+ */
7
+ export function get(name, valWhenUndef) {
8
+ const x = process.env[name];
9
+ return x === undefined ? valWhenUndef : x;
10
+ }
11
+ /**
12
+ * Get an environment variable as a boolean. `"true"`, `"1"`, `"yes"`, `"on"`
13
+ * (case insensitive) are `true`, anything else is `false`.
14
+ *
15
+ * @param name env variable name
16
+ * @param valWhenUndef value to return if the variable is not defined - must be
17
+ * a boolean, else `false` is returned
18
+ */
19
+ export function getAsBool(name, valWhenUndef) {
20
+ const x = process.env[name];
21
+ if (x === undefined) {
22
+ if (typeof valWhenUndef === "boolean") {
23
+ return valWhenUndef;
24
+ }
25
+ return false;
26
+ }
27
+ const b = x.toLowerCase();
28
+ return b === "true" || b === "1" || b === "yes" || b === "on";
29
+ }
30
+ /**
31
+ * Get an environment variable as an integer.
32
+ *
33
+ * @param name env variable name
34
+ * @param valWhenUndef value to return if the variable is not defined or can't
35
+ * be parsed - must be a number, else `NaN` is returned
36
+ */
37
+ export function getAsInt(name, valWhenUndef) {
38
+ let n = NaN;
39
+ const x = process.env[name];
40
+ if (x !== undefined) {
41
+ n = +x;
42
+ if (!isNaN(n))
43
+ return n;
44
+ }
45
+ if (typeof valWhenUndef === "number") {
46
+ return valWhenUndef;
47
+ }
48
+ return n;
49
+ }
50
+ export const env = { get, getAsBool, getAsInt };
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Escape a string for literal use inside a RegExp.
3
+ *
4
+ * Paths routinely carry regex metacharacters - a `.` in a dot directory, `+`
5
+ * or parens in a project name, `\` separators on Windows - so interpolating
6
+ * one raw either silently mismatches or throws a SyntaxError.
7
+ */
8
+ export declare const escapeRegExp: (x: string) => string;
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Escape a string for literal use inside a RegExp.
3
+ *
4
+ * Paths routinely carry regex metacharacters - a `.` in a dot directory, `+`
5
+ * or parens in a project name, `\` separators on Windows - so interpolating
6
+ * one raw either silently mismatches or throws a SyntaxError.
7
+ */
8
+ export const escapeRegExp = (x) => x.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&");
package/dist/exec.d.ts ADDED
@@ -0,0 +1,44 @@
1
+ import type { ChildProcess } from "node:child_process";
2
+ export interface ExecOutput {
3
+ stdout: string;
4
+ stderr: string;
5
+ }
6
+ export interface ExecError extends Error {
7
+ output: ExecOutput;
8
+ code: number;
9
+ }
10
+ export type ExecCallback = (err: ExecError | null, output: ExecOutput) => void;
11
+ /**
12
+ * Options passed through to shelljs `exec` (`async: true` is always set).
13
+ * A plain boolean is shorthand for `{ silent: boolean }`.
14
+ */
15
+ export interface ExecOptions {
16
+ silent?: boolean;
17
+ env?: Record<string, string | undefined>;
18
+ cwd?: string;
19
+ [key: string]: unknown;
20
+ }
21
+ /** command fragments: arrays of strings are joined with `" "` */
22
+ export type ExecFragment = string | string[];
23
+ export type ExecArg = ExecFragment | ExecOptions | ExecCallback | boolean;
24
+ /** thenable returned by `exec` when no callback is given */
25
+ export interface ExecResult {
26
+ then: <T = ExecOutput, R = never>(onFulfill?: ((output: ExecOutput) => T | PromiseLike<T>) | null, onReject?: ((err: ExecError) => R | PromiseLike<R>) | null) => Promise<T | R>;
27
+ catch: <R = never>(onReject?: ((err: ExecError) => R | PromiseLike<R>) | null) => Promise<ExecOutput | R>;
28
+ promise: Promise<ExecOutput>;
29
+ child: ChildProcess;
30
+ stdout: ChildProcess["stdout"];
31
+ stderr: ChildProcess["stderr"];
32
+ }
33
+ /**
34
+ * Execute a shell command with shelljs `exec` in async mode.
35
+ *
36
+ * Arguments can be any mix of command fragments (strings / arrays of strings,
37
+ * joined with `" "`), one options object or boolean (silent shorthand) as the
38
+ * first, last, or second to last argument, and a callback as the last argument.
39
+ *
40
+ * Returns the shelljs child process when a callback is given, else an
41
+ * {@link ExecResult} thenable.
42
+ */
43
+ export declare function exec(...args: Array<ExecFragment | ExecOptions | boolean>): ExecResult;
44
+ export declare function exec(...args: [...ExecArg[], ExecCallback]): ChildProcess;
package/dist/exec.js ADDED
@@ -0,0 +1,77 @@
1
+ import shell from "shelljs";
2
+ import assert from "node:assert";
3
+ import { util } from "./util.js";
4
+ export function exec(...args) {
5
+ const error = (cmd, code, output) => {
6
+ const err = new Error(`shell cmd '${cmd}' exit code ${code}`);
7
+ err.output = output;
8
+ err.code = code;
9
+ return err;
10
+ };
11
+ const len = args.length;
12
+ let cb;
13
+ let options;
14
+ const cmdFragments = [];
15
+ for (let i = 0; i < len; i++) {
16
+ const arg = args[i];
17
+ const tof = typeof arg;
18
+ if (tof === "string" || Array.isArray(arg)) {
19
+ cmdFragments.push(arg);
20
+ }
21
+ else if (tof === "function") {
22
+ assert(i + 1 === len, "xsh.exec: callback must be the last argument");
23
+ cb = arg;
24
+ }
25
+ else if (tof === "boolean" || (tof === "object" && arg !== null)) {
26
+ assert(i === 0 || len - i === 1 || len - i === 2, "xsh.exec: options must be the first, last, or second to last argument");
27
+ options = arg;
28
+ }
29
+ else {
30
+ throw new Error("xsh.exec: command fragment must be an array or string");
31
+ }
32
+ }
33
+ //
34
+ // Dispatch on `typeof`, not `constructor.name`: the latter threw a TypeError on `null` and on
35
+ // `Object.create(null)` options, and rejected class-instance options that structurally satisfy
36
+ // ExecOptions - so the declared type accepted arguments the runtime did not.
37
+ //
38
+ if (options === undefined) {
39
+ options = { silent: false };
40
+ }
41
+ else if (typeof options === "boolean") {
42
+ options = { silent: options };
43
+ }
44
+ if (cmdFragments.length < 1) {
45
+ throw new Error("xsh.exec: expects at least one command fragment");
46
+ }
47
+ let s = "";
48
+ const cmd = cmdFragments.reduce((a, x) => {
49
+ if (Array.isArray(x)) {
50
+ x = x.join(" ");
51
+ }
52
+ a = `${a}${s}${x}`;
53
+ s = " ";
54
+ return a;
55
+ }, "");
56
+ const doExec = (xcb) => shell.exec(cmd, Object.assign({ async: true }, options), (code, stdout, stderr) => {
57
+ const output = { stdout, stderr };
58
+ const err = code === 0 ? null : error(cmd, code, output);
59
+ xcb(err, output);
60
+ });
61
+ if (cb) {
62
+ return doExec(cb);
63
+ }
64
+ let child;
65
+ assert(util.Promise, "xsh.exec: No Promise available - see doc on setting one");
66
+ const promise = new util.Promise((resolve, reject) => {
67
+ child = doExec((err, output) => (err ? reject(err) : resolve(output)));
68
+ });
69
+ return {
70
+ then: (a, b) => promise.then(a, b),
71
+ catch: (a) => promise.catch(a),
72
+ promise,
73
+ child,
74
+ stdout: child.stdout,
75
+ stderr: child.stderr
76
+ };
77
+ }
@@ -0,0 +1,26 @@
1
+ import shell from "shelljs";
2
+ import { exec } from "./exec.ts";
3
+ import { env } from "./env.ts";
4
+ import { envPath } from "./env-path.ts";
5
+ import { mkCmd } from "./mkcmd.ts";
6
+ import { pathCwd } from "./path-cwd.ts";
7
+ import { pathCwdNm } from "./path-cwd-nm.ts";
8
+ export type { ExecOutput, ExecError, ExecCallback, ExecOptions, ExecFragment, ExecArg, ExecResult } from "./exec.ts";
9
+ export type { EnvContainer } from "./env-path.ts";
10
+ export interface Xsh {
11
+ exec: typeof exec;
12
+ env: typeof env;
13
+ envPath: typeof envPath;
14
+ mkCmd: typeof mkCmd;
15
+ pathCwd: typeof pathCwd;
16
+ pathCwdNm: typeof pathCwdNm;
17
+ /** the shelljs instance xsh uses */
18
+ $: typeof shell;
19
+ /** Promise implementation used by exec - set to null to restore native Promise */
20
+ Promise: PromiseConstructor;
21
+ }
22
+ declare const xsh: Xsh;
23
+ export { exec, env, envPath, mkCmd, pathCwd, pathCwdNm };
24
+ export declare const $: typeof shell;
25
+ export default xsh;
26
+ export { xsh as "module.exports" };
package/dist/index.js ADDED
@@ -0,0 +1,30 @@
1
+ import shell from "shelljs";
2
+ import { util } from "./util.js";
3
+ import { exec } from "./exec.js";
4
+ import { env } from "./env.js";
5
+ import { envPath } from "./env-path.js";
6
+ import { mkCmd } from "./mkcmd.js";
7
+ import { pathCwd } from "./path-cwd.js";
8
+ import { pathCwdNm } from "./path-cwd-nm.js";
9
+ const xsh = {
10
+ exec,
11
+ env,
12
+ envPath,
13
+ mkCmd,
14
+ pathCwd,
15
+ pathCwdNm,
16
+ $: shell
17
+ };
18
+ Object.defineProperty(xsh, "Promise", {
19
+ set: p => {
20
+ util.Promise = p || Promise;
21
+ },
22
+ get: () => util.Promise
23
+ });
24
+ export { exec, env, envPath, mkCmd, pathCwd, pathCwdNm };
25
+ export const $ = shell;
26
+ export default xsh;
27
+ // make `require("xsh")` in CJS consumers (node >=22.12 require(esm)) return the
28
+ // xsh object itself - same shape as the historical module.exports - instead of
29
+ // the module namespace.
30
+ export { xsh as "module.exports" };
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Make a command string: a single array of strings is joined with `" "`,
3
+ * otherwise all arguments are joined with `" "`.
4
+ */
5
+ export declare function mkCmd(...args: Array<string | string[]>): string;
package/dist/mkcmd.js ADDED
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Make a command string: a single array of strings is joined with `" "`,
3
+ * otherwise all arguments are joined with `" "`.
4
+ */
5
+ export function mkCmd(...args) {
6
+ const a = args[0];
7
+ return Array.isArray(a) ? a.join(" ") : args.join(" ");
8
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Remove occurrences of CWD/node_modules from `p`.
3
+ *
4
+ * @param p path string to process
5
+ * @param flags RegExp flags, ie: `"g"`
6
+ */
7
+ declare function remove(p: string, flags?: string): string;
8
+ /**
9
+ * Replace occurrences of CWD/node_modules in `p` with `str` (default
10
+ * `"CWD/~"`), and any remaining `/node_modules/` with `/~/`.
11
+ *
12
+ * @param p path string to process
13
+ * @param str replacement - non-string means use `"CWD/~"`
14
+ * @param flags RegExp flags, ie: `"g"`
15
+ */
16
+ declare function replace(p: string, str?: string | null | false, flags?: string): string;
17
+ export declare const pathCwdNm: {
18
+ remove: typeof remove;
19
+ replace: typeof replace;
20
+ };
21
+ export {};
@@ -0,0 +1,34 @@
1
+ import Path from "node:path";
2
+ import { pathCwd } from "./path-cwd.js";
3
+ import { escapeRegExp } from "./esc-regex.js";
4
+ const normNm = escapeRegExp(Path.normalize("/node_modules/"));
5
+ const normNmReplacer = Path.normalize("/~/");
6
+ const makeNmRegex = () => escapeRegExp(Path.resolve("node_modules"));
7
+ /**
8
+ * Remove occurrences of CWD/node_modules from `p`.
9
+ *
10
+ * @param p path string to process
11
+ * @param flags RegExp flags, ie: `"g"`
12
+ */
13
+ function remove(p, flags) {
14
+ const nmRegex = new RegExp(makeNmRegex(), flags || "");
15
+ p = p.replace(nmRegex, "");
16
+ return pathCwd.remove(p, flags);
17
+ }
18
+ /**
19
+ * Replace occurrences of CWD/node_modules in `p` with `str` (default
20
+ * `"CWD/~"`), and any remaining `/node_modules/` with `/~/`.
21
+ *
22
+ * @param p path string to process
23
+ * @param str replacement - non-string means use `"CWD/~"`
24
+ * @param flags RegExp flags, ie: `"g"`
25
+ */
26
+ function replace(p, str, flags) {
27
+ if (typeof str !== "string") {
28
+ str = Path.join(`CWD`, `~`);
29
+ }
30
+ const nmRegex = new RegExp(makeNmRegex(), flags || "");
31
+ p = pathCwd.replace(p.replace(nmRegex, str), null, flags);
32
+ return p.replace(new RegExp(normNm, flags), normNmReplacer);
33
+ }
34
+ export const pathCwdNm = { remove, replace };
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Remove occurrences of CWD from `p`.
3
+ *
4
+ * @param p path string to process
5
+ * @param flags RegExp flags, ie: `"g"`
6
+ * @param stripSlash also strip the path separator following CWD
7
+ */
8
+ declare function remove(p: string, flags?: string, stripSlash?: boolean): string;
9
+ /**
10
+ * Replace occurrences of CWD in `p` with `str` (default `"CWD"`).
11
+ *
12
+ * @param p path string to process
13
+ * @param str replacement - non-string means use `"CWD"`
14
+ * @param flags RegExp flags, ie: `"g"`
15
+ */
16
+ declare function replace(p: string, str?: string | null | false, flags?: string): string;
17
+ export declare const pathCwd: {
18
+ remove: typeof remove;
19
+ replace: typeof replace;
20
+ };
21
+ export {};
@@ -0,0 +1,36 @@
1
+ import Path from "node:path";
2
+ import { escapeRegExp } from "./esc-regex.js";
3
+ /**
4
+ * Remove occurrences of CWD from `p`.
5
+ *
6
+ * @param p path string to process
7
+ * @param flags RegExp flags, ie: `"g"`
8
+ * @param stripSlash also strip the path separator following CWD
9
+ */
10
+ function remove(p, flags, stripSlash) {
11
+ const cwd = process.cwd();
12
+ if (stripSlash) {
13
+ const regex = new RegExp(escapeRegExp(Path.join(cwd, Path.sep)), flags);
14
+ p = p.replace(regex, "");
15
+ }
16
+ if (p.indexOf(cwd) >= 0) {
17
+ const regex = new RegExp(escapeRegExp(cwd), flags);
18
+ return p.replace(regex, "");
19
+ }
20
+ return p;
21
+ }
22
+ /**
23
+ * Replace occurrences of CWD in `p` with `str` (default `"CWD"`).
24
+ *
25
+ * @param p path string to process
26
+ * @param str replacement - non-string means use `"CWD"`
27
+ * @param flags RegExp flags, ie: `"g"`
28
+ */
29
+ function replace(p, str, flags) {
30
+ if (typeof str !== "string") {
31
+ str = "CWD";
32
+ }
33
+ const regex = new RegExp(escapeRegExp(process.cwd()), flags);
34
+ return p.replace(regex, str);
35
+ }
36
+ export const pathCwd = { remove, replace };
package/dist/util.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Mutable holder for the Promise implementation xsh uses.
3
+ *
4
+ * Lives in its own module so exec reads the current value at call time,
5
+ * while the setter is exposed as the `Promise` property on the xsh object.
6
+ */
7
+ export declare const util: {
8
+ Promise: PromiseConstructor;
9
+ };
package/dist/util.js ADDED
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Mutable holder for the Promise implementation xsh uses.
3
+ *
4
+ * Lives in its own module so exec reads the current value at call time,
5
+ * while the setter is exposed as the `Promise` property on the xsh object.
6
+ */
7
+ export const util = {
8
+ Promise
9
+ };
package/package.json CHANGED
@@ -1,35 +1,51 @@
1
1
  {
2
2
  "name": "xsh",
3
- "version": "0.4.5",
3
+ "version": "1.0.0",
4
4
  "description": "Some random NodeJS helper functions for shell execution",
5
- "main": "lib/index.js",
5
+ "type": "module",
6
+ "types": "./dist/index.d.ts",
7
+ "main": "./dist/index.js",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "default": "./dist/index.js"
12
+ },
13
+ "./package.json": "./package.json"
14
+ },
15
+ "sideEffects": false,
16
+ "engines": {
17
+ "node": ">=22.12.0"
18
+ },
6
19
  "scripts": {
7
- "test": "mocha test/spec",
8
- "format": "prettier --write --print-width 100 lib/*.js",
9
- "coverage": "nyc --all --reporter=lcov --reporter=text --reporter=text-summary npm test"
20
+ "build": "rm -rf dist && tsc -p tsconfig.json",
21
+ "test": "vitest run",
22
+ "coverage": "vitest run --coverage",
23
+ "ci:check": "tsc --noEmit -p tsconfig.json && vitest run",
24
+ "prepublishOnly": "npm run build",
25
+ "postpack": "publish-util-postpack"
10
26
  },
11
27
  "files": [
12
- "lib"
28
+ "dist"
13
29
  ],
30
+ "bugs": {
31
+ "url": "https://github.com/jchip/fynjs/issues"
32
+ },
14
33
  "repository": {
15
34
  "type": "git",
16
- "url": "https://github.com/jchip/xsh.git"
35
+ "url": "git+https://github.com/jchip/fynjs.git",
36
+ "directory": "packages/xsh"
17
37
  },
18
- "homepage": "https://github.com/jchip/xsh",
19
- "keywords": [],
38
+ "homepage": "https://github.com/jchip/fynjs/tree/main/packages/xsh",
39
+ "keywords": [
40
+ "shell",
41
+ "exec",
42
+ "shelljs",
43
+ "env",
44
+ "PATH"
45
+ ],
20
46
  "author": "Joel Chen <joel123@gmail.com>",
21
47
  "license": "Apache-2.0",
22
48
  "dependencies": {
23
- "shcmd": "^0.8.4"
24
- },
25
- "devDependencies": {
26
- "bluebird": "^3.5.1",
27
- "chai": "^4.0.2",
28
- "mocha": "^3.4.2",
29
- "nyc": "^11.0.2",
30
- "prettier": "^1.19.1"
31
- },
32
- "prettier": {
33
- "printWidth": 100
49
+ "shelljs": "^0.10.0"
34
50
  }
35
51
  }
package/lib/env-path.js DELETED
@@ -1,94 +0,0 @@
1
- "use strict";
2
-
3
- const Path = require("path");
4
- const pathDelim = Path.delimiter;
5
-
6
- /* istanbul ignore next */
7
- const defaultEnvKey = process.platform === "win32" ? "Path" : "PATH";
8
-
9
- function findEnvKey(env, key) {
10
- if (!key || !env.hasOwnProperty(key)) {
11
- for (const x of Object.keys(env)) {
12
- if (x.toLowerCase() === "path") {
13
- key = x;
14
- break;
15
- }
16
- }
17
- }
18
-
19
- return key;
20
- }
21
-
22
- const envKey = findEnvKey(process.env, defaultEnvKey);
23
-
24
- function check(env) {
25
- // allow calls like this: envPath.add("addition_path", "existing_path");
26
- if (typeof env === "string") {
27
- env = { [envKey]: env };
28
- } else if (!env) {
29
- env = process.env;
30
- }
31
-
32
- return env;
33
- }
34
-
35
- function addToFront(p, env) {
36
- env = check(env);
37
-
38
- let update = env[envKey] || "";
39
-
40
- if (typeof p === "string" && p && update.indexOf(p) !== 0) {
41
- update = update.trim();
42
- const paths = update.split(pathDelim).filter(x => x && x !== p);
43
- paths.unshift(p);
44
- update = paths.join(pathDelim);
45
- }
46
-
47
- env[envKey] = update;
48
-
49
- return update;
50
- }
51
-
52
- function addToEnd(p, env) {
53
- env = check(env);
54
-
55
- let update = env[envKey] || "";
56
-
57
- if (typeof p === "string" && p) {
58
- update = update.trim();
59
- const paths = update.split(pathDelim).filter(x => x && x !== p);
60
- paths.push(p);
61
- update = paths.join(pathDelim);
62
- }
63
-
64
- env[envKey] = update;
65
-
66
- return update;
67
- }
68
-
69
- function add(p, env) {
70
- env = check(env);
71
-
72
- let update = env[envKey] || "";
73
-
74
- if (typeof p === "string" && p) {
75
- update = update.trim();
76
- const paths = update.split(pathDelim).filter(x => x);
77
- if (paths.indexOf(p) < 0) {
78
- paths.push(p);
79
- update = paths.join(pathDelim);
80
- }
81
- }
82
-
83
- env[envKey] = update;
84
-
85
- return update;
86
- }
87
-
88
- module.exports = {
89
- addToFront,
90
- addToEnd,
91
- add,
92
- envKey,
93
- findEnvKey
94
- };
package/lib/env.js DELETED
@@ -1,40 +0,0 @@
1
- "use strict";
2
-
3
- const get = (name, valWhenUndef) => {
4
- const x = process.env[name];
5
- return x === undefined ? valWhenUndef : x;
6
- };
7
-
8
- const getAsBool = (name, valWhenUndef) => {
9
- const x = process.env[name];
10
- if (x === undefined) {
11
- if (typeof valWhenUndef === "boolean") {
12
- return valWhenUndef;
13
- }
14
- return false;
15
- }
16
-
17
- const b = x.toLowerCase();
18
- return b === "true" || b === "1" || b === "yes" || b === "on";
19
- };
20
-
21
- const getAsInt = (name, valWhenUndef) => {
22
- let n = NaN;
23
- const x = process.env[name];
24
- if (x !== undefined) {
25
- n = +x;
26
- if (!isNaN(n)) return n;
27
- }
28
-
29
- if (typeof valWhenUndef === "number") {
30
- return valWhenUndef;
31
- }
32
-
33
- return n;
34
- };
35
-
36
- module.exports = {
37
- get: get,
38
- getAsBool,
39
- getAsInt
40
- };
package/lib/esc-bs.js DELETED
@@ -1,6 +0,0 @@
1
- "use strict";
2
-
3
- const Path = require("path");
4
-
5
- /* istanbul ignore next */
6
- module.exports = Path.sep === "\\" ? x => x.replace(/\\/g, "\\\\") : x => x;
package/lib/exec.js DELETED
@@ -1,88 +0,0 @@
1
- "use strict";
2
-
3
- const shell = require("shcmd");
4
- const util = require("./util");
5
- const assert = require("assert");
6
-
7
- function exec() {
8
- const error = (cmd, code, output) => {
9
- const err = new Error(`shell cmd '${cmd}' exit code ${code}`);
10
- err.output = output;
11
- err.code = code;
12
- return err;
13
- };
14
-
15
- const len = arguments.length;
16
-
17
- let cb;
18
- let options;
19
-
20
- const cmdFragments = [];
21
- for (let i = 0; i < len; i++) {
22
- const arg = arguments[i];
23
- const tof = typeof arg;
24
- if (tof === "string" || Array.isArray(arg)) {
25
- cmdFragments.push(arg);
26
- } else if (tof === "function") {
27
- assert(i + 1 === len, "xsh.exec: callback must be the last argument");
28
- cb = arg;
29
- } else if (arg.constructor.name === "Boolean" || arg.constructor.name === "Object") {
30
- assert(
31
- i === 0 || len - i === 1 || len - i === 2,
32
- "xsh.exec: options must be the first, last, or second to last argument"
33
- );
34
- options = arg;
35
- } else {
36
- throw new Error("xsh.exec: command fragment must be an array or string");
37
- }
38
- }
39
-
40
- if (!options) {
41
- options = { silent: false };
42
- } else if (options.constructor.name === "Boolean") {
43
- options = { silent: options };
44
- }
45
-
46
- if (cmdFragments.length < 1) {
47
- throw new Error("xsh.exec: expects at least one command fragment");
48
- }
49
-
50
- let s = "";
51
- const cmd = cmdFragments.reduce((a, x) => {
52
- if (Array.isArray(x)) {
53
- x = x.join(" ");
54
- }
55
- a = `${a}${s}${x}`;
56
- s = " ";
57
- return a;
58
- }, "");
59
-
60
- const doExec = xcb =>
61
- shell.exec(cmd, Object.assign({ async: true }, options), (code, stdout, stderr) => {
62
- const output = { stdout, stderr };
63
- const err = code === 0 ? null : error(cmd, code, output);
64
- xcb(err, output);
65
- });
66
-
67
- if (cb) {
68
- return doExec(cb);
69
- }
70
-
71
- let child;
72
-
73
- assert(util.Promise, "xsh.exec: No Promise available - see doc on setting one");
74
- const promise = new util.Promise((resolve, reject) => {
75
- child = doExec((err, output) => (err ? reject(err) : resolve(output)));
76
- });
77
-
78
- return {
79
- then: (a, b) => promise.then(a, b),
80
- catch: a => promise.catch(a),
81
- promise,
82
- child,
83
- stdout: child.stdout,
84
- stderr: child.stderr
85
- };
86
- }
87
-
88
- module.exports = exec;
package/lib/index.js DELETED
@@ -1,22 +0,0 @@
1
- "use strict";
2
-
3
- const util = require("./util");
4
-
5
- const xsh = {
6
- exec: require("./exec"),
7
- env: require("./env"),
8
- envPath: require("./env-path"),
9
- mkCmd: require("./mkcmd"),
10
- pathCwd: require("./path-cwd"),
11
- pathCwdNm: require("./path-cwd-nm"),
12
- $: require("shcmd")
13
- };
14
-
15
- Object.defineProperty(xsh, "Promise", {
16
- set: p => {
17
- util.Promise = p || Promise;
18
- },
19
- get: () => util.Promise
20
- });
21
-
22
- module.exports = xsh;
package/lib/mkcmd.js DELETED
@@ -1,7 +0,0 @@
1
- "use strict";
2
-
3
- function mkCmd(a) {
4
- return Array.isArray(a) ? a.join(" ") : Array.prototype.slice.call(arguments).join(" ");
5
- }
6
-
7
- module.exports = mkCmd;
@@ -1,25 +0,0 @@
1
- "use strict";
2
-
3
- const pathCwd = require("./path-cwd");
4
- const Path = require("path");
5
- const escBs = require("./esc-bs");
6
- const normNm = escBs(Path.normalize("/node_modules/"));
7
- const normNmReplacer = Path.normalize("/~/");
8
-
9
- const makeNmRegex = () => escBs(Path.resolve("node_modules"));
10
-
11
- module.exports = {
12
- remove: (p, flags) => {
13
- const nmRegex = new RegExp(makeNmRegex(), flags || "");
14
- p = p.replace(nmRegex, "");
15
- return pathCwd.remove(p, flags);
16
- },
17
- replace: (p, str, flags) => {
18
- if (typeof str !== "string") {
19
- str = Path.join(`CWD`, `~`);
20
- }
21
- const nmRegex = new RegExp(makeNmRegex(), flags || "");
22
- p = pathCwd.replace(p.replace(nmRegex, str), null, flags);
23
- return p.replace(new RegExp(normNm, flags), normNmReplacer);
24
- }
25
- };
package/lib/path-cwd.js DELETED
@@ -1,26 +0,0 @@
1
- "use strict";
2
-
3
- const Path = require("path");
4
- const escBs = require("./esc-bs");
5
-
6
- module.exports = {
7
- remove: (p, flags, stripSlash) => {
8
- const cwd = process.cwd();
9
- if (stripSlash) {
10
- const regex = new RegExp(escBs(Path.join(cwd, Path.sep)), flags);
11
- p = p.replace(regex, "");
12
- }
13
- if (p.indexOf(cwd) >= 0) {
14
- const regex = new RegExp(escBs(cwd), flags);
15
- return p.replace(regex, "");
16
- }
17
- return p;
18
- },
19
- replace: (p, str, flags) => {
20
- if (typeof str !== "string") {
21
- str = "CWD";
22
- }
23
- const regex = new RegExp(escBs(process.cwd()), flags);
24
- return p.replace(regex, str);
25
- }
26
- };
package/lib/util.js DELETED
@@ -1,5 +0,0 @@
1
- "use strict";
2
-
3
- module.exports = {
4
- Promise
5
- };