This repository has been archived by the owner on Mar 25, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
96 lines (84 loc) · 3.23 KB
/
index.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
'use strict';
const fs = require('mz/fs');
const path = require('path');
const Readable = require('stream').Readable;
const globby = require('globby');
const nodeEval = require('node-eval');
const decl = require('bem-decl');
const BemBundle = require('@bem/bundle');
/**
*
* @param {string} pattern
* @param {object} opts
* @param {string[]} opts.levels List of additional levels relative to the bundle root folder
* @param {boolean} opts.preferBemjson
* @returns {module:stream/Readable}
*/
module.exports = function(pattern, opts) {
opts = Object.assign({
levels: [], //
preferBemjson: false
}, opts);
const output = new Readable({
objectMode: true,
read: function() {}
});
globby(pattern, opts)
// Skip entities started with `.`
.then(matches => matches.filter(dirname => path.basename(dirname).charAt(0) !== '.'))
.then(dirnames => Promise.all(dirnames.map(dirname => {
return fs.readdir(dirname)
.then(filenames => Promise.all(filenames.map(filename => {
const filepath = path.join(dirname, filename);
return fs.stat(filepath)
.then(stats => ({
path: filepath,
basename: filename,
name: pathName(dirname),
tech: pathTech(filename),
isDirectory: stats.isDirectory(),
isFile: stats.isFile()
}));
})))
.then(files => ({dirname, files}));
})))
.then(bundles => Promise.all(bundles.map(bundle => {
bundle = Object.assign({
name: path.basename(bundle.dirname),
path: bundle.dirname + path.sep + '.',
levels: opts.levels.map(level => path.join(bundle.dirname, level))
}, bundle);
const bemjsonFilename = _pathToBestMatched(bundle, 'bemjson.js');
const bemdeclFilename = _pathToBestMatched(bundle, 'bemdecl.js');
return Promise
.all([
bemdeclFilename && decl.load(bemdeclFilename),
bemjsonFilename && fs.readFile(bemjsonFilename, 'utf8')
])
.then(res => {
const decl = res[0];
const bemjson = res[1];
decl && !opts.preferBemjson && (bundle.decl = decl.map(item => item.entity));
bemjson && (bundle.bemjson = nodeEval(bemjson, path.resolve(bemjsonFilename)));
})
.then(() => output.push(new BemBundle(bundle)))
})))
.catch(err => {
console.error(err.stack);
output.emit(err)
})
.then(() => output.push(null));
return output;
};
function _pathToBestMatched(bundle, tech) {
const res = bundle.files
.filter(f => f.isFile && f.tech === tech)
.sort(f => f.name !== bundle.name);
return Object(res[0]).path;
}
function pathTech(fullpath) {
return path.basename(fullpath).split('.').slice(1).join('.');
}
function pathName(fullpath) {
return path.basename(fullpath).split('.')[0];
}