This repository has been archived by the owner on Jan 13, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 72
/
level.js
1255 lines (1038 loc) · 37.1 KB
/
level.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
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
var PATH = require('./path'),
FS = require('fs'),
INHERIT = require('inherit'),
createTech = require('./tech').createTech,
bemUtil = require('./util'),
LOGGER = require('./logger'),
isRequireable = bemUtil.isRequireable,
getLevelClass = function(path, optional) {
var level = optional && !isRequireable(path) ? {} : requireLevel(path);
if (level.Level) return level.Level;
return INHERIT(level.baseLevelPath? getLevelClass(level.baseLevelPath) : Level, level);
},
requireLevel = function(path) {
return bemUtil.requireWrapper(require)(path, true);
},
levelCache = {},
useCache = false,
exceptLevels = [],
allRe = /(?:^([^_.\/]+)\/__([^_.\/]+)\/(?:_([^_.\/]+)\/\1__\2_\3(?:_([^_.\/]+))?|\1__\2)(.*?)$|^([^_.\/]+)\/(?:(?:\6)|(?:_([^_.\/]+)\/\6_\7(?:_([^_.\/]+))?))(.*?)$)/,
elemAllRe = /^([^_.\/]+)\/__([^_.\/]+)\/(?:_([^_.\/]+)\/\1__\2_\3(?:_([^_.\/]+))?|\1__\2)(.*?)$/,
blockAllRe = /^([^_.\/]+)\/(?:(?:\1)|(?:_([^_.\/]+)\/\1_\2(?:_([^_.\/]+))?))(.*?)$/;
/**
* Create level object from path on filesystem.
*
* @param {String | Object} level Path to level directory.
* @param {Object} [opts] Optional parameters
* @return {Level} Level object.
*/
exports.createLevel = function(level, opts) {
// NOTE: в директории .bem внутри уровня переопределения
// лежит модуль-конфиг для уровня переопределения
var path = level.path || level;
opts = opts || {};
if (!opts.noCache && levelCache[path]) return levelCache[path];
level = new (getLevelClass(PATH.resolve(path, '.bem', 'level.js'), true))(level, opts);
levelCache[path] = level;
return level;
};
exports.setCachePolicy = function(useCacheByDefault, except) {
useCache = useCacheByDefault;
exceptLevels = except || [];
};
exports.resetLevelsCache = function(all) {
for(var l in levelCache) {
var level = levelCache[l];
if (!level.cache || all) level.files = null;
}
};
var Level = exports.Level = INHERIT(/** @lends Level.prototype */{
/**
* Construct an instance of Level.
*
* @class Level base class.
* @constructs
* @param {String | Object} path Level directory path.
* @param {Object} [opts] Optional parameters
*/
__constructor: function(path, opts) {
opts = opts || {};
this.dir = PATH.resolve(path.path || path);
this.projectRoot = opts.projectRoot || PATH.resolve('');
// NOTE: keep this.path for backwards compatibility
this.path = this.bemDir = PATH.join(this.dir, '.bem');
path = PATH.relative(this.projectRoot, this.dir);
this.cache = useCache;
for(var e in exceptLevels) {
var except = exceptLevels[e];
if (path.substr(0, except.length) === except) {
this.cache = !this.cache;
break;
}
}
// NOTE: tech modules cache
this._techsCache = {};
},
/**
* Return level type.
*
* Default is `['level']`.
*
* @return {String[]}
*/
getTypes: function() {
return ['level'];
},
/**
* Place to store uncommon level configurations
*
* @return {Object}
*/
getConfig: function() {
return {};
},
/**
* Tech module definitions for level
*
* @return {Object} Tech module definitions
*/
getTechs: function() {
// NOTE: this.techs is for backwards compatibility with legacy level configs
return this.techs || {};
},
/**
* Get tech object from its name and optional path to tech module.
*
* Object will be created and stored in cache. All following calls
* to getTech() with same name will return the same object.
*
* Is you need unique object every time, use createTech() method
* with same signature.
*
* @param {String} name Tech name
* @param {String} [path] Path to tech module
* @return {Tech}
*/
getTech: function(name, path) {
if(!this._techsCache.hasOwnProperty(name)) {
this._techsCache[name] = this.createTech(name, path || name);
}
return this._techsCache[name];
},
/**
* Create tech object from its name and optional path to tech module.
*
* @param {String} name Tech name
* @param {String} [path] Path to tech module
* @return {Tech}
*/
createTech: function(name, path) {
return createTech(this.resolveTech(path || name), name, this);
},
/**
* Resolve tech identifier into tech module path.
*
* @param {String} techIdent Tech identifier.
* @param {Boolean} [force] Flag to not use tech name resolution.
* @return {String} Tech module path.
*/
resolveTech: function(techIdent, force) {
if(bemUtil.isPath(techIdent)) {
return this.resolveTechPath(techIdent);
}
if(!force && this.getTechs().hasOwnProperty(techIdent)) {
return this.resolveTechName(techIdent);
}
return bemUtil.getBemTechPath(techIdent);
},
/**
* Resolve tech name into tech module path.
*
* @param {String} techName Tech name.
* @return {String} Tech module path.
*/
resolveTechName: function(techName) {
var p = this.getTechs()[techName];
return typeof p !== 'undefined'? this.resolveTech(p, true) : null;
},
/**
* Resolve tech module path.
*
* @throws {Error} In case when tech module is not found.
* @param {String} techPath Tech path (relative or absolute).
* @return {String} Tech module path.
*/
resolveTechPath: function(techPath) {
// Get absolute path if path starts with "."
// NOTE: Can not replace check to !isAbsolute()
if(techPath.substring(0, 1) === '.') {
// Resolve relative path starting at level `.bem/` directory
techPath = PATH.join(this.bemDir, techPath);
/* jshint -W109 */
if(!isRequireable(techPath)) {
throw new Error("Tech module on path '" + techPath + "' not found");
}
/* jshint +W109 */
return techPath;
}
// Trying absolute of relative-without-dot path
if(isRequireable(techPath)) {
return techPath;
}
/* jshint -W109 */
try {
return require.resolve('./' + PATH.join('./techs', techPath));
} catch (err) {
throw new Error("Tech module with path '" + techPath + "' not found on require search paths");
}
/* jshint +W109 */
},
/**
* Get list of default techs to create with `bem create {block,elem,mod}`
* commands.
*
* Returns all declared techs in `defaultTechs` property or keys of result
* of `getTech()` method if `defaultTechs` is undefined.
*
* @return {String[]} Array of tech names.
*/
getDefaultTechs: function() {
return this.defaultTechs || Object.keys(this.getTechs());
},
/**
* Resolve relative paths using level config directory `.bem/`
* as a base for them.
*
* Absolute paths (and keys of object) will be left untouched.
* Returns new Array of strings or Object.
*
* @param {Object|String[]} paths Paths to resolve.
* @return {Object|String[]} Resolved paths.
*/
resolvePaths: function(paths) {
// resolve array of paths
if (Array.isArray(paths)) {
return paths.map(function(path) {
return this.resolvePath(path);
}, this);
}
// resolve paths in object values
var resolved = {};
Object.keys(paths).forEach(function(key) {
resolved[key] = this.resolvePath(paths[key]);
}, this);
return resolved;
},
/**
* Resolve relative path using level config directory `.bem/`
* as a base.
*
* Absolute path will be left untouched.
*
* @param {String} path Path to resolve.
* @return {String} Resolved path.
*/
resolvePath: function(path) {
return PATH.resolve(this.path, path);
},
/**
* Construct path to tech file / directory from
* prefix and tech name.
*
* @param {String} prefix Path prefix.
* @param {String} tech Tech name.
* @return {String} Absolute path.
*/
getPath: function(prefix, tech) {
return this.getTech(tech).getPath(prefix);
},
getPaths: function(prefix, tech) {
return (typeof tech === 'string'? this.getTech(tech): tech).getPaths(prefix);
},
/**
* Construct absolute path to tech file / directory from
* BEM entity object and tech name.
*
* @param {Object} item BEM entity object.
* @param {String} item.block Block name.
* @param {String} item.elem Element name.
* @param {String} item.mod Modifier name.
* @param {String} item.val Modifier value.
* @param {String} tech Tech name.
* @return {String} Absolute path.
*/
getPathByObj: function(item, tech) {
return PATH.join(this.dir, this.getRelPathByObj(item, tech));
},
/**
* Construct relative path to tech file / directory from
* BEM entity object and tech name.
*
* @param {Object} item BEM entity object.
* @param {String} item.block Block name.
* @param {String} item.elem Element name.
* @param {String} item.mod Modifier name.
* @param {String} item.val Modifier value.
* @param {String} tech Tech name.
* @return {String} Relative path.
*/
getRelPathByObj: function(item, tech) {
return this.getPath(this.getRelByObj(item), tech);
},
getFileByObjIfExists: function(item, tech) {
if (!this.files) return;
var blocks = this.files.tree,
block = blocks[item.block];
if (!block) return [];
if (item.mod && !item.elem) {
block = block.mods[item.mod];
if (block && item.val) block = block.vals[item.val];
} else if (item.elem) {
block = block.elems[item.elem];
if (block && item.mod) {
block = block.mods[item.mod];
if (block && item.val) block = block.vals[item.val];
}
}
var files = block? block.files: null;
if (!files || files.length === 0) return [];
var suffixes = tech.getSuffixes(),
res = [];
for(var i = 0; i < suffixes.length; i++) {
var suffix = suffixes[i],
filesBySuffix = files[suffix];
if (filesBySuffix) res = res.concat(filesBySuffix);
}
return res;
},
/**
* Get absolute path prefix on the filesystem to specified
* BEM entity described as an object with special properties.
*
* @param {Object} item BEM entity object.
* @param {String} item.block Block name.
* @param {String} item.elem Element name.
* @param {String} item.mod Modifier name.
* @param {String} item.val Modifier value.
* @return {String} Absolute path prefix.
*/
getByObj: function(item) {
return PATH.join(this.dir, this.getRelByObj(item));
},
/**
* Get relative to level directory path prefix on the filesystem
* to specified BEM entity described as an object with special
* properties.
*
* @param {Object} item BEM entity object.
* @param {String} item.block Block name.
* @param {String} item.elem Element name.
* @param {String} item.mod Modifier name.
* @param {String} item.val Modifier value.
* @return {String} Relative path prefix.
*/
getRelByObj: function(item) {
var getter, args;
if (item.block) {
getter = 'block';
args = [item.block];
if (item.elem) {
getter = 'elem';
args.push(item.elem);
}
if (item.mod) {
getter += '-mod';
args.push(item.mod);
if (item.val) {
getter += '-val';
args.push(item.val);
}
}
return this.getRel(getter, args);
}
return '';
},
/**
* Get absolute path prefix on the filesystem to specified
* BEM entity described as a pair of entity type and array.
*
* @param {String} what BEM entity type.
* @param {String[]} args Array of BEM entity meta.
* @return {String}
*/
get: function(what, args) {
return PATH.join(this.dir, this.getRel(what, args));
},
/**
* Get relative to level directory path prefix on the
* filesystem to specified BEM entity described as a pair
* of entity type and array.
*
* @param what
* @param args
* @return {String}
*/
getRel: function(what, args) {
return this['get-' + what].apply(this, args);
},
/**
* Get relative path prefix for block.
*
* @param {String} block Block name.
* @return {String} Path prefix.
*/
'get-block': function(block) {
return PATH.join.apply(null, [block, block]);
},
/**
* Get relative path prefix for block modifier.
*
* @param {String} block Block name.
* @param {String} mod Modifier name.
* @return {String} Path prefix.
*/
'get-block-mod': function(block, mod) {
return PATH.join.apply(null,
[block,
'_' + mod,
block + '_' + mod]);
},
/**
* Get relative path prefix for block modifier-with-value.
*
* @param {String} block Block name.
* @param {String} mod Modifier name.
* @param {String} val Modifier value.
* @return {String} Path prefix.
*/
'get-block-mod-val': function(block, mod, val) {
return PATH.join.apply(null,
[block,
'_' + mod,
block + '_' + mod + '_' + val]);
},
/**
* Get relative path prefix for elem.
*
* @param {String} block Block name.
* @param {String} elem Element name.
* @return {String} Path prefix.
*/
'get-elem': function(block, elem) {
return PATH.join.apply(null,
[block,
'__' + elem,
block + '__' + elem]);
},
/**
* Get relative path prefix for element modifier.
*
* @param {String} block Block name.
* @param {String} elem Element name.
* @param {String} mod Modifier name.
* @return {String} Path prefix.
*/
'get-elem-mod': function(block, elem, mod) {
return PATH.join.apply(null,
[block,
'__' + elem,
'_' + mod,
block + '__' + elem + '_' + mod]);
},
/**
* Get relative path prefix for element modifier-with-value.
*
* @param {String} block Block name.
* @param {String} elem Element name.
* @param {String} mod Modifier name.
* @param {String} val Modifier value.
* @return {String} Path prefix.
*/
'get-elem-mod-val': function(block, elem, mod, val) {
return PATH.join.apply(null,
[block,
'__' + elem,
'_' + mod,
block + '__' + elem + '_' + mod + '_' + val]);
},
/**
* Get regexp string to match parts of path that represent
* BEM entity on filesystem.
*
* @return {String}
*/
matchRe: function() {
return '[^_.' + PATH.dirSepRe + ']+';
},
/**
* Get order of matchers to apply during introspection.
*
* @return {String[]} Array of matchers names.
*/
matchOrder: function() {
return ['elem-all', 'block-all', 'elem-mod-val', 'elem-mod', 'block-mod-val',
'block-mod', 'elem', 'block'];
},
/**
* Get order of techs to match during introspection.
*
* @return {String[]} Array of techs names.
*/
matchTechsOrder: function() {
return Object.keys(this.getTechs());
},
/**
* Match path against all matchers and return first match.
*
* Match object will contain `block`, `suffix` and `tech` fields
* and can also contain any of the `elem`, `mod` and `val` fields
* or all of them.
*
* @param {String} path Path to match (absolute or relative).
* @return {Boolean|Object} BEM entity object in case of positive match and false otherwise.
*/
matchAny: function(path) {
if (PATH.isAbsolute(path)) path = PATH.relative(this.dir, path);
var matchTechs = this.matchTechsOrder().map(function(t) {
return this.getTech(t);
}, this);
return this.matchOrder().reduce(function(match, matcher) {
// Skip if already matched
if (match) return match;
// Try matcher
match = this.match(matcher, path);
// Skip if not matched
if (!match) return false;
// Try to match for tech
match.tech = matchTechs.reduce(function(tech, t) {
if (tech || !t.matchSuffix(match.suffix)) return tech;
return t.getTechName();
}, match.tech);
return match;
}.bind(this), false);
},
/**
* Match ralative path against specified matcher.
*
* Match object will contain `block` and `suffix` fields and
* can also contain any of the `elem`, `mod` and `val` fields
* or all of them.
*
* @param {String} what Matcher to match against.
* @param {String} path Path to match.
* @return {Boolean|Object} BEM entity object in case of positive match and false otherwise.
*/
match: function(what, path) {
return this['match-' + what].call(this, path);
},
/**
* Match if specified path represents block entity.
*
* Match object will contain `block` and `suffix` fields.
* @param {String} path Path to match.
* @return {Boolean|Object} BEM block object in case of positive match and false otherwise.
*/
'match-block': function(path) {
var match = new RegExp(['^(' + this.matchRe() + ')',
'\\1(.*?)$'].join(PATH.dirSepRe)).exec(path);
if (!match) return false;
return {
block: match[1],
suffix: match[2]
};
},
/**
* Match if specified path represents block modifier entity.
*
* Match object will contain `block`, `mod` and `suffix` fields.
*
* @param {String} path Path to match.
* @return {Boolean|Object} BEM block modifier object in case of positive match and false otherwise.
*/
'match-block-mod': function(path) {
var m = this.matchRe(),
match = new RegExp(['^(' + m + ')',
'_(' + m + ')',
'\\1_\\2(.*?)$'].join(PATH.dirSepRe)).exec(path);
if (!match) return false;
return {
block: match[1],
mod: match[2],
suffix: match[3]
};
},
/**
* Match if specified path represents block modifier-with-value entity.
*
* Match object will contain `block`, `mod`, `val` and `suffix` fields.
*
* @param {String} path Path to match.
* @return {Boolean|Object} BEM block modifier-with-value object in case of positive match and false otherwise.
*/
'match-block-mod-val': function(path) {
var m = this.matchRe(),
match = new RegExp(['^(' + m + ')',
'_(' + m + ')',
'\\1_\\2_(' + m + ')(.*?)$'].join(PATH.dirSepRe)).exec(path);
if (!match) return false;
return {
block: match[1],
mod: match[2],
val: match[3],
suffix: match[4]
};
},
'match-block-all': function(path) {
var match = blockAllRe.exec(path);
if (!match) return false;
var res = {
block: match[1]
};
if (match[2]) {
res.mod = match[2];
if (match[3]) res.val = match[3];
}
if (match[4]) res.suffix = match[4];
return res;
},
'get-block-all': function() {
},
'get-elem-all': function() {
},
/**
* Match if specified path represents element entity.
*
* Match object will contain `block`, `elem` and `suffix` fields.
*
* @param {String} path Path to match.
* @return {Boolean|Object} BEM element object in case of positive match and false otherwise.
*/
'match-elem': function(path) {
var m = this.matchRe(),
match = new RegExp(['^(' + m + ')',
'__(' + m + ')',
'\\1__\\2(.*?)$'].join(PATH.dirSepRe)).exec(path);
if (!match) return false;
return {
block: match[1],
elem: match[2],
suffix: match[3]
};
},
/**
* Match if specified path represents element modifier entity.
*
* Match object will contain `block`, `elem`, `mod` and `suffix` fields.
*
* @param {String} path Path to match.
* @return {Boolean|Object} BEM element modifier object in case of positive match and false otherwise.
*/
'match-elem-mod': function(path) {
var m = this.matchRe(),
match = new RegExp(['^(' + m + ')',
'__(' + m + ')',
'_(' + m + ')',
'\\1__\\2_\\3(.*?)$'].join(PATH.dirSepRe)).exec(path);
if (!match) return false;
return {
block: match[1],
elem: match[2],
mod: match[3],
suffix: match[4]
};
},
/**
* Match if specified path represents element modifier-with-value entity.
*
* Match object will contain `block`, `elem`, `mod`, `val` and `suffix` fields.
*
* @param {String} path Path to match.
* @return {Boolean|Object} BEM element modifier-with-value object in case of positive match and false otherwise.
*/
'match-elem-mod-val': function(path) {
var m = this.matchRe(),
match = new RegExp(['^(' + m + ')',
'__(' + m + ')',
'_(' + m + ')',
'\\1__\\2_\\3_(' + m + ')(.*?)$'].join(PATH.dirSepRe)).exec(path);
if (!match) return false;
return {
block: match[1],
elem: match[2],
mod: match[3],
val: match[4],
suffix: match[5]
};
},
'match-elem-all': function(path) {
var match = elemAllRe.exec(path);
if (!match) return false;
var res = {
block: match[1],
elem: match[2]
};
if (match[3]) res.mod = match[3];
if (match[4]) res.val = match[4];
if (match[5]) res.suffix = match[5];
return res;
},
'match-all': function(path) {
var match = allRe.exec(path);
if (!match) return false;
var res = {};
if (match[1]) {
res.block = match[1];
res.elem = match[2];
if (match[3]) res.mod = match[3];
if (match[4]) res.val = match[4];
if (match[5]) res.suffix = match[5];
} else if (match[6]) {
res.block = match[6];
if (match[7]) {
res.mod = match[7];
if (match[8]) res.val = match[8];
}
if (match[9]) res.suffix = match[9];
}
return res;
},
/**
* Get declaration for block.
*
* @param {String} blockName Block name to get declaration for.
* @return {Object} Block declaration object.
*/
getBlockByIntrospection: function(blockName) {
// TODO: support any custom naming scheme, e.g. flat, when there are
// no directories for blocks
var decl = this.getDeclByIntrospection(PATH.dirname(this.get('block', [blockName])));
return decl.length? decl.shift() : {};
},
/**
* Get declaration of level directory or one of its subdirectories.
*
* @param {String} [from] Relative path to subdirectory of level directory to start introspection from.
* @return {Array} Array of declaration.
*/
getDeclByIntrospection: function(from) {
this._declIntrospector || (this._declIntrospector = this.createIntrospector({
creator: function(res, match) {
if (match && match.tech) {
return this._mergeMatchToDecl(match, res);
}
return res;
}
}));
return this._declIntrospector(from);
},
/**
* Get BEM entities from level directory or one of its subdirectories.
*
* @param {String} [from] Relative path to subdirectory of level directory to start introspection from.
* @return {Array} Array of entities.
*/
getItemsByIntrospection: function(from) {
this._itemsIntrospector || (this._itemsIntrospector = this.createIntrospector());
return this._itemsIntrospector(from);
},
scanFiles: function(force) {
var list = {},
blocks = {},
flat = [],
files = {
files: list,
tree: blocks,
blocks: flat
},
items = {
push: function(file, item) {
file.suffix = item.suffix[0] === '.'?item.suffix.substr(1):item.suffix;
(list[file.suffix] || (list[file.suffix] = [])).push(file);
flat.push(item);
var block = blocks[item.block] || (blocks[item.block] = {elems: {}, mods: {}, files: {}});
if (item.mod && !item.elem) {
block = block.mods[item.mod] || (block.mods[item.mod] = {vals: {}, files: {}});
if (item.val) block = block.vals[item.val] || (block.vals[item.val] = {files: {}});
}
if (item.elem) {
block = block.elems[item.elem] || (block.elems[item.elem] = {mods: {}, files: {}});
if (item.mod) block = block.mods[item.mod] || (block.mods[item.mod] = {vals: {}, files: {}});
if (item.val) block = block.vals[item.val] || (block.vals[item.val] = {files: {}});
}
(block.files[file.suffix] || (block.files[file.suffix] = [])).push(file);
}
};
if (this.files && !force) return this.files;
var _this = this,
cachePath = PATH.join(this.projectRoot, '.bem', 'cache', PATH.relative(this.projectRoot, this.dir));
if (this.cache) {
try {
_this.files = JSON.parse(FS.readFileSync(PATH.join(cachePath, 'files.json')));
return _this.files;
} catch(err) {
LOGGER.fdebug('cache for level not found', _this.dir);
}
}
_this.scan(items);
_this.files = files;
return bemUtil
.mkdirp(cachePath)
.then(function() {
return bemUtil.writeFile(PATH.join(cachePath, 'files.json'), JSON.stringify(files));
})
.then(function() {
return files;
});
},
scan: function(items) {
if (!bemUtil.isDirectory(this.dir)) return;
LOGGER.time('scan ' + this.dir);
var _this = this;
this.suffixToTech = {};
Object.keys(this.getTechs()).forEach(function(tech) {
try {
tech = this.getTech(tech);
tech.getSuffixes().forEach(function(s) {
this.suffixToTech['.' + s] = tech.getTechName();
}, this);
} catch(err) {
LOGGER.fwarn(err.message);
}
}, this);
_this.scanBlocks(_this.dir, items);
LOGGER.timeEndLevel('debug', 'scan ' + _this.dir);
},
scanBlocks: function(path, items) {
var dirs = [],
_this = this;
bemUtil.getDirsFilesSync(path, dirs);
return dirs
.filter(function(dir) {
return dir[0] !== '_' && dir[0] !== '.';
})
.forEach(function(block) {
return _this.scanBlock(_this.dir, block, items);
});
},
scanBlock: function(path, block, items) {
var _this = this,
dirs = [], files = [];
bemUtil.getDirsFilesSync(PATH.join(path, block), dirs, files);
var blockPart = block + '.',
blockPartL = blockPart.length;
files.forEach(function(f) {
var file = f.file;
if (file.substr(0, blockPartL) !== blockPart) return;
var suffix = file.substr(blockPartL - 1);
items.push(f, {
block: block,
suffix: suffix,
tech: _this.suffixToTech[suffix]
});
});
dirs.forEach(function(dir) {
if (_this.isElemDir(dir)) return _this.scanElem(path, block, dir, items);
if (_this.isModDir(dir)) return _this.scanMod(path, block, null, dir, items);
if (dir.substr(0, blockPartL) !== blockPart) return;
var suffix = dir.substr(blockPartL - 1);
items.push(dir, {