Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

format_tests #53

Open
wants to merge 13 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 2 additions & 5 deletions lib/create-entity.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,18 @@
var fs = require('fs'),
path = require('path'),
stream = require('stream'),
bemNaming = require('@bem/naming'),
Promise = require('pinkie-promise'),
mkdirp = require('mkdirp'),
createTree = require('./create-tree'),
relativePath = function(to) { return path.relative(process.cwd(), to); };

module.exports = function(entity, fileName, template, options) {
module.exports = function(fileName, content, options) {
return new Promise(function(resolve, reject) {
function onEnd(error) {
error ? reject(error) : resolve(fileName);
}

var isPiped = template instanceof stream.Readable,
content = (isPiped || typeof template === 'string') ? template :
template(entity, bemNaming(options.naming)),
var isPiped = content instanceof stream.Readable,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

useless

also try to use createTree for all

isFile = isPiped || (typeof content !== 'object');

fs.exists(fileName, function(exists) {
Expand Down
120 changes: 13 additions & 107 deletions lib/create.js
Original file line number Diff line number Diff line change
@@ -1,110 +1,16 @@
'use strict';

var path = require('path'),
bemConfig = require('bem-config'),
BemEntityName = require('@bem/entity-name'),
BemCell = require('@bem/cell'),
scheme = require('@bem/fs-scheme'),
bemNaming = require('@bem/naming'),
braceExpansion = require('brace-expansion'),
createEntity = require('./create-entity'),
getTemplate = require('./template'),
uniq = require('uniq'),
Promise = require('pinkie-promise');
const getEntityData = require('./get-entity-data');
const getPath = require('./get-path');
const template = require('./template');
const createEntity = require('./create-entity');

module.exports = function create(entities, levels, techs, options) {
options || (options = {});
techs || (techs = []);
var baseConfig = bemConfig(options),
cwd = path.resolve(options.cwd || '');

return baseConfig.module('bem-tools')
.then(function(bemToolsConf) {
var pluginConf = bemToolsConf && bemToolsConf.plugins && bemToolsConf.plugins.create || {};

return bemConfig(Object.assign({}, options, { extendBy: pluginConf }));
}).then(function(config) {
if (!levels || !levels.length) {
var levelsMap = config.levelMapSync(),
levelList = Object.keys(levelsMap);

var defaultLevels = levelList.filter(function(level) {
return levelsMap[level].default;
});

var levelByCwd = levelList.filter(function(level) {
return cwd.indexOf(level) === 0;
}).sort().reverse()[0];

levels = levelByCwd || (defaultLevels.length ? defaultLevels : cwd);
}

Array.isArray(entities) || (entities = [entities]);
Array.isArray(levels) || (levels = [levels]);

return Promise.all(entities.map(function(input) {
var isFileGlob = typeof input === 'string';

return Promise.all((isFileGlob ? braceExpansion(input) : [input]).map(function(filepathOrInput) {
var currentLevels = levels;

if (typeof filepathOrInput === 'string') {
var currentLevel = path.dirname(filepathOrInput);
currentLevel !== '.' && (currentLevels = [currentLevel]);
}

return Promise.all(currentLevels.map(function(relLevel) {
var rootDir = config.rootSync() || cwd,
level = path.resolve(rootDir, relLevel);

return config.level(level).then(function(levelOptions) {
levelOptions || (levelOptions = {});

var levelScheme = levelOptions.scheme,
buildPath = scheme(levelScheme).path,
currentTechs = uniq([].concat(levelOptions.techs || [], techs)),
entity;

if (isFileGlob) {
var file = path.basename(filepathOrInput),
// split for entity key and tech (by first dot)
match = file.match(/^([^.]+)(?:\.(.+))?$/);

entity = bemNaming(levelOptions.naming).parse(match[1]);
if (match[2]) {
currentTechs = uniq(techs.concat(match[2]));
}
} else {
entity = BemEntityName.create(filepathOrInput);
}

options.onlyTech && (currentTechs = options.onlyTech);

options.excludeTech && (currentTechs = currentTechs.filter(function(tech) {
return options.excludeTech.indexOf(tech) === -1;
}));

return Promise.all(currentTechs.map(function(tech) {
var pathToFile = buildPath(
new BemCell({ entity: entity, tech: tech }),
levelOptions.schemeOptions || levelOptions),
absPathToFile = path.join(path.resolve(level), pathToFile),
template = options.fileContent || getTemplate(tech, levelOptions);

levelOptions.forceRewrite = options.forceRewrite;

return createEntity(entity, absPathToFile, template, levelOptions);
}));
});
}));

}));
})).then(flatten);
});
var entityData = getEntityData(entities, levels, techs, options);

return Promise.all(entityData.map(item =>
template.apply(item)
.then(content =>
createEntity(getPath(item), content, item.levelOptions)
)
)
);
};

function flatten(arr) {
return arr.reduce(function(acc, item) {
return acc.concat(Array.isArray(item) ? flatten(item) : item);
}, []);
}
100 changes: 100 additions & 0 deletions lib/get-entity-data.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
'use strict';

var path = require('path'),
bemNaming = require('@bem/naming'),
BemEntityName = require('@bem/entity-name'),
braceExpansion = require('brace-expansion'),
uniq = require('uniq'),
bemConfig = require('bem-config');

function flatten(arr) {
return arr.reduce(function(acc, item) {
return acc.concat(Array.isArray(item) ? flatten(item) : item);
}, []);
}

module.exports = function getEntityData(entities, levels, techs, options) {
options || (options = {});
techs || (techs = []);
var baseConfig = bemConfig(options),
cwd = path.resolve(options.cwd || ''),

bemToolsConf = baseConfig.moduleSync('bem-tools'),

pluginConf = bemToolsConf && bemToolsConf.plugins && bemToolsConf.plugins.create || {},

config = bemConfig(Object.assign({}, options, { extendBy: pluginConf }));

if (!levels || !levels.length) {
var levelsMap = config.levelMapSync(),
levelList = Object.keys(levelsMap);

var defaultLevels = levelList.filter(function(level) {
Copy link

@dustyo-O dustyo-O May 17, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

возможно, нужно вычислять только после levelByCwd, потому что на строке https://github.com/bem-tools/bem-tools-create/pull/53/files#diff-d854c73a37caf2bcd71fe93eba02959fR40 стоит справа от или

return levelsMap[level].default;
});

var levelByCwd = levelList.filter(function(level) {
return cwd.indexOf(level) === 0;
}).sort().reverse()[0];

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

затащить reverse внутрь sort


levels = levelByCwd || (defaultLevels.length ? defaultLevels : cwd);
}

Array.isArray(entities) || (entities = [entities]);
Array.isArray(levels) || (levels = [levels]);

return flatten(entities.map(function(input) {
var isFileGlob = typeof input === 'string';

return (isFileGlob ? braceExpansion(input) : [input]).map(function(filepathOrInput) {
var currentLevels = levels;

if (typeof filepathOrInput === 'string') {
var currentLevel = path.dirname(filepathOrInput);
currentLevel !== '.' && (currentLevels = [currentLevel]);
}

return currentLevels.map(function(relLevel) {
var rootDir = config.rootSync() || cwd,
level = path.resolve(rootDir, relLevel),
levelOptions = config.levelSync(level) || {},
currentTechs = uniq([].concat(levelOptions.techs || [], techs)),
entity;

if (isFileGlob) {
var file = path.basename(filepathOrInput),
// split for entity key and tech (by first dot)
match = file.match(/^([^.]+)(?:\.(.+))?$/);

entity = bemNaming(levelOptions.naming).parse(match[1]);
if (match[2]) {
currentTechs = uniq(techs.concat(match[2]));
}
} else {
entity = BemEntityName.create(filepathOrInput);
}

options.onlyTech && (currentTechs = options.onlyTech);

options.excludeTech && (currentTechs = currentTechs.filter(function(tech) {
return options.excludeTech.indexOf(tech) === -1;
}));

return currentTechs.map(function(tech) {
if (options.forceRewrite) {
levelOptions.forceRewrite = options.forceRewrite;
}

return {
config: config,
levelOptions: levelOptions,
tech: tech,
options: options,
entity: entity,
level: level
};
});
});
});
}));
};
15 changes: 15 additions & 0 deletions lib/get-path.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const path = require('path');
const scheme = require('@bem/fs-scheme');
const BemCell = require('@bem/cell');

module.exports = function getPath(item) {
const levelOptions = item.config.levelSync(item.level) || {};
const levelScheme = levelOptions.scheme;
const buildPath = scheme(levelScheme).path;
const pathToFile = buildPath(
new BemCell({ entity: item.entity, tech: item.tech }),
item.levelOptions.schemeOptions || item.levelOptions
);

return path.join(path.resolve(item.level), pathToFile);
};
44 changes: 29 additions & 15 deletions lib/template.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,44 @@
'use strict';

var fs = require('fs'),
path = require('path');
path = require('path'),
bemNaming = require('@bem/naming'),
stream = require('stream'),
streamToPromise = require('stream-to-promise');

function defaultTemplate() {
return '';
}

module.exports = function getTemplate(tech, options) {
var templateFolder = options.templateFolder,
techId = (options.techsTemplates && options.techsTemplates[tech]) || tech,
templatePath = options.templates && options.templates[techId] && path.resolve(options.templates[techId]),
possiblePaths = [path.join(__dirname, 'templates')];
module.exports = {
get: function(tech, options) {
var templateFolder = options.templateFolder,
techId = (options.techsTemplates && options.techsTemplates[tech]) || tech,
templatePath = options.templates && options.templates[techId] && path.resolve(options.templates[techId]),
possiblePaths = [path.join(__dirname, 'templates')];

templateFolder && possiblePaths.unshift(templateFolder);
templateFolder && possiblePaths.unshift(templateFolder);

if (!templatePath) {
for (var i = 0; i < possiblePaths.length; i++) {
var possibleTemplatePath = path.resolve(possiblePaths[i], techId + '.js');
if (!templatePath) {
for (var i = 0; i < possiblePaths.length; i++) {
var possibleTemplatePath = path.resolve(possiblePaths[i], techId + '.js');

if (fs.existsSync(possibleTemplatePath)) {
templatePath = possibleTemplatePath;
break;
if (fs.existsSync(possibleTemplatePath)) {
templatePath = possibleTemplatePath;
break;
}
}
}
}

return templatePath ? require(templatePath) : defaultTemplate;
return templatePath ? require(templatePath) : defaultTemplate;
},

apply: function(item) {
var template = item.options.fileContent || this.get(item.tech, item.levelOptions),
isPiped = template instanceof stream.Readable;

return isPiped ? streamToPromise(template) : Promise.resolve(
typeof template === 'string' ? template : template(item.entity, bemNaming(item.levelOptions.naming))
);
}
};
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"brace-expansion": "^1.1.6",
"mkdirp": "^0.5.1",
"pinkie-promise": "^2.0.1",
"stream-to-promise": "^2.2.0",
"uniq": "^1.0.1"
},
"devDependencies": {
Expand Down
Loading