-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathifopt.js
689 lines (589 loc) · 19.9 KB
/
ifopt.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
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
require('nativejs-proto-extensions');
let ifopt = {
// @TODO: Make arg validation of functions
/**
* @var {Boolean} colorize Indicating to not use color in log ouputs.
*/
colorize: true,
/**
* @var {Object} colors Default Color of ifopt.
*/
colors: {
Restore: "[xlb]",
Reset: "\x1b[0m",
Bright: "\x1b[1m",
Dim: "\x1b[2m",
Underscore: "\x1b[4m",
Blink: "\x1b[5m",
Reverse: "\x1b[7m",
Hidden: "\x1b[8m",
fg: {
Black: "\x1b[30m",
Red: "\x1b[31m",
Green: "\x1b[32m",
Yellow: "\x1b[33m",
Blue: "\x1b[34m",
Magenta: "\x1b[35m",
Cyan: "\x1b[36m",
White: "\x1b[37m",
Crimson: "\x1b[38m",
Success: "\x1b[32m",
Error: "\x1b[31m",
Info: "\x1b[36m",
Warning: "\x1b[33m",
Debug: "\x1b[38;5;208m"
},
bg: {
Black: "\x1b[40m",
Red: "\x1b[41m",
Green: "\x1b[42m",
Yellow: "\x1b[43m",
Blue: "\x1b[44m",
Magenta: "\x1b[45m",
Cyan: "\x1b[46m",
White: "\x1b[47m",
Crimson: "\x1b[48m",
Success: "\x1b[42m",
Error: "\x1b[41m",
Info: "\x1b[46m",
Warning: "\x1b[43m",
Debug: "\x1b[38;5;208m"
}
},
/**
* @var {String} separator Default separator for arguments.
*/
separator: ",",
/**
* @var {String} shortopt Memorized short options.
*/
shortopt: "",
/**
* @var {Array} longopt Memorized list of long options.
*/
longopt: [],
/**
* @var {Array} implicits Memorized list of property name of implicit
* arguments.
*/
implicits: [],
/**
* @var {Object} implicitRefs Memorized of object reference to bridge
* value of implicit arguments.
*/
implicitRefs: null,
/**
* @var {Object} levels Logging levels
*/
levels: {
},
/**
* @var {Object} smartLogging Log level rule to manage display.
*/
smartLogging: {
},
/**
* @var {boolean} selfDebug To display debug message of ifopt.
*/
selfDebug: false,
/**
* Set options to parse without parsing them.
*
* @param {String} sopt Short Options
* @param {Array} lopt Long Options
* @param {Array} implicitNames (Optional) Name of property as implicit
* argument
* @param {Object} implicitRefs (Optional) Object reference to brigde with
* caller
*
* @return {boolean}
*/
setOpts: function (
sopt,
lopt,
implicitNames = [],
implicitRefs = {}
) {
ifopt.setShortOpt(sopt);
ifopt.setLongOpt(lopt);
ifopt.setImplicitOpt(implicitNames, implicitRefs);
return true;
},
/**
* Set the short options for the instance.
*
* @param {String} sopt Provided short options string.
*
* @return {boolean}
*/
setShortOpt: function (sopt) {
ifopt.shortopt = sopt;
return true;
},
/**
* Set the long options for the instance.
*
* @param {Array} lopt Provided long options list.
*
* @return {boolean}
*/
setLongOpt: function (lopt) {
ifopt.longopt = lopt;
return true;
},
/**
* Set the implicit argument of the program (name and ref object).
*
* @param {Array} implicitNames Name of properties of ref object.
* @param {Object} implicitRefs Object Reference.
*
* @return {boolean}
*/
setImplicitOpt: function (implicitNames, implicitRefs) {
ifopt.implicits = implicitNames;
ifopt.implicitRefs = implicitRefs;
return true;
},
/**
* Set the separator to split an option.
*
* @param {String} sep The separator char.
*
* @return {boolean}
*/
setSeparator: function (sep) {
ifopt.separator = sep;
return true;
},
/**
* Get the current color object configuration.
*
* @return {Object|{fg: {Red: string, Cyan: string, White: string, Yellow: string, Blue: string, Magenta: string, Black: string, Crimson: string, Green: string}, Reverse: string, bg: {Red: string, Cyan: string, White: string, Yellow: string, Blue: string, Magenta: string, Black: string, Crimson: string, Green: string}, Blink: string, Dim: string, Hidden: string, Underscore: string, Reset: string, Bright: string}}
*/
getColors: function () {
return ifopt.colors;
},
/**
* Return the color string for specified path
*
* @param colorPty Path of the color in property ifopt.colors.
*
* @return {*}
*/
getColor: function (colorPty) {
return ifopt.colors.getValueForPath(colorPty);
},
/**
* Set the new object colors configuration.
* Use getColors first, perform modification and update with this method.
*
* @param {Object|{fg: {Red: string, Cyan: string, White: string, Yellow: string, Blue: string, Magenta: string, Black: string, Crimson: string, Green: string}, Reverse: string, bg: {Red: string, Cyan: string, White: string, Yellow: string, Blue: string, Magenta: string, Black: string, Crimson: string, Green: string}, Blink: string, Dim: string, Hidden: string, Underscore: string, Reset: string, Bright: string}} colors
*/
setColors: function (colors) {
ifopt.colors = colors;
},
/**
* Set/Update a color specifying its property path
*
* @param {String} colorPty The object property path (fg.Yellow)
* @param {String} color Bash Color Instruction
*
* @return {boolean}
*/
setColor: function (colorPty, color) {
let newColor = ifopt.colors;
let newColorRef = newColor;
colorPty = colorPty.split(".");
for (let i = 0; i < colorPty.length; i++) {
let pty = colorPty[i];
if (i === (colorPty.length - 1)) {
newColorRef[pty] = color;
} else{
if (!newColorRef[pty]) {
newColorRef[pty] = {};
}
newColorRef = newColorRef[pty];
}
}
Object.assign(ifopt.colors, newColor);
return true;
},
/**
* Neutralize colors controls to blank.
* If called without parameter, the defined colors for ifopt
* instance are neutralize. You can passe your colors object definition
* (copy from ifopt one using getColors()).
*
* @param {Object} colors Colors object definition (optional)
*
* @return {*}
*/
removeColor: function (colors = ifopt.colors) {
let removed = Object.assign({}, colors);
for (let pty in removed) {
if (removed.hasOwnProperty(pty)) {
if (typeof removed[pty] === 'string') {
removed[pty] = '';
}
if (removed[pty] instanceof Object) {
removed[pty] = ifopt.removeColor(removed[pty]);
}
}
}
return removed;
},
/**
* Set log message will not use colors.
*
* @return {boolean}
*/
noColor: function () {
ifopt.colorize = false;
return true;
},
/**
* Set if log message use colors.
* If called without parameters, meaning true, use colors.
*
* @param {boolean} usage Use color (or not (false))
*
* @return {boolean}
*/
useColor: function (usage = true) {
ifopt.colorize = (usage);
return true;
},
/**
* Traiter les arguments passé au programme
*
* @param shortopt Définition des options courtes.
* @param longopt Définition des options longues.
* @param implicits Définition des paramètre implicite.
* @param implicitRefs Objet de référence pour passer les valeurs.
*
* @returns {{}} Options parsées.
*/
getopt: function (shortopt, longopt, implicits, implicitRefs) {
shortopt = shortopt || ifopt.shortopt;
longopt = longopt || ifopt.longopt;
implicits = implicits || ifopt.implicits;
implicitRefs = implicitRefs || ifopt.implicitRefs;
ifopt.shortopt = shortopt;
ifopt.longopt = longopt;
ifopt.implicits = implicits;
ifopt.implicitRefs = implicitRefs;
ifopt.checkShortopt(shortopt);
let processedArg = 0;
let implicitArg = 1;
let procOptions = {}; // .optarg, .opt, .optval
let runWithoutError = true;
process.argv.forEach(function(arg) {
processedArg++;
// Skip Interpreter (node.exe) and it self (mdmerge.js)
if (processedArg < 3) return;
// Check if it is a explicit argument (longopt).
if (/^--/.test(arg)) {
let splitOpt = arg.match(/^--([a-zA-Z0-9._-]+)=?(.*)/);
if (!splitOpt) return;
let opt = splitOpt[1];
let optVal = splitOpt[2];
for(let i = 0; i < longopt.length; i++) {
let lgOpt = longopt[i].match(/([a-zA-Z0-9._-]+)(:*)/);
let lgOptName = lgOpt[1];
let lgOptConfig = lgOpt[2];
if (opt === lgOptName) {
if (lgOptConfig === ':' && !optVal) {
ifopt.log(`Option %s require a value`, 1, [opt]);
runWithoutError = false;
}
if (procOptions[opt]) {
procOptions = ifopt.appendOption(procOptions, arg, opt, optVal);
} else {
procOptions[opt] = ifopt.createOption(arg, opt, optVal);
}
}
}
}
// Check if it is a explicit argument (shortopt).
else if (/^-/.test(arg)) {
let opt = arg.substr(1, 1);
let optIdx = shortopt.indexOf(opt);
let optVal = arg.match(/^-(.+)=(.*)/);
if (optVal) optVal = optVal[2];
if (optIdx < 0 ) return;
let nextOptChar1 = shortopt.substr(optIdx +1, 1);
let nextOptChar2 = shortopt.substr(optIdx +2, 1);
if (nextOptChar1 === ':' && nextOptChar2 !== ':' && !optVal) {
ifopt.log(`Option %s require a value`, 1, [opt]);
runWithoutError = false;
}
if (procOptions[opt]) {
procOptions = ifopt.appendOption(procOptions, arg, opt, optVal);
} else {
procOptions[opt] = ifopt.createOption(arg, opt, optVal);
}
}
// This is an implicit argument.
else {
// Check if there is an implicit argument
if (implicits[implicitArg - 1]) {
let implicitPty = implicits[implicitArg - 1];
implicitRefs[implicitPty] = arg;
}
implicitArg++;
}
});
if (runWithoutError) {
return procOptions;
} else {
process.exit();
}
},
// @TODO validation de la chaine shortopt pour limiter les doublons
checkShortopt: function() {
},
/**
* Créer une option parsée pour utilisation ultérieure.
*
* @param optarg Option d'origine passée en argument.
* @param opt Option isolée.
* @param optval Valeur de l'option.
*
* @returns {{optarg: *, opt: *, optval: *}}
*/
createOption: function (optarg, opt, optval) {
return {
"arg": optarg,
"opt": opt,
"val": optval
};
},
/**
* Afficher un message dans le stream.
*
* @param message Message à afficher.
* @param level Niveau de message. 0=OK,1=KO,2=WARN.
* @param args Arguments which will replace placeholder in message.
* @param ignoreSmartLog Ignore smartLog rules.
*
* @return {number}
*/
log: function (message = '', level = 0, args = [], ignoreSmartLog = false){
let lvlConf = ifopt.levels[level];
let display = true;
let colors = (ifopt.colorize) ? ifopt.colors : ifopt.removeColor();
// Replace Placeholders.
let argi = 0;
args.map(function (arg) {
argi++;
arg = colors.fg.Yellow + arg + colors.Reset;
arg = arg.split(colors.Restore).join(colors.fg.Yellow);
if (/%[1-9]+\$s/.test(message)) {
let regexp = new RegExp(`%${argi}\\$s`);
message = message.replace(regexp, arg)
} else {
message = message.replace(/%s/, arg);
}
});
// Check "smartLogin"
for (let group in ifopt.smartLogging) {
if (group === 'getValueForPath') continue;
let enabled = ifopt.smartLogging[group].enabled;
let levels = ifopt.smartLogging[group].levels;
if (levels.lastIndexOf(level) >= 0) {
display = enabled;
break;
}
}
if (display || ignoreSmartLog) {
console.log(
"[ " +
lvlConf.color +
lvlConf.name +
colors.Reset +
" ] : " +
message.split(colors.Restore).join(colors.Reset)
);
}
return lvlConf.return;
},
/**
* Create logging level for STDx. Will display specified name and color.
*
* @param {number} level Level number (must be unique)
* @param {string} name Display logging name.
* @param {string} color Path to the color of ifopt.colors (check ifopt.getColors())
* @param {number} lreturn Return code for the logging level
*
* @return {boolean}
*/
createLogLevel: function (level, name, color = 'Reset', lreturn = 0) {
// Check if level does not exist.
if (ifopt.levels.hasOwnProperty(level)) {
let levelName = ifopt.getValueForPath(`levels.${level}.name`);
ifopt.log("Log level %s already exist (name: %s). Logging level will be overwrited.", 2, [level, levelName]);
}
ifopt.levels[level] = {
name: name,
color: ifopt.colors.getValueForPath(color),
return: lreturn
};
return true;
},
/**
* Set display behavior for log() function using group, enabling boolean
* for specified levels
*
* @param groupName Levels groupname to handle them
* @param groupEnabled If false, levels will not display when calling log()
* @param levels Levels of the group
*
* @return {boolean}
*/
setLogLevel: function (groupName, groupEnabled = false, levels = []) {
if (!(typeof groupName === 'string')) {
ifopt.log(
"%s is not string",
1,
["setLogLevel() groupName"]
);
return false;
}
if (ifopt.selfDebug) {
ifopt.log("groupName : %s", 4, [groupName])
ifopt.log("groupEnabled '%s'(%s) => %s", 4, [
groupEnabled, typeof groupEnabled, !!(groupEnabled)
]);
}
groupEnabled = !!(groupEnabled);
levels = (typeof levels !== 'object') ? [levels] : levels;
if (ifopt.selfDebug) {
ifopt.log("levels :", 4);
console.log(levels);
}
if (ifopt.smartLogging[groupName]){
ifopt.smartLogging[groupName].enabled = groupEnabled;
if (levels.length > 0) {
ifopt.smartLogging[groupName].levels = levels;
}
} else {
ifopt.smartLogging[groupName] = {
enabled: groupEnabled,
levels: levels
};
}
if (ifopt.selfDebug) {
ifopt.log("smartLogging :", 4);
console.dir(ifopt.smartLogging, {depth: null})
}
return true;
},
/**
* Aggregate value under a option when user use multiple times the same options.
*
* @param {Object} optstack
* @param {String} optagr Entered option (short or long)
* @param {String} opt Option Name
* @param {String} optval Option Value
*
* @returns {Array} Return aggregated value for the option.
*/
appendOption: function (optstack, optagr, opt, optval) {
if (!(optstack[opt].val instanceof Array)) {
optstack[opt].val = [optstack[opt].val];
}
optstack[opt].val.push(optval);
return optstack;
},
/**
* Check the option/list of options are provided in the command line.
*
* @param {String|Array} opts Option/List of options
* @param {String} op or|and operator telling if all option are require
* or at least one.
* @returns {boolean}
*/
isOption: function (opts, op = "or") {
opts = !(opts instanceof Array) ? [].push(opts) : opts;
let returnOp = (op.toLowerCase() !== 'or');
let OPTS = ifopt.getopt();
for (let i = 0; i < opts.length; i++) {
let opt = opts[i];
if (OPTS[opt]) {
if (op.toLowerCase() === 'or') {
return true;
}
} else {
if (op.toLowerCase() === 'and') {
return false;
}
}
}
return returnOp;
},
/**
* Get all values under a unique list for provided options.
*
* @param {Array} opts List of options names.
*
* @returns {Array} List of values.
*/
getOptsValues: function (opts) {
let outputArray = [];
for (let i in opts) {
let opt = opts[i];
if (ifopt.isOption([opt])) {
outputArray = ifopt.optToArray(ifopt.getopt(), opt, outputArray);
}
}
return outputArray;
},
/**
* Return the value of the first options specified in the array.
*
* @param {String|Array} opts Options to get value
*
* @return {[*]|boolean} The returned value or false if not found.
*/
getOptValue: function (opts) {
let options = ifopt.getopt();
if (!(opts instanceof Array)) {
opts = [opts]
}
for (let i = 0; i < opts.length; i++) {
if (options[opts[i]]) {
return options[opts[i]].val;
}
}
return false;
},
/**
* Aggregate values of specified options to list of value (merge shortopt and longopt)
*
* @param {Array} optpool Program options data.
* @param {String} name Name of this option (short or long).
* @param {Array} outputArray Existing data list to aggregate in.
*
* @returns {Array} List of values.
*/
optToArray: function (optpool, name, outputArray) {
if (optpool[name]) {
if (optpool[name].val instanceof Array) {
outputArray = outputArray.concat(optpool[name].val);
} else {
outputArray = outputArray.concat([optpool[name].val])
}
}
return outputArray;
}
};
/**
* Initialization
*/
// Set own logging levels
ifopt.createLogLevel(0, 'SUCCESS', 'fg.Success', 0);
ifopt.createLogLevel(1, 'ERROR', 'fg.Error', 1);
ifopt.createLogLevel(2, 'WARNING', 'fg.Warning', 0);
ifopt.createLogLevel(3, 'INFO', 'fg.Info', 0);
ifopt.createLogLevel(4, 'DEBUG', 'fg.Debug', 0);
module.exports = ifopt;