@jdeighan/coffee-utils 4.1.6 → 4.1.10

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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@jdeighan/coffee-utils",
3
3
  "type": "module",
4
- "version": "4.1.6",
4
+ "version": "4.1.10",
5
5
  "description": "A set of utility functions for CoffeeScript",
6
6
  "main": "coffee_utils.js",
7
7
  "exports": {
@@ -13,7 +13,6 @@
13
13
  "./debug": "./src/debug_utils.js",
14
14
  "./svelte": "./src/svelte_utils.js",
15
15
  "./test": "./src/UnitTester.js",
16
- "./privenv": "./src/private_env.js",
17
16
  "./package.json": "./package.json"
18
17
  },
19
18
  "engines": {
@@ -21,7 +20,8 @@
21
20
  },
22
21
  "scripts": {
23
22
  "build": "cls && rm -f ./src/*.js && coffee -c ./src",
24
- "pretest": "npm run build && rm -f ./test/*.js && rm -f ./test/*.coffee && cielo -fq ./test",
23
+ "old_pretest": "npm run build && rm -f ./test/*.js && rm -f ./test/*.coffee && cielo -fq ./test",
24
+ "pretest": "cls && coffee -c .",
25
25
  "test": "ava ./test/*.test.js",
26
26
  "prefinaltest": "npm run pretest",
27
27
  "finaltest": "cross-env FINALTEST=yes ava ./test/*.test.js"
@@ -86,6 +86,7 @@ export joinBlocks = (lBlocks...) ->
86
86
 
87
87
  lNonEmptyBlocks = []
88
88
  for block in lBlocks
89
+ assert isString(block), "joinBlocks(): block #{block} is not a string"
89
90
  if nonEmpty(block)
90
91
  lNonEmptyBlocks.push block
91
92
  return lNonEmptyBlocks.join('\n')
@@ -110,6 +110,7 @@ export var joinBlocks = function(...lBlocks) {
110
110
  lNonEmptyBlocks = [];
111
111
  for (i = 0, len1 = lBlocks.length; i < len1; i++) {
112
112
  block = lBlocks[i];
113
+ assert(isString(block), `joinBlocks(): block ${block} is not a string`);
113
114
  if (nonEmpty(block)) {
114
115
  lNonEmptyBlocks.push(block);
115
116
  }
@@ -100,6 +100,14 @@ export isHash = (x) ->
100
100
 
101
101
  return (getClassName(x) == 'Object')
102
102
 
103
+ # ---------------------------------------------------------------------------
104
+
105
+ export hashHasKey = (x, key) ->
106
+
107
+ assert isHash(x), "hashHasKey(): not a hash"
108
+ assert isString(key), "hashHasKey(): key not a string"
109
+ return x.hasOwnProperty(key)
110
+
103
111
  # ---------------------------------------------------------------------------
104
112
  # isEmpty
105
113
  # - string is whitespace, array has no elements, hash has no keys
@@ -149,6 +157,7 @@ export setCommentRegexp = (regexp) ->
149
157
 
150
158
  export isComment = (str) ->
151
159
 
160
+ assert isString(str), "isComment(): not a string"
152
161
  return if str.match(commentRegExp) then true else false
153
162
 
154
163
  # ---------------------------------------------------------------------------
@@ -264,6 +273,7 @@ export titleLine = (title, char='=', padding=2, linelen=42) ->
264
273
 
265
274
  export rtrim = (line) ->
266
275
 
276
+ assert isString(line), "rtrim(): line is not a string"
267
277
  lMatches = line.match(/\s+$/)
268
278
  if lMatches?
269
279
  n = lMatches[0].length # num chars to remove
@@ -357,3 +367,21 @@ export extractMatches = (line, regexp, convertFunc=undef) ->
357
367
  return lStrings
358
368
 
359
369
  # ---------------------------------------------------------------------------
370
+
371
+ export envVarsWithPrefix = (prefix, hOptions={}) ->
372
+ # --- valid options:
373
+ # stripPrefix
374
+
375
+ assert prefix, "envVarsWithPrefix: empty prefix!"
376
+ plen = prefix.length
377
+ h = {}
378
+ for key in Object.keys(process.env)
379
+ if key.indexOf(prefix) == 0
380
+ if hOptions.stripPrefix
381
+ h[key.substr(plen)] = process.env[key]
382
+ else
383
+ h[key] = process.env[key]
384
+ return h
385
+
386
+ # ---------------------------------------------------------------------------
387
+
@@ -97,6 +97,13 @@ export var isHash = function(x) {
97
97
  return getClassName(x) === 'Object';
98
98
  };
99
99
 
100
+ // ---------------------------------------------------------------------------
101
+ export var hashHasKey = function(x, key) {
102
+ assert(isHash(x), "hashHasKey(): not a hash");
103
+ assert(isString(key), "hashHasKey(): key not a string");
104
+ return x.hasOwnProperty(key);
105
+ };
106
+
100
107
  // ---------------------------------------------------------------------------
101
108
  // isEmpty
102
109
  // - string is whitespace, array has no elements, hash has no keys
@@ -147,6 +154,7 @@ export var setCommentRegexp = function(regexp) {
147
154
 
148
155
  // ---------------------------------------------------------------------------
149
156
  export var isComment = function(str) {
157
+ assert(isString(str), "isComment(): not a string");
150
158
  if (str.match(commentRegExp)) {
151
159
  return true;
152
160
  } else {
@@ -266,6 +274,7 @@ export var titleLine = function(title, char = '=', padding = 2, linelen = 42) {
266
274
  // rtrim - strip trailing whitespace
267
275
  export var rtrim = function(line) {
268
276
  var lMatches, n;
277
+ assert(isString(line), "rtrim(): line is not a string");
269
278
  lMatches = line.match(/\s+$/);
270
279
  if (lMatches != null) {
271
280
  n = lMatches[0].length; // num chars to remove
@@ -392,3 +401,25 @@ export var extractMatches = function(line, regexp, convertFunc = undef) {
392
401
  };
393
402
 
394
403
  // ---------------------------------------------------------------------------
404
+ export var envVarsWithPrefix = function(prefix, hOptions = {}) {
405
+ var h, i, key, len, plen, ref;
406
+ // --- valid options:
407
+ // stripPrefix
408
+ assert(prefix, "envVarsWithPrefix: empty prefix!");
409
+ plen = prefix.length;
410
+ h = {};
411
+ ref = Object.keys(process.env);
412
+ for (i = 0, len = ref.length; i < len; i++) {
413
+ key = ref[i];
414
+ if (key.indexOf(prefix) === 0) {
415
+ if (hOptions.stripPrefix) {
416
+ h[key.substr(plen)] = process.env[key];
417
+ } else {
418
+ h[key] = process.env[key];
419
+ }
420
+ }
421
+ }
422
+ return h;
423
+ };
424
+
425
+ // ---------------------------------------------------------------------------
@@ -209,6 +209,7 @@ reMethod = ///^
209
209
 
210
210
  export funcMatch = (curFunc) ->
211
211
 
212
+ assert isString(curFunc), "funcMatch(): not a string"
212
213
  if lDebugFuncs.includes(curFunc)
213
214
  return true
214
215
  else if (lMatches = curFunc.match(reMethod)) \
@@ -204,6 +204,7 @@ reMethod = /^([A-Za-z_][A-Za-z0-9_]*)\.([A-Za-z_][A-Za-z0-9_]*)$/;
204
204
  // --- export only to allow unit tests
205
205
  export var funcMatch = function(curFunc) {
206
206
  var _, cls, lMatches, meth;
207
+ assert(isString(curFunc), "funcMatch(): not a string");
207
208
  if (lDebugFuncs.includes(curFunc)) {
208
209
  return true;
209
210
  } else if ((lMatches = curFunc.match(reMethod)) && ([_, cls, meth] = lMatches) && lDebugFuncs.includes(meth)) {
@@ -6,7 +6,7 @@ import fs from 'fs'
6
6
 
7
7
  import {
8
8
  assert, undef, pass, rtrim, error, nonEmpty,
9
- isRegExp, isFunction, croak,
9
+ isString, isRegExp, isFunction, croak,
10
10
  } from '@jdeighan/coffee-utils'
11
11
  import {log} from '@jdeighan/coffee-utils/log'
12
12
  import {debug} from '@jdeighan/coffee-utils/debug'
@@ -34,6 +34,7 @@ export isSimpleFileName = (path) ->
34
34
 
35
35
  export fileExt = (path) ->
36
36
 
37
+ assert isString(path), "fileExt(): path not a string"
37
38
  if lMatches = path.match(/\.[A-Za-z0-9_]+$/)
38
39
  return lMatches[0]
39
40
  else
@@ -45,8 +46,14 @@ export fileExt = (path) ->
45
46
 
46
47
  export mydir = (url) ->
47
48
 
48
- dir = pathlib.dirname(urllib.fileURLToPath(url))
49
- return mkpath(dir)
49
+ debug "url = #{url}"
50
+ path = urllib.fileURLToPath(url)
51
+ debug "path = #{path}"
52
+ dir = pathlib.dirname(path)
53
+ debug "dir = #{dir}"
54
+ final = mkpath(dir)
55
+ debug "final = #{final}"
56
+ return final
50
57
 
51
58
  # ---------------------------------------------------------------------------
52
59
 
@@ -129,6 +136,25 @@ export withExt = (path, newExt, hOptions={}) ->
129
136
  name = name.substr(1)
130
137
  return mkpath(dir, "#{name}#{newExt}")
131
138
 
139
+ # ---------------------------------------------------------------------------
140
+ # removeFileWithExt - remove file with different ext
141
+
142
+ export removeFileWithExt = (path, newExt, hOptions={}) ->
143
+ # --- Valid options:
144
+ # doLog
145
+ # removeLeadingUnderScore
146
+
147
+ fullpath = withExt(path, newExt, hOptions)
148
+ try
149
+ fs.unlinkSync fullpath
150
+ if hOptions.doLog
151
+ log " unlink #{filename}"
152
+ success = true
153
+ catch err
154
+ log " UNLINK FAILED: #{err.message}"
155
+ success = false
156
+ return success
157
+
132
158
  # ---------------------------------------------------------------------------
133
159
  # withUnderScore - add '_' to file name
134
160
 
package/src/fs_utils.js CHANGED
@@ -13,6 +13,7 @@ import {
13
13
  rtrim,
14
14
  error,
15
15
  nonEmpty,
16
+ isString,
16
17
  isRegExp,
17
18
  isFunction,
18
19
  croak
@@ -46,6 +47,7 @@ export var isSimpleFileName = function(path) {
46
47
  // ---------------------------------------------------------------------------
47
48
  export var fileExt = function(path) {
48
49
  var lMatches;
50
+ assert(isString(path), "fileExt(): path not a string");
49
51
  if (lMatches = path.match(/\.[A-Za-z0-9_]+$/)) {
50
52
  return lMatches[0];
51
53
  } else {
@@ -57,9 +59,15 @@ export var fileExt = function(path) {
57
59
  // mydir() - pass argument `import.meta.url` and it will return
58
60
  // the directory your file is in
59
61
  export var mydir = function(url) {
60
- var dir;
61
- dir = pathlib.dirname(urllib.fileURLToPath(url));
62
- return mkpath(dir);
62
+ var dir, final, path;
63
+ debug(`url = ${url}`);
64
+ path = urllib.fileURLToPath(url);
65
+ debug(`path = ${path}`);
66
+ dir = pathlib.dirname(path);
67
+ debug(`dir = ${dir}`);
68
+ final = mkpath(dir);
69
+ debug(`final = ${final}`);
70
+ return final;
63
71
  };
64
72
 
65
73
  // ---------------------------------------------------------------------------
@@ -148,6 +156,28 @@ export var withExt = function(path, newExt, hOptions = {}) {
148
156
  return mkpath(dir, `${name}${newExt}`);
149
157
  };
150
158
 
159
+ // ---------------------------------------------------------------------------
160
+ // removeFileWithExt - remove file with different ext
161
+ export var removeFileWithExt = function(path, newExt, hOptions = {}) {
162
+ var err, fullpath, success;
163
+ // --- Valid options:
164
+ // doLog
165
+ // removeLeadingUnderScore
166
+ fullpath = withExt(path, newExt, hOptions);
167
+ try {
168
+ fs.unlinkSync(fullpath);
169
+ if (hOptions.doLog) {
170
+ log(` unlink ${filename}`);
171
+ }
172
+ success = true;
173
+ } catch (error1) {
174
+ err = error1;
175
+ log(` UNLINK FAILED: ${err.message}`);
176
+ success = false;
177
+ }
178
+ return success;
179
+ };
180
+
151
181
  // ---------------------------------------------------------------------------
152
182
  // withUnderScore - add '_' to file name
153
183
  export var withUnderScore = function(path) {
@@ -14,7 +14,7 @@ import {arrayToBlock, blockToArray} from '@jdeighan/coffee-utils/block'
14
14
  export splitLine = (line) ->
15
15
 
16
16
  assert line?, "splitLine(): line is undef"
17
- assert (typeof line == 'string'), "splitLine(): line is not a string"
17
+ assert isString(line), "splitLine(): line is not a string"
18
18
  line = rtrim(line)
19
19
  lMatches = line.match(/^(\s*)(.*)$/)
20
20
  return [lMatches[1].length, lMatches[2]]
@@ -34,6 +34,7 @@ export indentation = (level) ->
34
34
 
35
35
  export indentLevel = (str) ->
36
36
 
37
+ assert isString(str), "indentLevel(): not a string"
37
38
  lMatches = str.match(/^\t*/)
38
39
  return lMatches[0].length
39
40
 
@@ -76,6 +77,8 @@ export undented = (text, level=undef) ->
76
77
  return ''
77
78
  else if isArray(text)
78
79
  lLines = text
80
+ for line in lLines
81
+ assert isString(line), "undented(): input array is not all strings"
79
82
  if (lLines.length == 0)
80
83
  return []
81
84
  else
@@ -25,7 +25,7 @@ import {
25
25
  export var splitLine = function(line) {
26
26
  var lMatches;
27
27
  assert(line != null, "splitLine(): line is undef");
28
- assert(typeof line === 'string', "splitLine(): line is not a string");
28
+ assert(isString(line), "splitLine(): line is not a string");
29
29
  line = rtrim(line);
30
30
  lMatches = line.match(/^(\s*)(.*)$/);
31
31
  return [lMatches[1].length, lMatches[2]];
@@ -44,6 +44,7 @@ export var indentation = function(level) {
44
44
  // it's OK if the string is ONLY indentation
45
45
  export var indentLevel = function(str) {
46
46
  var lMatches;
47
+ assert(isString(str), "indentLevel(): not a string");
47
48
  lMatches = str.match(/^\t*/);
48
49
  return lMatches[0].length;
49
50
  };
@@ -84,7 +85,7 @@ export var indented = function(input, level = 0) {
84
85
  // indentation is removed
85
86
  // - returns same type as text, i.e. either string or array
86
87
  export var undented = function(text, level = undef) {
87
- var i, lLines, lMatches, lNewLines, len, line, nToRemove, toRemove;
88
+ var i, j, lLines, lMatches, lNewLines, len, len1, line, nToRemove, toRemove;
88
89
  if ((level != null) && (level === 0)) {
89
90
  return text;
90
91
  }
@@ -95,6 +96,10 @@ export var undented = function(text, level = undef) {
95
96
  }
96
97
  } else if (isArray(text)) {
97
98
  lLines = text;
99
+ for (i = 0, len = lLines.length; i < len; i++) {
100
+ line = lLines[i];
101
+ assert(isString(line), "undented(): input array is not all strings");
102
+ }
98
103
  if (lLines.length === 0) {
99
104
  return [];
100
105
  }
@@ -111,8 +116,8 @@ export var undented = function(text, level = undef) {
111
116
  }
112
117
  nToRemove = toRemove.length;
113
118
  lNewLines = [];
114
- for (i = 0, len = lLines.length; i < len; i++) {
115
- line = lLines[i];
119
+ for (j = 0, len1 = lLines.length; j < len1; j++) {
120
+ line = lLines[j];
116
121
  if (isEmpty(line)) {
117
122
  lNewLines.push('');
118
123
  } else {
package/temp.js CHANGED
@@ -1,16 +1,26 @@
1
1
  // Generated by CoffeeScript 2.6.1
2
2
  // temp.coffee
3
- var str;
3
+ var dir;
4
4
 
5
5
  import {
6
- hashToStr
6
+ say
7
7
  } from '@jdeighan/coffee-utils';
8
8
 
9
- // ---------------------------------------------------------------------------
10
- str = hashToStr({
11
- c: 3,
12
- b: 2,
13
- a: 1
14
- });
9
+ import {
10
+ log
11
+ } from '@jdeighan/coffee-utils/log';
12
+
13
+ import {
14
+ setDebugging
15
+ } from '@jdeighan/coffee-utils/debug';
16
+
17
+ import {
18
+ mydir,
19
+ mkpath
20
+ } from '@jdeighan/coffee-utils/fs';
21
+
22
+ setDebugging(true);
23
+
24
+ dir = mydir(import.meta.url);
15
25
 
16
- console.log(str);
26
+ say(`dir = ${dir}`);
@@ -1,185 +0,0 @@
1
- # block.test.coffee
2
-
3
- import assert from 'assert'
4
-
5
- import {UnitTester} from '@jdeighan/coffee-utils/test'
6
- import {
7
- blockToArray, arrayToBlock, firstLine, remainingLines,
8
- normalizeBlock, truncateBlock,
9
- joinBlocks, forEachLine, forEachBlock, forEachSetOfBlocks,
10
- } from '@jdeighan/coffee-utils/block'
11
-
12
- simple = new UnitTester()
13
-
14
- # ---------------------------------------------------------------------------
15
-
16
- simple.equal 108, blockToArray("abc\nxyz\n"), [
17
- 'abc'
18
- 'xyz'
19
- ]
20
-
21
- simple.equal 113, blockToArray("abc\nxyz\n\n\n\n"), [
22
- 'abc'
23
- 'xyz'
24
- ]
25
-
26
- simple.equal 118, blockToArray("abc\n\nxyz\n"), [
27
- 'abc'
28
- ''
29
- 'xyz'
30
- ]
31
-
32
- # ---------------------------------------------------------------------------
33
-
34
- simple.equal 126, arrayToBlock(['a','b','c']), "a\nb\nc\n"
35
-
36
- # ---------------------------------------------------------------------------
37
-
38
- simple.equal 225, firstLine("""
39
- #starbucks
40
- do this
41
- do that
42
- """), '#starbucks'
43
-
44
- # ---------------------------------------------------------------------------
45
-
46
- simple.equal 225, remainingLines("""
47
- #starbucks
48
- do this
49
- do that
50
- """), """
51
- do this
52
- do that
53
- """
54
-
55
- # ---------------------------------------------------------------------------
56
-
57
- (() ->
58
- str = joinBlocks('import me', '', 'do this\ndo that')
59
- simple.equal 17, str, """
60
- import me
61
- do this
62
- do that
63
- """
64
- )()
65
-
66
- # ---------------------------------------------------------------------------
67
-
68
- simple.equal 49, normalizeBlock("""
69
- line 1
70
- line 2
71
- """), """
72
- line 1
73
- line 2
74
- """ + '\n'
75
-
76
- simple.equal 57, normalizeBlock("""
77
- line 1
78
-
79
- line 2
80
- """), """
81
- line 1
82
- line 2
83
- """ + '\n'
84
-
85
- simple.equal 66, normalizeBlock("""
86
-
87
- line 1
88
-
89
- line 2
90
-
91
-
92
- """), """
93
- line 1
94
- line 2
95
- """ + '\n'
96
-
97
- # ---------------------------------------------------------------------------
98
-
99
- simple.equal 96, truncateBlock("""
100
- line 1
101
- line 2
102
- line 3
103
- line 4
104
- """, 2), """
105
- line 1
106
- line 2
107
- """ + '\n'
108
-
109
- # ---------------------------------------------------------------------------
110
-
111
- (() ->
112
- lBlocks = [
113
- "import {say} from '@jdeighan/coffee-utils'",
114
- "",
115
- "<script>\n\tx = 42\n</script>",
116
- "",
117
- ]
118
- str = joinBlocks(lBlocks...)
119
- simple.equal 34, str, """
120
- import {say} from '@jdeighan/coffee-utils'
121
- <script>
122
- x = 42
123
- </script>
124
- """
125
- )()
126
-
127
- # ---------------------------------------------------------------------------
128
-
129
- (() ->
130
- lImports = [
131
- "import {say} from '@jdeighan/coffee-utils'",
132
- ]
133
- code = """
134
- if (x==42)
135
- log "line 2 in unit test"
136
- """
137
- str = joinBlocks(lImports..., code)
138
- simple.equal 34, str, """
139
-
140
- import {say} from '@jdeighan/coffee-utils'
141
- if (x==42)
142
- log "line 2 in unit test"
143
- """
144
- )()
145
-
146
- # ---------------------------------------------------------------------------
147
- # test forEachLine()
148
-
149
- (() ->
150
- lLines = []
151
-
152
- callback = (line) ->
153
- lLines.push line
154
- return
155
-
156
- filepath = "c:/Users/johnd/coffee-utils/test/data/file2.txt"
157
- await forEachLine filepath, callback
158
-
159
- simple.equal 55, lLines, [
160
- "abc",
161
- "def",
162
- "ghi",
163
- "jkl",
164
- ]
165
- )()
166
-
167
- # ---------------------------------------------------------------------------
168
- # test forEachBlock()
169
-
170
- (() ->
171
- lBlocks = []
172
-
173
- callback = (block) ->
174
- lBlocks.push block
175
- return
176
-
177
- filepath = "c:/Users/johnd/coffee-utils/test/data/file3.txt"
178
- await forEachBlock filepath, callback
179
-
180
- simple.equal 76, lBlocks, [
181
- "abc\ndef",
182
- "abc\ndef\nghi",
183
- "abc\ndef\nghi\njkl",
184
- ]
185
- )()