-
Notifications
You must be signed in to change notification settings - Fork 0
/
assert.js
224 lines (190 loc) · 5.91 KB
/
assert.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
'use strict'
import fs from 'fs'
import { exec } from 'child_process'
import { info, serializeMsg } from './log.js'
import { isWindows, symbols } from './_common.js'
import { check, guard } from './execute.js'
// make Errors a bit more specific (also in stacktrace)
export class FailError extends Error {
constructor(message) {
super(message)
this.name = 'FailError'
// this.channel = 'logging' // Example custom property
}
}
export const pass = (...msg) => {
console.log(
'\u001b[32mpass: ' + serializeMsg(msg) + ` ${symbols.ok}\u001b[0m`
)
}
export const fail = (...msg) => {
const errMsg =
'\u001b[91;48;5;52mfail(): ' +
serializeMsg(msg) +
` failed ${symbols.tripleCross}\u001b[0m`
// TODO depend on context, i.e. not in mocha
exec('aplay -q ./util/sounds/CantinaBand3.wav &')
throw new FailError(errMsg)
// REF stacktrace matters
// https://stackoverflow.com/questions/16697791/nodejs-get-filename-of-caller-function
// Error.captureStackTrace(err);
// warn(
// '\n',
// // @ts-ignore
// err.stack
// .split(/\r\n|\r|\n/)
// .slice(2, -5)
// .map(line => (stackLine.test(line) ? '\u001b[38;5;112m' + line + '\u001b[0m' : line))
// .join('\n')
// );
// throw err;
// process.exit(1);
}
// ===========================================================
// ensure Functions (asserts)
// ===========================================================
export const ensureTrue = (value, ...msg) => {
value === true || fail('ensureTrue():', ...msg)
}
export const ensureFalse = (value, ...msg) => {
value === false || fail('ensureTrue():', ...msg)
}
export const ensureTruthy = (value, ...msg) => {
!!value || fail('ensureTruthy():', ...msg)
}
export const ensureEqual = (shouldValue, isValue, ...msg) => {
shouldValue === isValue ||
fail(
`ensureEqual(): shouldValue '${shouldValue}' (${typeof shouldValue}) does not match isValue '${isValue}' (${typeof isValue})`,
...msg
)
}
export const ensureString = (value, ...msg) => {
typeof value === 'undefined' &&
fail('ensureString(): Value not even defined', ...msg)
typeof value === 'string' ||
fail(`ensureString(): Not a string '${value}'`, ...msg)
value.length > 0 || fail(`ensureString(): empty string '${value}'`, ...msg)
}
export const ensureFileExists = (path, ...msg) => {
ensureTrue(
fs.existsSync(path),
`ensureFileExists: no such file '${path}'`,
...msg
)
ensureTrue(
fs.lstatSync(path).isFile(),
`ensureFileExists: '${path}' is a dir (should be a file)`,
...msg
)
}
// Note: was ensureDirExists
export const ensureFolderExists = (path, ...msg) => {
ensureTrue(
fs.existsSync(path),
`ensureFolderExists: no such directory '${path}'`,
...msg
)
ensureTrue(
fs.lstatSync(path).isDirectory(),
`ensureFolderExists: '${path}' is a file, not a directory)`,
...msg
)
}
export const ensureFileOrFolderExists = (path, ...msg) => {
ensureTrue(
fs.existsSync(path),
`ensureFileExists: no such file/folder '${path}'`,
...msg
)
}
export const ensureFileOrFolderOrLinkExists = (path, ...msg) => {
const stat = fs.lstatSync(path)
ensureTrue(stat.isFile() || stat.isDirectory() || stat.isSymbolicLink(),
`ensureFileExists: no such file/folder/link '${path}'`,
...msg
)
}
export const ensureWellFormedUser = (user, ...msg) => {
ensureTrue(
/^[a-z]*$/.test(user),
`not a valid user '${user}', possibly a command?`, ...msg
)
}
export const ensureRoot = () => {
if (isWindows) {
if (check('net session > nul 2>&1', { mute: true }) !== 0) {
fail('you are not in an admin prompt')
}
} else {
// @ts-ignore
process.getuid() === 0 || fail('you are not root')
}
}
export const ensureNonRoot = () => {
if (isWindows) {
if (check('net session > nul 2>&1', { mute: true }) === 0) {
fail('you are in an admin prompt, please run in a non-admin prompt')
}
} else {
// @ts-ignore
process.getuid() !== 0 || fail('you are root, run as a non-root')
}
}
export const ensureMachine = machineName => {
const actualMachineName = guard('uname -n', { mute: true, noPass: true }).trim()
ensureTrue(machineName === actualMachineName, `ensureMachine: machine name '${actualMachineName}' does not match expected machine name '${machineName}'.`)
pass(`ensureMachine: '${machineName}'`)
}
const validURL = /^(http[s]?:\/\/(www\.)?|ftp:\/\/(www\.)?|www\.){1}([0-9A-Za-z-.@:%_+~#=]+)+((\.[a-zA-Z]{2,3})+)(\/(.*))?(\?(.*))?/
export const ensureValidURL = (url) => {
ensureTrue(validURL.test(url), `url '${url}' seems not to be a valid url`)
}
// only used for self-testing in UtilsDEmo
export const ensureFails = (fn, ...msg) => {
let failed = false
try {
fn()
} catch (error) {
pass('↑ ensureFails: Des g\'hört so (all good)', error)
failed = true
}
ensureTrue(failed, 'function did NOT fail!', ...msg)
}
export const ensureRealObject = (o) => {
ensureTrue(
typeof o === 'object' && o !== null && !Array.isArray(o),
`not a real object (not counting null, array): ${o}`
)
}
export const ensureArray = (a) => {
ensureTrue(Array.isArray(a), `not an array: ${a}`)
}
export const validateOptions = (optionsObject, validOptions) => {
ensureRealObject(optionsObject)
ensureArray(validOptions)
Object.keys(optionsObject).map(k => ensureTrue(validOptions.includes(k), `unknown key '${k}' (upper/lowercase?) not in`, validOptions))
}
export default {
FailError,
pass,
fail,
ensureTrue,
ensureFalse,
ensureTruthy,
ensureEqual,
ensureString,
ensureFileExists,
ensureFolderExists,
ensureFileOrFolderExists,
ensureFileOrFolderOrLinkExists,
ensureRoot,
ensureNonRoot,
ensureMachine,
ensureWellFormedUser,
ensureValidURL,
ensureFails,
ensureRealObject,
ensureArray,
validateOptions
}