@goldstack/utils-sh 0.5.0 → 0.5.1

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/README.md CHANGED
@@ -1,6 +1,5 @@
1
- # Goldstack Bash Utilities
2
-
3
- This library provides various convenience methods for working with files and folders as well as interacting with the shell.
4
-
5
- It was originally a wrapper of [shelljs](https://www.npmjs.com/package/shelljs), but since [shelljs has poor support for bundling due to a custom way to load required scripts](https://github.com/shelljs/shelljs/issues/962#issuecomment-583136465) all shelljs commands have been replaced with other libraries or vanilla Node.js file operations.
6
-
1
+ # Goldstack Bash Utilities
2
+
3
+ This library provides various convenience methods for working with files and folders as well as interacting with the shell.
4
+
5
+ It was originally a wrapper of [shelljs](https://www.npmjs.com/package/shelljs), but since [shelljs has poor support for bundling due to a custom way to load required scripts](https://github.com/shelljs/shelljs/issues/962#issuecomment-583136465) all shelljs commands have been replaced with other libraries or vanilla Node.js file operations.
@@ -1,43 +1,43 @@
1
- import { sync as globSync } from 'glob';
2
- export interface ExecParams {
3
- silent?: boolean;
4
- }
5
- export declare const copy: (source: string[] | string, dest: string) => Promise<void>;
6
- export declare const assertFileExists: (filePath: string) => void;
7
- export declare const assertDirectoryExists: (directoryPath: string, errorMesssage?: string) => void;
8
- export declare const cp: (options: string, source: string | string[], dest: string) => void;
9
- /**
10
- * Safer delete in Windows environment, since automatic retires are attempted when there is a temporary error.
11
- */
12
- export declare const rmSafe: (...files: string[]) => Promise<void>;
13
- export declare const rm: (options: string, ...files: string[]) => void;
14
- export declare const mkdir: (options: string, ...dirs: string[]) => void;
15
- export declare const zip: (params: {
16
- directory: string;
17
- target: string;
18
- mode?: number;
19
- }) => Promise<void>;
20
- /**
21
- * Unzips a zip file into directly into a directory.
22
- */
23
- export declare const unzip: (params: {
24
- file: string;
25
- targetDirectory: string;
26
- }) => Promise<void>;
27
- export declare const tempDir: () => string;
28
- declare const exec: (cmd: string, params?: ExecParams) => string;
29
- declare const execSafe: (file: string, args: string[], params?: ExecParams) => string;
30
- export declare const execAsync: (cmd: string, params?: ExecParams) => Promise<string>;
31
- declare const read: (path: string) => string;
32
- declare const tryRead: (path: string) => string | undefined;
33
- declare const readToType: <T>(path: string) => T | undefined;
34
- /**
35
- * Writes to a file - if contents have not changed, do not change the file.
36
- */
37
- declare const write: (content: string, path: string) => void;
38
- declare const pwd: () => string;
39
- declare const cd: (newdir: string) => void;
40
- declare const commandExists: (command: string) => boolean;
41
- declare const changeExtension: (file: string, extension: string) => string;
42
- export { exec, execSafe, pwd, read, write, cd, globSync, commandExists, readToType, tryRead, changeExtension, };
1
+ import { sync as globSync } from 'glob';
2
+ export interface ExecParams {
3
+ silent?: boolean;
4
+ }
5
+ export declare const copy: (source: string[] | string, dest: string) => Promise<void>;
6
+ export declare const assertFileExists: (filePath: string) => void;
7
+ export declare const assertDirectoryExists: (directoryPath: string, errorMesssage?: string) => void;
8
+ export declare const cp: (options: string, source: string | string[], dest: string) => void;
9
+ /**
10
+ * Safer delete in Windows environment, since automatic retires are attempted when there is a temporary error.
11
+ */
12
+ export declare const rmSafe: (...files: string[]) => Promise<void>;
13
+ export declare const rm: (options: string, ...files: string[]) => void;
14
+ export declare const mkdir: (options: string, ...dirs: string[]) => void;
15
+ export declare const zip: (params: {
16
+ directory: string;
17
+ target: string;
18
+ mode?: number;
19
+ }) => Promise<void>;
20
+ /**
21
+ * Unzips a zip file into directly into a directory.
22
+ */
23
+ export declare const unzip: (params: {
24
+ file: string;
25
+ targetDirectory: string;
26
+ }) => Promise<void>;
27
+ export declare const tempDir: () => string;
28
+ declare const exec: (cmd: string, params?: ExecParams) => string;
29
+ declare const execSafe: (file: string, args: string[], params?: ExecParams) => string;
30
+ export declare const execAsync: (cmd: string, params?: ExecParams) => Promise<string>;
31
+ declare const read: (path: string) => string;
32
+ declare const tryRead: (path: string) => string | undefined;
33
+ declare const readToType: <T>(path: string) => T | undefined;
34
+ /**
35
+ * Writes to a file - if contents have not changed, do not change the file.
36
+ */
37
+ declare const write: (content: string, path: string) => void;
38
+ declare const pwd: () => string;
39
+ declare const cd: (newdir: string) => void;
40
+ declare const commandExists: (command: string) => boolean;
41
+ declare const changeExtension: (file: string, extension: string) => string;
42
+ export { exec, execSafe, pwd, read, write, cd, globSync, commandExists, readToType, tryRead, changeExtension, };
43
43
  //# sourceMappingURL=utilsSh.d.ts.map
@@ -1,299 +1,299 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.changeExtension = exports.tryRead = exports.readToType = exports.commandExists = exports.globSync = exports.cd = exports.write = exports.read = exports.pwd = exports.execSafe = exports.exec = exports.execAsync = exports.tempDir = exports.unzip = exports.zip = exports.mkdir = exports.rm = exports.rmSafe = exports.cp = exports.assertDirectoryExists = exports.assertFileExists = exports.copy = void 0;
7
- const child_process_1 = require("child_process");
8
- const fs_1 = __importDefault(require("fs"));
9
- const ncp_1 = __importDefault(require("ncp"));
10
- const fs_extra_1 = __importDefault(require("fs-extra"));
11
- const path_1 = __importDefault(require("path"));
12
- const rimraf_1 = __importDefault(require("rimraf"));
13
- const archiver_1 = __importDefault(require("archiver"));
14
- const extract_zip_1 = __importDefault(require("extract-zip"));
15
- const which_1 = __importDefault(require("which"));
16
- const glob_1 = require("glob");
17
- Object.defineProperty(exports, "globSync", { enumerable: true, get: function () { return glob_1.sync; } });
18
- const copy = async (source, dest) => {
19
- let sourceArr;
20
- if (Array.isArray(source)) {
21
- sourceArr = source;
22
- }
23
- else {
24
- sourceArr = [source];
25
- }
26
- for (const sourceEl of sourceArr) {
27
- const files = (0, glob_1.sync)(sourceEl);
28
- for (let i = 0; i < files.length; i++) {
29
- const file = files[i];
30
- await new Promise((resolve, reject) => {
31
- let destCorrected;
32
- if (!fs_1.default.lstatSync(file).isDirectory()) {
33
- destCorrected = dest + path_1.default.basename(file);
34
- }
35
- else {
36
- destCorrected = dest;
37
- }
38
- (0, ncp_1.default)(file, destCorrected, { stopOnErr: true }, (err) => {
39
- if (err) {
40
- reject(err);
41
- return;
42
- }
43
- resolve();
44
- });
45
- });
46
- }
47
- }
48
- };
49
- exports.copy = copy;
50
- const assertFileExists = (filePath) => {
51
- if (!fs_1.default.existsSync(filePath)) {
52
- throw new Error(`File '${filePath}' expected to exist but it does not`);
53
- }
54
- if (!fs_1.default.statSync(filePath).isFile()) {
55
- throw new Error(`Expected file at path '${filePath}' but found directory instead.`);
56
- }
57
- };
58
- exports.assertFileExists = assertFileExists;
59
- const assertDirectoryExists = (directoryPath, errorMesssage) => {
60
- if (!fs_1.default.existsSync(directoryPath)) {
61
- throw new Error(`Directory '${directoryPath}' expected to exist but it does not. ${errorMesssage || ''}`);
62
- }
63
- if (!fs_1.default.statSync(directoryPath).isDirectory()) {
64
- throw new Error(`Expected directory at path '${directoryPath}' but found file instead. ${errorMesssage || ''}`);
65
- }
66
- };
67
- exports.assertDirectoryExists = assertDirectoryExists;
68
- const assertDir = (filePath) => {
69
- const dirname = path_1.default.dirname(filePath);
70
- (0, exports.mkdir)('-p', dirname);
71
- };
72
- const cpSingle = (singleSource, dest, copySyncOptions) => {
73
- const isDestDirectory = fs_1.default.existsSync(dest) && fs_1.default.lstatSync(dest).isDirectory();
74
- const isSourceDirectory = fs_1.default.lstatSync(singleSource).isDirectory();
75
- if (isDestDirectory) {
76
- assertDir(dest);
77
- }
78
- // see https://github.com/jprichardson/node-fs-extra/blob/HEAD/docs/copy-sync.md
79
- // https://github.com/jprichardson/node-fs-extra/issues/323
80
- if (isDestDirectory && !isSourceDirectory) {
81
- fs_extra_1.default.copySync(singleSource, `${dest}/${path_1.default.basename(singleSource)}`, copySyncOptions);
82
- return;
83
- }
84
- if (isDestDirectory && isSourceDirectory) {
85
- // copy directory as sub-directory
86
- fs_extra_1.default.copySync(singleSource, `${dest}/${path_1.default.basename(singleSource)}`, copySyncOptions);
87
- return;
88
- }
89
- fs_extra_1.default.copySync(singleSource, dest, copySyncOptions);
90
- };
91
- const cp = (options, source, dest) => {
92
- if (options !== '-f' && options !== '-rf' && options !== '') {
93
- throw new Error('Unknown option for cp ' + options);
94
- }
95
- const copySyncOptions = {
96
- overwrite: options.indexOf('f') !== -1,
97
- };
98
- if (Array.isArray(source)) {
99
- source.forEach((singleSource) => {
100
- cpSingle(singleSource, dest, copySyncOptions);
101
- });
102
- }
103
- else {
104
- assertDir(dest);
105
- cpSingle(source, dest, copySyncOptions);
106
- }
107
- };
108
- exports.cp = cp;
109
- /**
110
- * Safer delete in Windows environment, since automatic retires are attempted when there is a temporary error.
111
- */
112
- const rmSafe = async (...files) => {
113
- for (const file of files) {
114
- await new Promise((resolve, reject) => {
115
- (0, rimraf_1.default)(file, {
116
- maxBusyTries: 10,
117
- }, (e) => {
118
- if (e) {
119
- reject(e);
120
- return;
121
- }
122
- resolve();
123
- });
124
- });
125
- }
126
- };
127
- exports.rmSafe = rmSafe;
128
- const rm = (options, ...files) => {
129
- for (const file of files) {
130
- rimraf_1.default.sync(file); // sh.rm(options, files);
131
- // if (!res || res.code !== 0) {
132
- // sh.echo(res.stdout);
133
- // sh.echo(res.stderr);
134
- // throw new Error(`Cannot remove ${file}`);
135
- // }
136
- }
137
- };
138
- exports.rm = rm;
139
- const mkdir = (options, ...dirs) => {
140
- dirs.forEach((dir) => {
141
- fs_1.default.mkdirSync(dir, {
142
- recursive: options.indexOf('-p') >= 0,
143
- });
144
- });
145
- };
146
- exports.mkdir = mkdir;
147
- const zip = async (params) => {
148
- await new Promise((resolve, reject) => {
149
- const output = fs_1.default.createWriteStream(params.target);
150
- const archive = (0, archiver_1.default)('zip', {
151
- zlib: { level: 9 },
152
- });
153
- archive.on('warning', function (err) {
154
- console.warn(err.message);
155
- });
156
- output.on('finish', () => {
157
- resolve();
158
- });
159
- output.on('error', reject);
160
- // pipe archive data to the file
161
- archive.pipe(output);
162
- archive.directory(params.directory, false, {
163
- mode: params.mode,
164
- });
165
- archive.finalize();
166
- });
167
- };
168
- exports.zip = zip;
169
- /**
170
- * Unzips a zip file into directly into a directory.
171
- */
172
- const unzip = async (params) => {
173
- await (0, extract_zip_1.default)(params.file, {
174
- dir: path_1.default.resolve(params.targetDirectory),
175
- });
176
- };
177
- exports.unzip = unzip;
178
- const tempDir = () => {
179
- if (process.env.GOLDSTACK_WORKDIR) {
180
- return process.env.GOLDSTACK_WORKDIR;
181
- }
182
- return './goldstackLocal/';
183
- };
184
- exports.tempDir = tempDir;
185
- const exec = (cmd, params) => {
186
- try {
187
- const res = (0, child_process_1.execSync)(cmd);
188
- if (!(params === null || params === void 0 ? void 0 : params.silent)) {
189
- console.log(res.toString());
190
- }
191
- return res.toString();
192
- }
193
- catch (e) {
194
- console.error('Command failed:', cmd);
195
- if (e.stderr) {
196
- console.error(e.stderr.toString());
197
- }
198
- if (e.stdout) {
199
- console.log(e.stdout.toString());
200
- }
201
- throw e;
202
- }
203
- };
204
- exports.exec = exec;
205
- const execSafe = (file, args, params) => {
206
- try {
207
- const res = (0, child_process_1.execFileSync)(file, args);
208
- if (!(params === null || params === void 0 ? void 0 : params.silent)) {
209
- console.log(res.toString());
210
- }
211
- return res.toString();
212
- }
213
- catch (e) {
214
- console.error('Command failed:', file, args);
215
- if (e.stderr) {
216
- console.error(e.stderr.toString());
217
- }
218
- if (e.stdout) {
219
- console.log(e.stdout.toString());
220
- }
221
- throw e;
222
- }
223
- };
224
- exports.execSafe = execSafe;
225
- const execAsync = async (cmd, params) => {
226
- return new Promise((resolve, reject) => {
227
- (0, child_process_1.exec)(cmd, (err, stdout, stderr) => {
228
- if (!(params === null || params === void 0 ? void 0 : params.silent)) {
229
- console.log(stdout.toString());
230
- }
231
- if (err) {
232
- console.error('Command failed:', cmd);
233
- if (stderr) {
234
- console.error(stderr.toString());
235
- }
236
- reject(err);
237
- return;
238
- }
239
- resolve(stdout.toString());
240
- });
241
- });
242
- };
243
- exports.execAsync = execAsync;
244
- const read = (path) => {
245
- const buffer = fs_1.default.readFileSync(path, 'utf8');
246
- return buffer.toString();
247
- };
248
- exports.read = read;
249
- const tryRead = (path) => {
250
- let buffer;
251
- try {
252
- buffer = fs_1.default.readFileSync(path, 'utf8');
253
- }
254
- catch (ex) { }
255
- return buffer === null || buffer === void 0 ? void 0 : buffer.toString();
256
- };
257
- exports.tryRead = tryRead;
258
- const readToType = (path) => {
259
- const stringObject = tryRead(path);
260
- let result = undefined;
261
- if (stringObject)
262
- result = JSON.parse(stringObject);
263
- return result;
264
- };
265
- exports.readToType = readToType;
266
- /**
267
- * Writes to a file - if contents have not changed, do not change the file.
268
- */
269
- const write = (content, path) => {
270
- if (fs_1.default.existsSync(path)) {
271
- const previousContent = fs_1.default.readFileSync(path, 'utf8');
272
- if (content === previousContent) {
273
- return;
274
- }
275
- }
276
- fs_1.default.writeFileSync(path, content, {
277
- encoding: 'utf8',
278
- });
279
- };
280
- exports.write = write;
281
- const pwd = () => process.cwd();
282
- exports.pwd = pwd;
283
- const cd = (newdir) => {
284
- process.chdir(newdir);
285
- };
286
- exports.cd = cd;
287
- const commandExists = (command) => {
288
- const res = which_1.default.sync(command, { nothrow: true });
289
- return res !== null;
290
- };
291
- exports.commandExists = commandExists;
292
- // https://stackoverflow.com/a/57371333
293
- const changeExtension = (file, extension) => {
294
- // extension should include the dot, for example '.html'
295
- const basename = path_1.default.basename(file, path_1.default.extname(file));
296
- return path_1.default.join(path_1.default.dirname(file), basename + extension);
297
- };
298
- exports.changeExtension = changeExtension;
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.changeExtension = exports.tryRead = exports.readToType = exports.commandExists = exports.globSync = exports.cd = exports.write = exports.read = exports.pwd = exports.execSafe = exports.exec = exports.execAsync = exports.tempDir = exports.unzip = exports.zip = exports.mkdir = exports.rm = exports.rmSafe = exports.cp = exports.assertDirectoryExists = exports.assertFileExists = exports.copy = void 0;
7
+ const child_process_1 = require("child_process");
8
+ const fs_1 = __importDefault(require("fs"));
9
+ const ncp_1 = __importDefault(require("ncp"));
10
+ const fs_extra_1 = __importDefault(require("fs-extra"));
11
+ const path_1 = __importDefault(require("path"));
12
+ const rimraf_1 = __importDefault(require("rimraf"));
13
+ const archiver_1 = __importDefault(require("archiver"));
14
+ const extract_zip_1 = __importDefault(require("extract-zip"));
15
+ const which_1 = __importDefault(require("which"));
16
+ const glob_1 = require("glob");
17
+ Object.defineProperty(exports, "globSync", { enumerable: true, get: function () { return glob_1.sync; } });
18
+ const copy = async (source, dest) => {
19
+ let sourceArr;
20
+ if (Array.isArray(source)) {
21
+ sourceArr = source;
22
+ }
23
+ else {
24
+ sourceArr = [source];
25
+ }
26
+ for (const sourceEl of sourceArr) {
27
+ const files = (0, glob_1.sync)(sourceEl);
28
+ for (let i = 0; i < files.length; i++) {
29
+ const file = files[i];
30
+ await new Promise((resolve, reject) => {
31
+ let destCorrected;
32
+ if (!fs_1.default.lstatSync(file).isDirectory()) {
33
+ destCorrected = dest + path_1.default.basename(file);
34
+ }
35
+ else {
36
+ destCorrected = dest;
37
+ }
38
+ (0, ncp_1.default)(file, destCorrected, { stopOnErr: true }, (err) => {
39
+ if (err) {
40
+ reject(err);
41
+ return;
42
+ }
43
+ resolve();
44
+ });
45
+ });
46
+ }
47
+ }
48
+ };
49
+ exports.copy = copy;
50
+ const assertFileExists = (filePath) => {
51
+ if (!fs_1.default.existsSync(filePath)) {
52
+ throw new Error(`File '${filePath}' expected to exist but it does not`);
53
+ }
54
+ if (!fs_1.default.statSync(filePath).isFile()) {
55
+ throw new Error(`Expected file at path '${filePath}' but found directory instead.`);
56
+ }
57
+ };
58
+ exports.assertFileExists = assertFileExists;
59
+ const assertDirectoryExists = (directoryPath, errorMesssage) => {
60
+ if (!fs_1.default.existsSync(directoryPath)) {
61
+ throw new Error(`Directory '${directoryPath}' expected to exist but it does not. ${errorMesssage || ''}`);
62
+ }
63
+ if (!fs_1.default.statSync(directoryPath).isDirectory()) {
64
+ throw new Error(`Expected directory at path '${directoryPath}' but found file instead. ${errorMesssage || ''}`);
65
+ }
66
+ };
67
+ exports.assertDirectoryExists = assertDirectoryExists;
68
+ const assertDir = (filePath) => {
69
+ const dirname = path_1.default.dirname(filePath);
70
+ (0, exports.mkdir)('-p', dirname);
71
+ };
72
+ const cpSingle = (singleSource, dest, copySyncOptions) => {
73
+ const isDestDirectory = fs_1.default.existsSync(dest) && fs_1.default.lstatSync(dest).isDirectory();
74
+ const isSourceDirectory = fs_1.default.lstatSync(singleSource).isDirectory();
75
+ if (isDestDirectory) {
76
+ assertDir(dest);
77
+ }
78
+ // see https://github.com/jprichardson/node-fs-extra/blob/HEAD/docs/copy-sync.md
79
+ // https://github.com/jprichardson/node-fs-extra/issues/323
80
+ if (isDestDirectory && !isSourceDirectory) {
81
+ fs_extra_1.default.copySync(singleSource, `${dest}/${path_1.default.basename(singleSource)}`, copySyncOptions);
82
+ return;
83
+ }
84
+ if (isDestDirectory && isSourceDirectory) {
85
+ // copy directory as sub-directory
86
+ fs_extra_1.default.copySync(singleSource, `${dest}/${path_1.default.basename(singleSource)}`, copySyncOptions);
87
+ return;
88
+ }
89
+ fs_extra_1.default.copySync(singleSource, dest, copySyncOptions);
90
+ };
91
+ const cp = (options, source, dest) => {
92
+ if (options !== '-f' && options !== '-rf' && options !== '') {
93
+ throw new Error('Unknown option for cp ' + options);
94
+ }
95
+ const copySyncOptions = {
96
+ overwrite: options.indexOf('f') !== -1,
97
+ };
98
+ if (Array.isArray(source)) {
99
+ source.forEach((singleSource) => {
100
+ cpSingle(singleSource, dest, copySyncOptions);
101
+ });
102
+ }
103
+ else {
104
+ assertDir(dest);
105
+ cpSingle(source, dest, copySyncOptions);
106
+ }
107
+ };
108
+ exports.cp = cp;
109
+ /**
110
+ * Safer delete in Windows environment, since automatic retires are attempted when there is a temporary error.
111
+ */
112
+ const rmSafe = async (...files) => {
113
+ for (const file of files) {
114
+ await new Promise((resolve, reject) => {
115
+ (0, rimraf_1.default)(file, {
116
+ maxBusyTries: 10,
117
+ }, (e) => {
118
+ if (e) {
119
+ reject(e);
120
+ return;
121
+ }
122
+ resolve();
123
+ });
124
+ });
125
+ }
126
+ };
127
+ exports.rmSafe = rmSafe;
128
+ const rm = (options, ...files) => {
129
+ for (const file of files) {
130
+ rimraf_1.default.sync(file); // sh.rm(options, files);
131
+ // if (!res || res.code !== 0) {
132
+ // sh.echo(res.stdout);
133
+ // sh.echo(res.stderr);
134
+ // throw new Error(`Cannot remove ${file}`);
135
+ // }
136
+ }
137
+ };
138
+ exports.rm = rm;
139
+ const mkdir = (options, ...dirs) => {
140
+ dirs.forEach((dir) => {
141
+ fs_1.default.mkdirSync(dir, {
142
+ recursive: options.indexOf('-p') >= 0,
143
+ });
144
+ });
145
+ };
146
+ exports.mkdir = mkdir;
147
+ const zip = async (params) => {
148
+ await new Promise((resolve, reject) => {
149
+ const output = fs_1.default.createWriteStream(params.target);
150
+ const archive = (0, archiver_1.default)('zip', {
151
+ zlib: { level: 9 },
152
+ });
153
+ archive.on('warning', function (err) {
154
+ console.warn(err.message);
155
+ });
156
+ output.on('finish', () => {
157
+ resolve();
158
+ });
159
+ output.on('error', reject);
160
+ // pipe archive data to the file
161
+ archive.pipe(output);
162
+ archive.directory(params.directory, false, {
163
+ mode: params.mode,
164
+ });
165
+ archive.finalize();
166
+ });
167
+ };
168
+ exports.zip = zip;
169
+ /**
170
+ * Unzips a zip file into directly into a directory.
171
+ */
172
+ const unzip = async (params) => {
173
+ await (0, extract_zip_1.default)(params.file, {
174
+ dir: path_1.default.resolve(params.targetDirectory),
175
+ });
176
+ };
177
+ exports.unzip = unzip;
178
+ const tempDir = () => {
179
+ if (process.env.GOLDSTACK_WORKDIR) {
180
+ return process.env.GOLDSTACK_WORKDIR;
181
+ }
182
+ return './goldstackLocal/';
183
+ };
184
+ exports.tempDir = tempDir;
185
+ const exec = (cmd, params) => {
186
+ try {
187
+ const res = (0, child_process_1.execSync)(cmd);
188
+ if (!(params === null || params === void 0 ? void 0 : params.silent)) {
189
+ console.log(res.toString());
190
+ }
191
+ return res.toString();
192
+ }
193
+ catch (e) {
194
+ console.error('Command failed:', cmd);
195
+ if (e.stderr) {
196
+ console.error(e.stderr.toString());
197
+ }
198
+ if (e.stdout) {
199
+ console.log(e.stdout.toString());
200
+ }
201
+ throw e;
202
+ }
203
+ };
204
+ exports.exec = exec;
205
+ const execSafe = (file, args, params) => {
206
+ try {
207
+ const res = (0, child_process_1.execFileSync)(file, args);
208
+ if (!(params === null || params === void 0 ? void 0 : params.silent)) {
209
+ console.log(res.toString());
210
+ }
211
+ return res.toString();
212
+ }
213
+ catch (e) {
214
+ console.error('Command failed:', file, args);
215
+ if (e.stderr) {
216
+ console.error(e.stderr.toString());
217
+ }
218
+ if (e.stdout) {
219
+ console.log(e.stdout.toString());
220
+ }
221
+ throw e;
222
+ }
223
+ };
224
+ exports.execSafe = execSafe;
225
+ const execAsync = async (cmd, params) => {
226
+ return new Promise((resolve, reject) => {
227
+ (0, child_process_1.exec)(cmd, (err, stdout, stderr) => {
228
+ if (!(params === null || params === void 0 ? void 0 : params.silent)) {
229
+ console.log(stdout.toString());
230
+ }
231
+ if (err) {
232
+ console.error('Command failed:', cmd);
233
+ if (stderr) {
234
+ console.error(stderr.toString());
235
+ }
236
+ reject(err);
237
+ return;
238
+ }
239
+ resolve(stdout.toString());
240
+ });
241
+ });
242
+ };
243
+ exports.execAsync = execAsync;
244
+ const read = (path) => {
245
+ const buffer = fs_1.default.readFileSync(path, 'utf8');
246
+ return buffer.toString();
247
+ };
248
+ exports.read = read;
249
+ const tryRead = (path) => {
250
+ let buffer;
251
+ try {
252
+ buffer = fs_1.default.readFileSync(path, 'utf8');
253
+ }
254
+ catch (ex) { }
255
+ return buffer === null || buffer === void 0 ? void 0 : buffer.toString();
256
+ };
257
+ exports.tryRead = tryRead;
258
+ const readToType = (path) => {
259
+ const stringObject = tryRead(path);
260
+ let result = undefined;
261
+ if (stringObject)
262
+ result = JSON.parse(stringObject);
263
+ return result;
264
+ };
265
+ exports.readToType = readToType;
266
+ /**
267
+ * Writes to a file - if contents have not changed, do not change the file.
268
+ */
269
+ const write = (content, path) => {
270
+ if (fs_1.default.existsSync(path)) {
271
+ const previousContent = fs_1.default.readFileSync(path, 'utf8');
272
+ if (content === previousContent) {
273
+ return;
274
+ }
275
+ }
276
+ fs_1.default.writeFileSync(path, content, {
277
+ encoding: 'utf8',
278
+ });
279
+ };
280
+ exports.write = write;
281
+ const pwd = () => process.cwd();
282
+ exports.pwd = pwd;
283
+ const cd = (newdir) => {
284
+ process.chdir(newdir);
285
+ };
286
+ exports.cd = cd;
287
+ const commandExists = (command) => {
288
+ const res = which_1.default.sync(command, { nothrow: true });
289
+ return res !== null;
290
+ };
291
+ exports.commandExists = commandExists;
292
+ // https://stackoverflow.com/a/57371333
293
+ const changeExtension = (file, extension) => {
294
+ // extension should include the dot, for example '.html'
295
+ const basename = path_1.default.basename(file, path_1.default.extname(file));
296
+ return path_1.default.join(path_1.default.dirname(file), basename + extension);
297
+ };
298
+ exports.changeExtension = changeExtension;
299
299
  //# sourceMappingURL=utilsSh.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@goldstack/utils-sh",
3
- "version": "0.5.0",
3
+ "version": "0.5.1",
4
4
  "description": "Utilities for working with files and folders in a bash like manner",
5
5
  "keywords": [
6
6
  "goldstack",
@@ -36,7 +36,7 @@
36
36
  "version:apply:force": "yarn version $@ && yarn version apply"
37
37
  },
38
38
  "dependencies": {
39
- "@goldstack/utils-log": "0.3.0",
39
+ "@goldstack/utils-log": "0.3.1",
40
40
  "archiver": "^5.3.1",
41
41
  "extract-zip": "^2.0.1",
42
42
  "fs-extra": "^10.0.0",
@@ -46,7 +46,7 @@
46
46
  "which": "^2.0.2"
47
47
  },
48
48
  "devDependencies": {
49
- "@goldstack/utils-git": "0.2.0",
49
+ "@goldstack/utils-git": "0.2.1",
50
50
  "@types/archiver": "^3.1.0",
51
51
  "@types/command-exists": "^1",
52
52
  "@types/fs-extra": "^9.0.13",