@jdeighan/coffee-utils 14.0.36 → 14.0.38

Sign up to get free protection for your applications and to get access to all the features.
Files changed (3) hide show
  1. package/package.json +4 -4
  2. package/src/fs.coffee +99 -30
  3. package/src/fs.js +121 -40
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@jdeighan/coffee-utils",
3
3
  "type": "module",
4
- "version": "14.0.36",
4
+ "version": "14.0.38",
5
5
  "description": "A set of utility functions for CoffeeScript",
6
6
  "main": "coffee_utils.js",
7
7
  "exports": {
@@ -45,14 +45,14 @@
45
45
  },
46
46
  "homepage": "https://github.com/johndeighan/coffee-utils#readme",
47
47
  "dependencies": {
48
- "@jdeighan/base-utils": "^4.0.22",
48
+ "@jdeighan/base-utils": "^4.0.26",
49
49
  "cross-env": "^7.0.3",
50
50
  "n-readlines": "^1.0.1",
51
51
  "readline-sync": "^1.4.10",
52
- "svelte": "^3.55.1"
52
+ "svelte": "^3.58.0"
53
53
  },
54
54
  "devDependencies": {
55
- "@jdeighan/unit-tester": "^3.0.43",
55
+ "@jdeighan/unit-tester": "^3.0.44",
56
56
  "ava": "^5.2.0"
57
57
  }
58
58
  }
package/src/fs.coffee CHANGED
@@ -1,8 +1,13 @@
1
1
  # fs.coffee
2
2
 
3
+ import os from 'os'
3
4
  import pathlib from 'path'
4
5
  import urllib from 'url'
5
6
  import fs from 'fs'
7
+ import {
8
+ readFile, writeFile, rm,
9
+ } from 'node:fs/promises'
10
+ import {execSync} from 'node:child_process'
6
11
  import readline from 'readline'
7
12
  import NReadLines from 'n-readlines'
8
13
 
@@ -16,6 +21,68 @@ import {LOG, LOGVALUE} from '@jdeighan/base-utils/log'
16
21
  import {dbg, dbgEnter, dbgReturn} from '@jdeighan/base-utils/debug'
17
22
  import {fromTAML} from '@jdeighan/base-utils/taml'
18
23
 
24
+ # ---------------------------------------------------------------------------
25
+
26
+ export mkpath = (lParts...) =>
27
+
28
+ # --- Ignore empty parts
29
+ lNewParts = []
30
+ for part in lParts
31
+ if nonEmpty(part)
32
+ lNewParts.push part
33
+
34
+ newPath = lNewParts.join('/').replaceAll('\\', '/')
35
+ if lMatches = newPath.match(/^([A-Z])\:(.*)$/)
36
+ [_, drive, rest] = lMatches
37
+ return "#{drive.toLowerCase()}:#{rest}"
38
+ else
39
+ return newPath
40
+
41
+ # ---------------------------------------------------------------------------
42
+
43
+ export mkdir = (dirpath) =>
44
+
45
+ try
46
+ fs.mkdirSync dirpath
47
+ catch err
48
+ if (err.code == 'EEXIST')
49
+ console.log 'Directory exists. Please choose another name'
50
+ else
51
+ console.log err
52
+ process.exit 1
53
+ return
54
+
55
+ # ---------------------------------------------------------------------------
56
+
57
+ export rmdir = (dirpath) =>
58
+
59
+ await rm dirpath, {recursive: true}
60
+ return
61
+
62
+ # ---------------------------------------------------------------------------
63
+
64
+ export rmfile = (filepath) =>
65
+
66
+ await rm filepath
67
+ return
68
+
69
+ # --------------------------------------------------------------------------
70
+
71
+ export execCmd = (cmdLine) =>
72
+
73
+ execSync cmdLine, {}, (error, stdout, stderr) =>
74
+ if (error)
75
+ LOG "ERROR in #{cmdLine}: #{error.code}"
76
+ process.exit 1
77
+ return stdout
78
+
79
+ # ---------------------------------------------------------------------------
80
+
81
+ export cloneRepo = (user, repo, dir) =>
82
+
83
+ git_repo = "https://github.com/#{user}/#{repo}.git"
84
+ return execCmd "git clone #{git_repo} #{dir}"
85
+
19
86
  # ---------------------------------------------------------------------------
20
87
  # mydir() - pass argument import.meta.url and it will return
21
88
  # the directory your file is in
@@ -29,6 +96,12 @@ export mydir = (url) =>
29
96
 
30
97
  # ---------------------------------------------------------------------------
31
98
 
99
+ export homeDir = () =>
100
+
101
+ return mkpath(os.homedir())
102
+
103
+ # ---------------------------------------------------------------------------
104
+
32
105
  export projRoot = (url) =>
33
106
 
34
107
  dir = mydir(url)
@@ -108,23 +181,6 @@ export fileExt = (path) =>
108
181
 
109
182
  # ---------------------------------------------------------------------------
110
183
 
111
- export mkpath = (lParts...) =>
112
-
113
- # --- Ignore empty parts
114
- lNewParts = []
115
- for part in lParts
116
- if nonEmpty(part)
117
- lNewParts.push part
118
-
119
- newPath = lNewParts.join('/').replace(/\\/g, '/')
120
- if lMatches = newPath.match(/^([A-Z])\:(.*)$/)
121
- [_, drive, rest] = lMatches
122
- return "#{drive.toLowerCase()}:#{rest}"
123
- else
124
- return newPath
125
-
126
- # ---------------------------------------------------------------------------
127
-
128
184
  export getFullPath = (filepath) =>
129
185
 
130
186
  return mkpath(pathlib.resolve(filepath))
@@ -230,10 +286,11 @@ export forEachSetOfBlocks = (filepath, func,
230
286
  return
231
287
 
232
288
  # ---------------------------------------------------------------------------
233
- # slurp - read an entire file into a string
289
+ # slurp - read a file into a string
234
290
 
235
- export slurp = (filepath, maxLines=undef) =>
291
+ export slurp = (filepath, hOptions={}) =>
236
292
 
293
+ {maxLines, format} = getOptions(hOptions)
237
294
  if defined(maxLines)
238
295
  lLines = []
239
296
  forEachLineInFile filepath, (line, nLines) ->
@@ -243,20 +300,33 @@ export slurp = (filepath, maxLines=undef) =>
243
300
  else
244
301
  filepath = filepath.replace(/\//g, "\\")
245
302
  contents = fs.readFileSync(filepath, 'utf8').toString()
246
- return contents
303
+ switch format
304
+ when 'TAML'
305
+ return fromTAML(contents)
306
+ when 'JSON'
307
+ return JSON.parse(contents)
308
+ else
309
+ assert notdefined(format), "Unknown format: #{format}"
310
+ return contents
247
311
 
248
312
  # ---------------------------------------------------------------------------
249
313
  # barf - write a string to a file
250
314
 
251
- export barf = (filepath, contents) =>
315
+ export barf = (filepath, contents='', hOptions={}) =>
252
316
 
253
- if isEmpty(contents)
254
- return
255
- if isArray(contents)
256
- contents = toBlock(contents)
257
- else if ! isString(contents)
258
- croak "barf(): Invalid contents"
259
- contents = rtrim(contents) + "\n"
317
+ {format} = getOptions(hOptions)
318
+ switch format
319
+ when 'TAML'
320
+ contents = toTAML(contents)
321
+ when 'JSON'
322
+ contents = JSON.stringify(contents, null, 3)
323
+ else
324
+ assert notdefined(format), "Unknown format: #{format}"
325
+ if isArray(contents)
326
+ contents = toBlock(contents)
327
+ else if ! isString(contents)
328
+ croak "barf(): Invalid contents"
329
+ contents = rtrim(contents) + "\n"
260
330
  fs.writeFileSync(filepath, contents, {encoding: 'utf8'})
261
331
  return
262
332
 
@@ -499,5 +569,4 @@ export parseSource = (source) =>
499
569
 
500
570
  export slurpTAML = (filepath) =>
501
571
 
502
- contents = slurp(filepath)
503
- return fromTAML(contents)
572
+ return slurp(filepath, {format: 'TAML'})
package/src/fs.js CHANGED
@@ -2,12 +2,24 @@
2
2
  // fs.coffee
3
3
  var isSystemDir;
4
4
 
5
+ import os from 'os';
6
+
5
7
  import pathlib from 'path';
6
8
 
7
9
  import urllib from 'url';
8
10
 
9
11
  import fs from 'fs';
10
12
 
13
+ import {
14
+ readFile,
15
+ writeFile,
16
+ rm
17
+ } from 'node:fs/promises';
18
+
19
+ import {
20
+ execSync
21
+ } from 'node:child_process';
22
+
11
23
  import readline from 'readline';
12
24
 
13
25
  import NReadLines from 'n-readlines';
@@ -51,6 +63,72 @@ import {
51
63
  fromTAML
52
64
  } from '@jdeighan/base-utils/taml';
53
65
 
66
+ // ---------------------------------------------------------------------------
67
+ export var mkpath = (...lParts) => {
68
+ var _, drive, i, lMatches, lNewParts, len, newPath, part, rest;
69
+ // --- Ignore empty parts
70
+ lNewParts = [];
71
+ for (i = 0, len = lParts.length; i < len; i++) {
72
+ part = lParts[i];
73
+ if (nonEmpty(part)) {
74
+ lNewParts.push(part);
75
+ }
76
+ }
77
+ newPath = lNewParts.join('/').replaceAll('\\', '/');
78
+ if (lMatches = newPath.match(/^([A-Z])\:(.*)$/)) {
79
+ [_, drive, rest] = lMatches;
80
+ return `${drive.toLowerCase()}:${rest}`;
81
+ } else {
82
+ return newPath;
83
+ }
84
+ };
85
+
86
+ // ---------------------------------------------------------------------------
87
+ export var mkdir = (dirpath) => {
88
+ var err;
89
+ try {
90
+ fs.mkdirSync(dirpath);
91
+ } catch (error1) {
92
+ err = error1;
93
+ if (err.code === 'EEXIST') {
94
+ console.log('Directory exists. Please choose another name');
95
+ } else {
96
+ console.log(err);
97
+ }
98
+ process.exit(1);
99
+ }
100
+ };
101
+
102
+ // ---------------------------------------------------------------------------
103
+ export var rmdir = async(dirpath) => {
104
+ await rm(dirpath, {
105
+ recursive: true
106
+ });
107
+ };
108
+
109
+ // ---------------------------------------------------------------------------
110
+ export var rmfile = async(filepath) => {
111
+ await rm(filepath);
112
+ };
113
+
114
+ // --------------------------------------------------------------------------
115
+ export var execCmd = (cmdLine) => {
116
+ execSync(cmdLine, {}, (error, stdout, stderr) => {
117
+ if (error) {
118
+ LOG(`ERROR in ${cmdLine}: ${error.code}`);
119
+ return process.exit(1);
120
+ }
121
+ });
122
+ return stdout;
123
+ };
124
+
125
+ // ---------------------------------------------------------------------------
126
+ export var cloneRepo = (user, repo, dir) => {
127
+ var git_repo;
128
+ git_repo = `https://github.com/${user}/${repo}.git`;
129
+ return execCmd(`git clone ${git_repo} ${dir}`);
130
+ };
131
+
54
132
  // ---------------------------------------------------------------------------
55
133
  // mydir() - pass argument import.meta.url and it will return
56
134
  // the directory your file is in
@@ -62,6 +140,11 @@ export var mydir = (url) => {
62
140
  return final;
63
141
  };
64
142
 
143
+ // ---------------------------------------------------------------------------
144
+ export var homeDir = () => {
145
+ return mkpath(os.homedir());
146
+ };
147
+
65
148
  // ---------------------------------------------------------------------------
66
149
  export var projRoot = (url) => {
67
150
  var dir, rootDir;
@@ -99,7 +182,7 @@ export var getStats = (fullpath) => {
99
182
  export var isFile = (fullpath) => {
100
183
  try {
101
184
  return getStats(fullpath).isFile();
102
- } catch (error) {
185
+ } catch (error1) {
103
186
  return false;
104
187
  }
105
188
  };
@@ -108,7 +191,7 @@ export var isFile = (fullpath) => {
108
191
  export var isDir = (fullpath) => {
109
192
  try {
110
193
  return getStats(fullpath).isDirectory();
111
- } catch (error) {
194
+ } catch (error1) {
112
195
  return false;
113
196
  }
114
197
  };
@@ -142,26 +225,6 @@ export var fileExt = (path) => {
142
225
  }
143
226
  };
144
227
 
145
- // ---------------------------------------------------------------------------
146
- export var mkpath = (...lParts) => {
147
- var _, drive, i, lMatches, lNewParts, len, newPath, part, rest;
148
- // --- Ignore empty parts
149
- lNewParts = [];
150
- for (i = 0, len = lParts.length; i < len; i++) {
151
- part = lParts[i];
152
- if (nonEmpty(part)) {
153
- lNewParts.push(part);
154
- }
155
- }
156
- newPath = lNewParts.join('/').replace(/\\/g, '/');
157
- if (lMatches = newPath.match(/^([A-Z])\:(.*)$/)) {
158
- [_, drive, rest] = lMatches;
159
- return `${drive.toLowerCase()}:${rest}`;
160
- } else {
161
- return newPath;
162
- }
163
- };
164
-
165
228
  // ---------------------------------------------------------------------------
166
229
  export var getFullPath = (filepath) => {
167
230
  return mkpath(pathlib.resolve(filepath));
@@ -273,9 +336,10 @@ export var forEachSetOfBlocks = (filepath, func, block_regexp = /^-{16,}$/, set_
273
336
  };
274
337
 
275
338
  // ---------------------------------------------------------------------------
276
- // slurp - read an entire file into a string
277
- export var slurp = (filepath, maxLines = undef) => {
278
- var contents, lLines;
339
+ // slurp - read a file into a string
340
+ export var slurp = (filepath, hOptions = {}) => {
341
+ var contents, format, lLines, maxLines;
342
+ ({maxLines, format} = getOptions(hOptions));
279
343
  if (defined(maxLines)) {
280
344
  lLines = [];
281
345
  forEachLineInFile(filepath, function(line, nLines) {
@@ -287,21 +351,38 @@ export var slurp = (filepath, maxLines = undef) => {
287
351
  filepath = filepath.replace(/\//g, "\\");
288
352
  contents = fs.readFileSync(filepath, 'utf8').toString();
289
353
  }
290
- return contents;
354
+ switch (format) {
355
+ case 'TAML':
356
+ return fromTAML(contents);
357
+ case 'JSON':
358
+ return JSON.parse(contents);
359
+ default:
360
+ assert(notdefined(format), `Unknown format: ${format}`);
361
+ return contents;
362
+ }
291
363
  };
292
364
 
293
365
  // ---------------------------------------------------------------------------
294
366
  // barf - write a string to a file
295
- export var barf = (filepath, contents) => {
296
- if (isEmpty(contents)) {
297
- return;
298
- }
299
- if (isArray(contents)) {
300
- contents = toBlock(contents);
301
- } else if (!isString(contents)) {
302
- croak("barf(): Invalid contents");
367
+ export var barf = (filepath, contents = '', hOptions = {}) => {
368
+ var format;
369
+ ({format} = getOptions(hOptions));
370
+ switch (format) {
371
+ case 'TAML':
372
+ contents = toTAML(contents);
373
+ break;
374
+ case 'JSON':
375
+ contents = JSON.stringify(contents, null, 3);
376
+ break;
377
+ default:
378
+ assert(notdefined(format), `Unknown format: ${format}`);
379
+ if (isArray(contents)) {
380
+ contents = toBlock(contents);
381
+ } else if (!isString(contents)) {
382
+ croak("barf(): Invalid contents");
383
+ }
384
+ contents = rtrim(contents) + "\n";
303
385
  }
304
- contents = rtrim(contents) + "\n";
305
386
  fs.writeFileSync(filepath, contents, {
306
387
  encoding: 'utf8'
307
388
  });
@@ -333,8 +414,8 @@ export var removeFileWithExt = (path, newExt, hOptions = {}) => {
333
414
  LOG(` unlink ${filename}`);
334
415
  }
335
416
  success = true;
336
- } catch (error) {
337
- err = error;
417
+ } catch (error1) {
418
+ err = error1;
338
419
  LOG(` UNLINK FAILED: ${err.message}`);
339
420
  success = false;
340
421
  }
@@ -576,7 +657,7 @@ export var parseSource = (source) => {
576
657
  // ---------------------------------------------------------------------------
577
658
  // slurpTAML - read TAML from a file
578
659
  export var slurpTAML = (filepath) => {
579
- var contents;
580
- contents = slurp(filepath);
581
- return fromTAML(contents);
660
+ return slurp(filepath, {
661
+ format: 'TAML'
662
+ });
582
663
  };