-
Notifications
You must be signed in to change notification settings - Fork 8
/
elf-utils.js
499 lines (440 loc) · 12 KB
/
elf-utils.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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
/**
* @author Charlie Calvert
*/
const path = require('path');
const fs = require('fs');
const os = require('os');
const mkdirp = require('mkdirp');
const Guid = require('uuid');
/**
* Remember that path.join solves the problem of
* properly appending a file name onto a path
*
* @param {Object} pathName
* @param {Object} fileName
*/
const elfJoin = function(pathName, fileName) {
'use strict';
return path.join(pathName, fileName);
};
function getGuidFromMarkdown(fileName, test) {
'use strict';
fs.readFile(fileName, 'utf8', function(err, data) {
if (err) {
throw err;
}
var result = data.match(/<!-- GUID: (.+?) -->/i)[1];
test(result);
});
}
function getGuid() {
'use strict';
return Guid.create();
}
function getHomeDir() {
'use strict';
let homeDir = null;
if (os.platform() === 'linux') {
homeDir = process.env.HOME;
} else if (os.platform() === 'win32') {
homeDir = process.env.USERPROFILE;
}
return homeDir;
}
/**
* Format the JSON that holds a two dimensional array of
* numbers representing a grid.
*/
var prettyPrintGrid = function(grid) {
'use strict';
let data = JSON.stringify(grid);
let result = data.replace(/\[\"/g, '\n\t[');
return result.replace(']]', ']\n]');
};
/*******************
* Dates
******************/
function createDate(dateSeparator, divider, timeSeparator) {
// TODO: Compare speed of padSlow and pad
function padSlow(number) {
return padNumber(number, 2, 0);
}
function pad(n) {
return (n < 10) ? ('0' + n) : ('' + n);
}
const date = new Date();
return date.getFullYear() + dateSeparator +
pad(date.getMonth() + 1) + dateSeparator +
pad(date.getDate()) + divider +
pad(date.getHours()) + timeSeparator +
pad(date.getMinutes()) + timeSeparator +
pad(date.getSeconds());
}
function getHyphenDate() {
const hyphen = "-";
return createDate(hyphen, hyphen, hyphen);
}
function getNormalDate() {
const hyphen = "-";
const colon = ":";
const space = " ";
return createDate(hyphen, space, colon);
}
/*******************
* Arrays
******************/
const arrayContains = function(target, value) {
'use strict';
let found = false;
for (let i = 0; i < target.length && !found; i++) {
if (target[i] === value) {
found = true;
}
}
return found;
};
function arrayDifference(firstArray, secondArray) {
'use strict';
return firstArray.filter(function(item) {
return secondArray.indexOf(item) < 0;
});
}
// Flawed solution. Read comments: http://stackoverflow.com/a/1187628
function arraySymmetricDifference(firstArray, secondArray) {
'use strict';
let temp = [];
let difference = [];
for (let i = 0; i < firstArray.length; i++) {
console.log(firstArray[i]);
temp[firstArray[i]] = true;
console.log(temp[firstArray[i]]);
}
console.log('temp:', temp);
console.log(firstArray);
for (let i = 0; i < secondArray.length; i++) {
if (temp[secondArray[i]]) {
delete temp[secondArray[i]];
} else {
temp[secondArray[i]] = true;
}
}
console.log(temp);
console.log(firstArray);
for (let item in temp) {
console.log(item);
difference.push(item);
}
return difference;
}
function isArray(itemToCheck) {
'use strict';
return Object.prototype.toString.call(itemToCheck) === '[object Array]';
}
/*******************
* Strings
******************/
function endsWith(value, suffix) {
'use strict';
return value.indexOf(suffix, value.length - suffix.length) !== -1;
}
function getFirstWord(value) {
'use strict';
return value.split(' ')[0];
}
const getLastCharacterOfString = function(value) {
'use strict';
return value.substring(value.length - 1);
};
const getEndFromCharacter = function(value, char) {
return value.substring(value.lastIndexOf(char) + 1, value.length);
};
function htmlEscape(str) {
'use strict';
return String(str)
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/</g, '<')
.replace(/>/g, '>');
}
// jscs:disable validateQuoteMarks
function htmlUnescape(str) {
'use strict';
return String(str)
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, "'")
.replace(/</g, '<')
.replace(/>/g, '>');
}
// jscs:enable validateQuoteMarks
function insertString(fileName, itemToInsert, index) {
'use strict';
return [fileName.slice(0, index), itemToInsert, fileName.slice(index)].join('');
}
const padNumber = function(numberToPad, width, padValue) {
'use strict';
padValue = padValue || '0';
numberToPad = numberToPad + '';
if (numberToPad.length >= width) {
return numberToPad;
} else {
return new Array(width - numberToPad.length + 1).join(padValue) + numberToPad;
}
};
function removeCharactersFromStartOfString(value, numberToDelete) {
'use strict';
return value.slice(numberToDelete, value.length);
}
function removeFromEndAtCharacter(value, char) {
'use strict';
return value.substring(0, value.lastIndexOf(char));
}
function stripPunctuation(value) {
'use strict';
return String(value)
.replace(/\./g, '')
.replace(/!/g, '')
.replace(/\?/g, '')
.replace(/,/g, '');
}
function stripWhiteSpace(value) {
'use strict';
return String(value)
.replace(/ /g, '')
.replace(/\t/g, '')
.replace(/\r/g, '')
.replace(/\n/g, '');
}
/*******************
* File Related
******************/
/* Creates directory with name like:
*
* /home/charlie/2017-09-03-21-09-09
*
*/
function createDateDir() {
let dateDirString = ensureEndsWithPathSep(process.env.HOME) +
getHyphenDate();
ensureDir(dateDirString);
console.log(dateDirString);
return dateDirString;
}
function deleteFile(fileName) {
return new Promise(function(resolve, reject) {
fs.unlink(fileName, (err) => {
if (err) {
reject(err);
}
resolve( {result: 'success'} );
});
});
}
function deleteDirectory(path) {
return new Promise(function(resolve, reject) {
fs.rmdir(path, (err) => {
if (err) {
reject(err);
}
const result = {
result: 'success',
path: path
};
resolve(result);
});
});
}
function directoryExists(path) {
'use strict';
let result = true;
try {
fs.accessSync(path, fs.F_OK);
} catch (e) {
result = false;
}
return result;
}
/**
* Test if a folder exists, if it does not, make it
*/
function ensureDir(folder) {
'use strict';
if (!fs.existsSync(folder)) {
mkdirp(folder);
}
return folder;
}
/**
* Be sure we start with a path separator.
*/
function ensureStartsWithPathSep(fileName) {
'use strict';
if (fileName.substring(0, 1) !== path.sep) {
fileName = path.sep + fileName;
}
return fileName;
}
function ensureEndsWithPathSep(fileName) {
'use strict';
if (getLastCharacterOfString(fileName) !== path.sep) {
fileName = fileName + path.sep;
}
return fileName;
}
function fileExists(filePath) {
'use strict';
try {
return fs.statSync(filePath).isFile();
} catch (err) {
return false;
}
}
// from: http://stackoverflow.com/a/1203361
function getExtension(fileName) {
'use strict';
fileName = fileName.trim();
const array = fileName.split('.');
if (array.length === 1 || (array[0] === '' && array.length === 2)) {
return '';
}
return array.pop().toLowerCase();
}
/*
* @name: getFileNameFromPath
*
* We can't be sure of what the path separator will be since
* we don't know the platform ahead of time. If you need
* to use a pathseparator that may differ from the one for
* the current OS, then you need to specify it:
*
* var actual = eu.getFileNameFromPath(test, "\\");
*
* Otherwise just pass in the string and let the function handle
* the separator automatically:
*
* var actual = eu.getFileNameFromPath(test);
*/
function getFileNameFromPath(fileName, pathSeparator) {
'use strict';
if (typeof pathSeparator === 'undefined') {
pathSeparator = path.sep;
}
const index = fileName.lastIndexOf(pathSeparator);
return fileName.substr(index + 1, fileName.length - index - 1);
}
/*
* @name: readFile
*
* To use promise, don't pass a callback
*/
function readFile(fileName, callback) {
'use strict';
if (!callback) {
return new Promise(function(resolve, reject) {
fs.readFile(fileName, 'utf8', function(err, fileContents) {
if (err) {
reject(err);
}
resolve({
'result': fileContents
});
});
});
} else {
fs.readFile(fileName, 'utf8', function(err, fileContents) {
if (err) {
throw (err);
}
callback({
'result': fileContents
});
});
}
}
function stripExtension(fileName) {
'use strict';
return fileName.substr(0, fileName.lastIndexOf('.'));
}
function swapExtension(fileName, ext) {
'use strict';
return fileName.substr(0, fileName.lastIndexOf('.')) + ext;
}
/*
* @name: writeFile
*
* @param: fileName
* @param: contents
*
* To use promise, don't pass a callback
*/
function writeFile(fileName, contents, callback) {
'use strict';
//console.log('writing', fileName);
if (!callback) {
return new Promise(function(resolve, reject) {
fs.writeFile(fileName, contents, 'utf8', function(err) {
if (err) {
reject(err);
}
resolve({
result: 'success'
});
});
});
} else {
fs.writeFile(fileName, contents, 'utf8', function(err) {
if (err) {
throw (err);
}
callback({
result: 'success'
});
});
}
}
/*******************************************
* Exports *
*******************************************/
exports.elfJoin = elfJoin;
exports.getGuidFromMarkdown = getGuidFromMarkdown;
exports.getGuid = getGuid;
exports.getHomeDir = getHomeDir;
exports.padNumber = padNumber;
exports.prettyPrintGrid = prettyPrintGrid;
// Dates
exports.createDate = createDate;
exports.getNormalDate = getNormalDate;
exports.getHyphenDate = getHyphenDate;
// Array
exports.arrayContains = arrayContains;
exports.arrayDifference = arrayDifference;
exports.arraySymetricDifference = arraySymmetricDifference;
exports.isArray = isArray;
// Strings
exports.endsWith = endsWith;
exports.getFirstWord = getFirstWord;
exports.getLastCharacterOfString = getLastCharacterOfString;
exports.getEndFromCharacter = getEndFromCharacter;
exports.htmlEscape = htmlEscape;
exports.htmlUnescape = htmlUnescape;
exports.insertString = insertString;
exports.removeCharactersFromStartOfString = removeCharactersFromStartOfString;
exports.removeFromEndAtCharacter = removeFromEndAtCharacter;
exports.stripPunctuation = stripPunctuation;
exports.stripWhiteSpace = stripWhiteSpace;
// Files
exports.createDateDir = createDateDir;
exports.deleteFile = deleteFile;
exports.deleteDirectory = deleteDirectory;
exports.directoryExists = directoryExists;
exports.ensureDir = ensureDir;
exports.ensureEndsWithPathSep = ensureEndsWithPathSep;
exports.ensureStartsWithPathSep = ensureStartsWithPathSep;
exports.fileExists = fileExists;
exports.getExtension = getExtension;
exports.getFileNameFromPath = getFileNameFromPath;
exports.readFile = readFile;
exports.stripExtension = stripExtension;
exports.swapExtension = swapExtension;
exports.writeFile = writeFile;