-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathutils.ts
265 lines (261 loc) · 9.02 KB
/
utils.ts
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
/// <reference path="typings/tsd.d.ts"/>
import * as path from 'path';
import * as fs from 'fs';
import * as util from 'util';
import * as _ from 'lodash';
//
// export function newLineActualAsParameter(actualNewLineChars: string) {
// if (actualNewLineChars) {
// return actualNewLineChars.replace(/\n/g, 'LF').replace(/\r/g, 'CR');
// }
// return '';
// }
//
// export function newLineParameterAsActual(parameterNewLineChars: string) {
// if (parameterNewLineChars) {
// return parameterNewLineChars.replace(/LF/g, '\n').replace(/CR/g, '\r');
// }
// return '';
// }
//
// // Converts "C:\boo" , "C:\boo\foo.ts" => "./foo.ts"; Works on unix as well.
// export function makeRelativePath(folderpath: string, filename: string, forceRelative = false) {
// var relativePath = path.relative(folderpath, filename).split('\\').join('/');
// if (forceRelative && relativePath[0] !== '.') {
// relativePath = './' + relativePath;
// }
// return relativePath;
// }
//
//
// // Finds the longest common section of a collection of strings.
// // Simply sorting and comparing first and last http://stackoverflow.com/a/1917041/390330
// function sharedStart(array: string[]): string {
// if (array.length === 0) {
// throw 'Cannot find common root of empty array.';
// }
// var A = array.slice(0).sort(),
// firstWord = A[0],
// lastWord = A[A.length - 1];
//
// if (firstWord === lastWord) {
// return firstWord;
// }
// else {
// var i = -1;
// do {
// i += 1;
// var firstWordChar = firstWord.charAt(i);
// var lastWordChar = lastWord.charAt(i);
// } while (firstWordChar === lastWordChar);
//
// return firstWord.substring(0, i);
// }
// }
//
// // Finds the common system path between paths
// // Explanation of how is inline
// export function findCommonPath(paths: string[], pathSeperator: string) {
// // Now for "C:\u\starter" "C:\u\started" => "C:\u\starte"
// var largetStartSegement = sharedStart(paths);
//
// // For "C:\u\starte" => C:\u\
// var ending = largetStartSegement.lastIndexOf(pathSeperator);
// return largetStartSegement.substr(0, ending);
// }
//
// /**
// * Returns the result of an array inserted into another, starting at the given index.
// */
// export function insertArrayAt<T>(array: T[], index: number, arrayToInsert: T[]): T[] {
// var updated = array.slice(0);
// var spliceAt: any[] = [index, 0];
// Array.prototype.splice.apply(updated, spliceAt.concat(arrayToInsert));
// return updated;
// }
//
// /**
// * Compares the end of the string with the given suffix for literal equality.
// *
// * @returns {boolean} whether the string ends with the suffix literally.
// */
// export function endsWith(str: string, suffix: string): boolean {
// return str.indexOf(suffix, str.length - suffix.length) !== -1;
// }
//
// export function isJavaScriptFile(filePath: string): boolean {
// if (filePath.toLowerCase) {
// return this.endsWith(filePath.toLowerCase(), '.js');
// }
// return false;
// }
//
// /** function for formatting strings
// * ('{0} says {1}','la','ba' ) => 'la says ba'
// */
// export function format(str: string, ...args: any[]) {
// return str.replace(/{(\d+)}/g, function (m, i?) {
// return args[i] !== undefined ? args[i] : m;
// });
// }
//
/**
* Get a random hex value
*
* @returns {string} hex string
*/
export function getRandomHex(length: number = 16): string {
var name: string = '';
do {
name += Math.round(Math.random() * Math.pow(16, 8)).toString(16);
}
while (name.length < length);
return name.substr(0, length);
}
//
/**
* Get a unique temp file
*
* @returns {string} unique-ish path to file in given directory.
* @throws when it cannot create a temp file in the specified directory
*/
export function getTempFile(prefix?: string, dir: string = '', extension = '.tmp.txt'): string {
prefix = (prefix ? prefix + '-' : '');
var attempts = 100;
do {
var name: string = prefix + getRandomHex(8) + extension;
var dest: string = path.join(dir, name);
if (!fs.existsSync(dest)) {
return dest;
}
attempts--;
}
while (attempts > 0);
throw 'Cannot create temp file in ' + dir;
}
//
// /////////////////////////////////////////////////////////////////////////
// // From https://github.com/centi/node-dirutils/blob/master/index.js
// // Slightly modified. See BAS
// ////////////////////////////////////////////////////////////////////////
//
// /**
// * Get all files from a directory and all its subdirectories.
// * @param {String} dirPath A path to a directory
// * @param {RegExp|Function} exclude Defines which files should be excluded.
// Can be a RegExp (whole filepath is tested) or a Function which will get the filepath
// as an argument and should return true (exclude file) or false (do not exclude).
// * @returns {Array} An array of files
// */
// export function getFiles(dirPath: string, exclude?: (filename: string) => boolean): string[] {
// return _getAll(dirPath, exclude, true);
// };
//
// /**
// * Get all directories from a directory and all its subdirectories.
// * @param {String} dirPath A path to a directory
// * @param {RegExp|Function} exclude Defines which directories should be excluded.
// Can be a RegExp (whole dirpath is tested) or a Function which will get the dirpath
// as an argument and should return true (exclude dir) or false (do not exclude).
// * @returns {Array} An array of directories
// */
// export function getDirs(dirPath: string, exclude?: (filename: string) => boolean): string[] {
// return _getAll(dirPath, exclude, false);
// };
//
// /**
// * Get all files or directories from a directory and all its subdirectories.
// * @param {String} dirPath A path to a directory
// * @param {RegExp|Function} exclude Defines which files or directories should be excluded.
// Can be a RegExp (whole path is tested) or a Function which will get the path
// as an argument and should return true (exclude) or false (do not exclude).
// * @param {Boolean} getFiles Whether to get files (true) or directories (false).
// * @returns {Array} An array of files or directories
// */
// function _getAll(dirPath: string, exclude: RegExp | ((filename: string) => boolean), getFiles: boo) {
// var _checkDirResult = _checkDirPathArgument(dirPath);
// var _checkExcludeResult;
// var items = [];
//
// if (util.isError(_checkDirResult)) {
// return _checkDirResult;
// }
// if (exclude) {
// _checkExcludeResult = _checkExcludeArgument(exclude);
// if (util.isError(_checkExcludeResult)) {
// return _checkExcludeResult;
// }
// }
//
// fs.readdirSync(dirPath).forEach(function (_item) {
// var _itempath = path.normalize(dirPath + '/' + _item);
//
// if (exclude) {
// if (util.isRegExp(exclude)) {
// if (exclude.test(_itempath)) {
// return;
// }
// }
// else {
// if (exclude(_itempath)) { // BAS, match full item path
// return;
// }
// }
// }
//
// if (fs.statSync(_itempath).isDirectory()) {
// if (!getFiles) {
// items.push(_itempath);
// }
// items = items.concat(_getAll(_itempath, exclude, getFiles));
// }
// else {
// if (getFiles === true) {
// items.push(_itempath);
// }
// }
// });
//
// return items;
// }
//
// /**
// * Check if the dirPath is provided and if it does exist on the filesystem.
// * @param {String} dirPath A path to the directory
// * @returns {String|Error} Returns the dirPath if everything is allright or an Error otherwise.
// */
// function _checkDirPathArgument(dirPath) {
// if (!dirPath || dirPath === '') {
// return new Error('Dir path is missing!');
// }
// if (!fs.existsSync(dirPath)) {
// return new Error('Dir path does not exist: ' + dirPath);
// }
//
// return dirPath;
// }
//
// /**
// * Check if the exclude argument is a RegExp or a Function.
// * @param {RegExp|Function} exclude A RegExp or a Function which returns true/false.
// * @returns {String|Error} Returns the exclude argument if everything is allright or an Error otherwise.
// */
// function _checkExcludeArgument(exclude) {
// if (!util.isRegExp(exclude) && typeof (exclude) !== 'function') {
// return new Error('Argument exclude should be a RegExp or a Function');
// }
//
// return exclude;
// }
//
//
// export function firstElementWithValue<T>(elements: T[], defaultResult: T = null): T {
// var result: T = defaultResult;
// _.each(elements, (item) => {
// if (!_.isNull(item) && !_.isUndefined(item)) {
// result = item;
// return false; // break out of lodash loop
// }
// });
// return result;
// }