-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnix.js
593 lines (553 loc) · 14.4 KB
/
nix.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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
var glob = require("glob");
var path = require("path");
var url = require("url");
var zlib = require("zlib");
var fs = require("fs");
var rang = require("./lib/string");
var crypto = require("crypto");
/**
* @param {[object]}
* @param {Function}
* Options:
* source: path to source directory
* destination: destination where to save
* compilers: [Array] nixCompilers
* options: {object} to be passed to compilers
* hash: boolean
* gzip: boolean
* async: boolean to compile files in async
* cdnBase: String to be used as prefixed in manifest and paths
* gzipOriginal: boolean Whether to gzip original file or create
* a .gz file
*
* Callback: Function(optional)
*/
function Nix(options, callback){
/*
Async file compilation flag
*/
var async = false,
/*
List of files to compile
*/
files,
/*
CDN path option to prefix manifest urls
*/
cdnBase = "",
/*
Options that will be passed to compilers
*/
compilerOptions = {},
/*
To generate hash suffixed files
pass manifest file option too to save these paths
*/
doesHash = false,
/*
To enable gzip compression of files
*/
doesGzip = false,
/*
Manifest Object extracted from json or
the manifest object passed in to Nix
*/
manifest,
/*
baseDirectory of project
defaults to current dir
*/
basePath,
/*
List of compilers
*/
compilers = [],
/*
Patterns list extracted from compilers
*/
patterns = [],
/*
Extensions registered by compilers
*/
extensions = [],
/*
Sad counters :(
*/
doneFiles = 0,
errorFiles = 0,
/*
destination folder to save file
*/
destination,
/*
source folder to look for files
*/
source,
/*
Path of manifest file
*/
_manifestFile = null,
/*
noop.. *shrug*
*/
noop = function(){},
/*
Callback default noop
*/
cb = noop,
/*
gzipOriginal File or not
*/
gzipOriginal = false;
/*
@usage: Returns the last extension of file
*/
var getExtension = function(path){
return path.substr(path.lastIndexOf(".") + 1, path.length)
}
/*
@usage: Replaces extension
*/
var replaceExtension = function(path, oldExt, newExt){
return path.replace(oldExt, newExt);
}
/*
@usage: Returns Files from given glob patterns
*/
var returnAsArray = function(source){
var array_source = [];
if (typeof source == 'string'){
array_source.push(source)
} else {
array_source = source;
}
return array_source;
}
/*
@usage: Grab files with given pattern
*/
var globFilesFromPatterns = function(source, basePath){
var _fileList = [];
var patterns = [];
patterns = returnAsArray(source)
patterns.forEach(function(_pattern){
var _files;
var files_path = path.resolve(basePath, _pattern);
if(_files = glob.sync(files_path)){
_files.forEach(function(_isFile){
if (fs.statSync(_isFile).isFile()){
_fileList.push(_isFile)
}
})
}
})
return _fileList;
}
/*
@usage: Register patterns
*/
var registerPatterns = function(_patterns){
var list;
if (!_patterns){
return false;
}
if ((list = returnAsArray(_patterns)).length > 0 ){
patterns = patterns.concat(list)
}
}
/*
@usage: Register Extensions of files of compilers
*/
var registerExtensions = function(_patterns){
var list;
if ((list = returnAsArray(_patterns)).length > 0 ){
extensions = extensions.concat(list)
}
}
/*
@usage: Validate Compilers config
*/
var getCompilerConfig = function(compilers){
var compilerList = [];
if (!compilers.length){
return compilerList;
}
compilers.map(function(_compiler){
if ((!_compiler.patterns && !_compiler.extensions) || !_compiler.compile){
console.log(String.concat("\t[ ⨯ ]", _compiler.name, "module registration failed").red().white());
} else {
compilerList.push(_compiler);
registerPatterns(_compiler.patterns);
registerExtensions(_compiler.extensions);
}
});
return compilerList;
}
/*
@usage: To check whether the given pattern or ext matches the compiler
_pattern: A regex pattern or an extension
key: pattern || extensions
*/
var getPatternMatchingCompilers = function(_pattern, key){
var _compilers;
if (key != "patterns" && key != "extensions"){
return exitNix("NixError: called getPatternMatchingCompilers without any key, report this error")
}
/*
I hate adding multiple if clauses. :-/
Anyways, never can be a "pattern == extension"
*/
if (patterns.indexOf(_pattern) != -1 || extensions.indexOf(_pattern) != -1){
_compilers = compilers.filter(function(_compiler){
// there can be compilers with only extension or pattern
if (!_compiler[key]){
return false;
}
if (_compiler.strict){
var hasExt = _compiler[key].filter(function(_ext){
return _ext == _pattern
})
if (hasExt.length > 0){
return true;
} else {
return false;
}
} else {
var hasExt = _compiler[key].filter(function(_ext){
// is this a regex?
if (_ext.source){
return _pattern.source == _ext.source
}
// no this is just a string
return (_ext.indexOf(_pattern)!= -1)
})
if (hasExt.length > 0){
return true;
} else {
return false;
}
}
})
if (_compilers.length > 0){
return _compilers;
} else {
return null;
}
} else {
return null;
}
}
/*
@usage: Returns Patterns
*/
var extractPatterns = function(string){
var matchedPatterns = [];
patterns.forEach(function(_pattern){
if (_pattern.test(string)){
var compilers = getPatternMatchingCompilers(_pattern, "patterns");
if (compilers)
matchedPatterns = matchedPatterns.concat(compilers);
}
})
return matchedPatterns;
}
/*
@usage: Helper to be exposed to compilers
*/
var nixExecPatterns = function(file, compilers, manifest){
var patterns = file.extractPatterns(file.content);
patterns.forEach(function(compiler){
compiler.compilePattern(file, compilers, manifest);
})
return file;
}
var nixReturnFileObject = function(file_path, oldFile){
try{
var content = fs.readFileSync(file_path)
var file = {
nixReturnFileObject : oldFile.nixReturnFileObject,
nixExecPatterns : oldFile.nixExecPatterns,
content: content.toString(),
path: file_path,
chainPaths: oldFile.chainPaths,
basePath: oldFile.basePath,
options: oldFile.options,
extractPatterns: extractPatterns,
nixGetFilePath: nixGetFilePath
};
return file;
} catch(e){
throw new Error(e)
}
}
/*
@usage: Returns the file path(if exists)
*/
var nixGetFilePath = function(_path, options){
var basePath = path.resolve(options.basePath, _path);
var current_path = path.resolve(options.current_path, _path);
if (fs.existsSync(basePath) && _path.indexOf("./") == -1){
return basePath
} else if (fs.existsSync(current_path)){
return current_path;
} else {
return false;
}
}
var nixEnsureDirectories = function(_path){
_path = _path.substr(0, _path.lastIndexOf("/"))
var _paths = _path.split("/");
var lastPath = "";
_paths.map(function(path){
try{
var stat = fs.statSync(lastPath + path+"/")
if (stat.isDirectory()){
lastPath += path+"/";
}
} catch(e){
lastPath += path+"/";
fs.mkdirSync(lastPath)
}
})
}
var saveCompiledFiles = function(file, manifest){
if (doesHash){
var hash = crypto.createHash("md5");
hash = hash.update(file.content)
hash = hash.digest('hex');
var key = file.path.replace(path.resolve(destination), "");
manifest[key] = cdnBase + key.substr(0, key.lastIndexOf("."))+ "-" + hash + key.substr(key.lastIndexOf(".")-1, key.length);
}
if (doesGzip){
try{
var gzipData = zlib.gzipSync(file.content, {level: 9})
} catch(e){
console.log("Failed to Gzip", file.path, e)
}
}
var writer = fs.createWriteStream(file.path, "w+");
if (!gzipOriginal){
var _gzipWriter = fs.createWriteStream(file.path+".gz", "w+")
} else {
file.content = gzipData;
}
writer.write(file.content, function(err, data){
if (err){
console.log("Couldn't save", file.path, err)
return process.exit(-1);
}
writer.destroy();
if (!gzipOriginal && doesGzip){
_gzipWriter.write(gzipData, function(err, data){
_gzipWriter.destroy()
if (err){
console.log("Cannot save gzip of", file.path)
}
})
}
_processNextFile();
});
}
/*
@usage: On basis of option, extract manifest
*/
var getManifest = function(_manifest){
if (typeof _manifest == 'string'){
// we have a path for manifest file
_manifestFile = path.resolve(basePath, _manifest);
if (fs.existsSync(_manifestFile)){
manifest = require(_manifestFile);
} else {
manifest = {};
}
} else {
// did you just passed the manifest file to me? Kewl!
manifest = typeof _manifest == "object"?_manifest: {};
}
return manifest;
}
/*
@usage: Returns paths from manifest to replace in files
*/
var manifestHelper = function(path, file_name){
if (manifest){
if (manifest[path]){
return manifest[path];
} else {
console.log(String.concat("\t[ ⨯ ] Can't find", path, "in manifest for", file_name));
return path;
}
} else {
return path;
}
}
/*
@usage: Save the manifest file
*/
var saveManifest = function(){
if (_manifestFile){
var writer = fs.createWriteStream(_manifestFile)
writer.write(JSON.stringify(manifest))
writer.on("finish", function(){
writer.destroy();
})
}
}
/*
@usage: A color coded console logger
*/
var endLog = function(successCount, errorCount, message){
message = message? message : "";
console.log(message.white());
console.log(String.concat("\t[ ✓ ]", successCount.toString(), "files compiled").white().green());
console.log(String.concat("\t[ ⨯ ]", errorCount.toString(), "files errored out").white().red());
}
/*
@usage: Todo: Error logger
*/
var errorLogger = function(fileInfo){
}
/*
@usage: Logs the critical error and exits
*/
var exitNix = function(message){
console.log(message.red().white());
endLog(doneFiles, errorFiles, "Exiting Nix")
return process.exit();
}
/*
:= Actual Flow Starts from here :=
Do we have necessary options to continue?
*/
if (options){
if (!options.source && !options.destination, !options.compilers)
throw new Error("Nix called without passing source, destination and compilers".red().white())
} else {
throw new Error("Nix called without any options".red().white())
}
/*
We will take the process.cwd as base if none is provided
*/
basePath = options.basePath? options.basePath: process.cwd();
destination = options.destination;
compilerOptions = options.options;
source = options.source.substr(0, options.source.indexOf("*"));
/*
Manifest JSON is required in case you are building a prod build
or have arbitary paths to load things from
*/
manifest = options.manifest? getManifest(options.manifest): null;
// Ninja Options!
cdnBase = options.cdnBase || cdnBase;
doesGzip = doesGzip || options.gzip;
doesHash = doesHash || options.hash;
async = async || options.async;
cb = callback || noop;
gzipOriginal = options.gzipOriginal || gzipOriginal;
if ((files = globFilesFromPatterns(options.source, basePath)).length === 0){
return endLog(0, 0, "Black hole passed to me!");
}
/*
Now that we have a file list, we need to build the compilation
configuration
*/
if ((compilers = getCompilerConfig(options.compilers)).length === 0){
return endLog(0, 0, "cannot compile with the compilers passed to me!".red())
}
/*
So, now we have compilers, files list, lets compile them!
*/
if (files.length == 0){
endLog(0, 0, "Meh.. None of matching file found to compile.. Nix!")
process.exit()
}
/*
This homey is core of everything!
It compiles with patterns and compilers
*/
var processFile = function(err, data, file){
var CompiledFile = {
content: data.toString(),
path: file,
destination: destination,
options: compilerOptions,
basePath: basePath,
chainPaths: [file],
notLogged: true,
nixGetFilePath: nixGetFilePath
}
if(err){
return console.log("Cannot read file", file, err)
}
var ext = getExtension(file);
var _compilers;
/*
Search for compilers for this file by extension
@strict mode
*/
if (_compilers = getPatternMatchingCompilers(ext, "extensions")){
// First Compile Patterns
var _patternCompilers;
_patternCompilers = extractPatterns(CompiledFile.content)
if (_patternCompilers){
_patternCompilers.forEach(function(_compiler){
// I don't wanna take risk
CompiledFile.extractPatterns = extractPatterns;
CompiledFile.nixExecPatterns = nixExecPatterns;
CompiledFile.nixReturnFileObject = nixReturnFileObject;
if (_compiler.compilePattern){
console.log(String.concat(_compiler.name).white().green(), String.concat(CompiledFile.path).white())
_compiler.compilePattern(CompiledFile, _compilers, manifestHelper);
} else {
// just warn daug, that the function wasn't there
console.log(String.concat("Yo daug, where is compilePattern function in your pattern helper?").red().white())
}
}) // pattern Compiler dies here!
}
/*
Compile the file with each compiler
*/
_compilers.forEach(function(_compiler){
if (CompiledFile.notLogged)
console.log(String.concat(_compiler.name).white().green(), String.concat(CompiledFile.path).white())
_compiler.compile(CompiledFile, _compilers, manifestHelper);
})
/*
We are done with compilation, lets save the file
*/
var _source = path.resolve(basePath, source);
var _destination = path.resolve(basePath, destination);
var _fpath = _destination+CompiledFile.path.replace(_source, "");
nixEnsureDirectories(_fpath);
CompiledFile.path = _fpath;
return saveCompiledFiles(CompiledFile, manifest);
} else {
console.log(String.concat("Skipped", file, "as no matching compiler for", ext, "extensions").red().white())
_processNextFile()
}
}
var _processNextFile = function(){
var file = files.shift();
if (!file){
saveManifest()
return cb(manifest);
}
// this is dead end, no turning back
// we have to fight the war or die trying!
try{
if (async){
fs.readFile(file, function(err, data){
return processFile(err, data, file)
})
} else {
var data = fs.readFileSync(file);
processFile(null, data, file)
}
} catch (err){
console.log(String.concat("Oops, something broke for", file, err.stack).red().white())
}
}
_processNextFile();
//console.log("Saving Compiled File, hold on!".green().white())
}
module.exports = Nix;