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

Do not build graph by default #357

Merged
merged 3 commits into from
Sep 23, 2015
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Separate class NodeWithGraph for building graph
  • Loading branch information
j0tunn committed Sep 23, 2015
commit 5f97701160aabad5cf36ad2737bb7854e9a3b9e6
3 changes: 2 additions & 1 deletion .jshintrc
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,6 @@
"maxlen": 120,
"unused": true,
"undef": true,
"node": true
"node": true,
"laxbreak": true
}
5 changes: 2 additions & 3 deletions lib/make.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
var vow = require('vow'),
Node = require('./node'),
nodeFactory = require('./node'),
path = require('path'),
clearRequire = require('clear-require'),
Logger = require('./logger'),
Expand Down Expand Up @@ -334,10 +334,9 @@ module.exports = inherit(/** @lends MakePlatform.prototype */ {
var _this = this,
cdir = this.getDir(),
nodeConfig = this._projectConfig.getNodeConfig(nodePath),
node = new Node(nodePath, this, this._cache);
node = nodeFactory.mkNode(nodePath, this, this._cache, this._graph);

node.setLogger(this._logger.subLogger(nodePath));
node.setBuildGraph(this._graph);
this._nodes[nodePath] = node;
this._nodeInitPromises[nodePath] = vowFs.makeDir(path.join(cdir, nodePath))
.then(function () {
Expand Down
8 changes: 8 additions & 0 deletions lib/node/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
var Node = require('./node');
var NodeWithGraph = require('./node-with-graph');

exports.mkNode = function (nodePath, makePlatform, cache, graph) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Сокращения - зло. Почему не buildNode ?

Copy link
Member

Choose a reason for hiding this comment

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

Это явно не build, но сокращения зло :)

По мне — createNode.

Copy link
Contributor

Choose a reason for hiding this comment

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

Почему не build ? factory.buildNode(params); - вполне себе фабрика нод строит ноду.
create - тоже ок.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Распространенные, общеизвестные сокращения - благо. Никто ж не жалуется на mkdir или собственно на dir. Или кто-то из вас не понял что означает сие сокращение?
Может еще API не будем использовать? Или img? Или ptr в плюсах?
Давайте руководствоваться здравым смыслом, а не громкими лозунгами

Copy link
Contributor

Choose a reason for hiding this comment

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

С пониманием 🆗 Спотыкаешься, когда читаешь - ведь проще прочитать copyString, чем strcpy.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

дело привычки

return graph
? new NodeWithGraph(nodePath, makePlatform, cache, graph)
: new Node(nodePath, makePlatform, cache);
};
98 changes: 98 additions & 0 deletions lib/node/node-with-graph.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
/**
* NodeWithGraph
* =============
*/

var Node = require('./node');
var Vow = require('vow');
var inherit = require('inherit');
var path = require('path');
var _ = require('lodash');

module.exports = inherit(Node, {
__constructor: function (nodePath, makePlatform, cache, graph) {
Copy link
Member

Choose a reason for hiding this comment

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

Зачем нужен аргумент graph?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

туда собственно передается граф из makePlatform

Copy link
Member

Choose a reason for hiding this comment

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

А почему не передавать как раньше через сеттер?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Потому что объект класса NodeWithGraph без графа не имеет смысла (да и работать не будет). Соответственно создавать нужно сразу рабочий объект, с графом. Сеттер здесь - штука бессмысленная, и потенциально может внести ошибку

this.__base(nodePath, makePlatform, cache);

/**
* Построитель графа сборки.
* @type {BuildGraph}
* @name NodeWithGraph.prototype._graph
* @private
*/
this._graph = graph;
},

///
_initTech: function (tech) {
var _this = this;
var nodeAdapterClass = function () {};
nodeAdapterClass.prototype = _this;
var nodeAdapter = new nodeAdapterClass();

return Vow.when(tech.init(nodeAdapter)).then(function () {
return Vow.when(tech.getTargets()).then(function (targets) {
targets.forEach(function (target) {
var targetPath = path.join(_this._path, target);
_this._graph.addTarget(targetPath, tech.getName());
});

nodeAdapter.requireSources = function (sources) {
return _this.requireSources(sources, targets);
};
nodeAdapter.requireNodeSources = function (sources) {
return _this.requireNodeSources(sources, targets);
};
});
});
},

///
requireSources: function (sources, targets) {
Copy link
Member

Choose a reason for hiding this comment

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

Сейчас методы переопределяются сразу, а не от наличия this._graph как было раньше.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

В этом и смысл: это отдельный класс, в котором this._graph точно есть. А какую ноду создавать (с графом или без) решается в фабричном методе по наличию аргумента graph

Copy link
Member

Choose a reason for hiding this comment

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

Тогда не нужен агрумент graph в конструкторе.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

как это не нужен? Он же из makePlatform летит, и в конструкторе сохраняется в свойство this._graph

var _this = this;
this._addDepsToGraph(targets, sources, function (source) {
return path.join(_this._path, _this.unmaskTargetName(source));
});

return Node.prototype.requireSources.apply(this, arguments);
},

///
requireNodeSources: function (sources, targets) {
var _this = this;
_.forEach(sources, function (nodeSources, nodeName) {
_this._addDepsToGraph(targets, nodeSources, function (source) {
return path.join(nodeName, _this.unmaskNodeTargetName(nodeName, source));
});
});

return Node.prototype.requireNodeSources.apply(this, arguments);
},

///
_addDepsToGraph: function (targets, sources, getDepFromPath) {
var _this = this;
targets = targets || [];

targets.forEach(function (target) {
var targetPath = path.join(_this._path, target);
sources.forEach(function (source) {
_this._graph.addDep(
targetPath,
getDepFromPath(source)
);
});
});
},

///
resolveTarget: function (target) {
this._graph.resolveTarget(path.join(this._path, target));
return Node.prototype.resolveTarget.apply(this, arguments);
},

///
destruct: function () {
this.__base();
delete this._graph;
}
});
81 changes: 13 additions & 68 deletions lib/node.js → lib/node/node.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
*/
var Vow = require('vow'),
fs = require('fs'),
vowFs = require('./fs/async-fs'),
vowFs = require('../fs/async-fs'),
path = require('path'),
inherit = require('inherit'),
TargetNotFoundEror = require('./errors/target-not-found-error');
TargetNotFoundEror = require('../errors/target-not-found-error');

/**
* Нода — директория, в которой происходит сборка. Например, сборка страницы.
Expand Down Expand Up @@ -127,13 +127,6 @@ module.exports = inherit(/** @lends Node.prototype */ {
* @private
*/
this._registerTargetsPromise = null;
/**
* Построитель графа сборки.
* @type {BuildGraph}
* @name Node.prototype._graph
* @private
*/
this._graph = null;
},

/**
Expand Down Expand Up @@ -236,16 +229,6 @@ module.exports = inherit(/** @lends Node.prototype */ {
this._targetNamesToClean = targetsToClean;
},

/**
* Устанавливает построитель графа сборки.
* @param {BuildGraph} graph
* @returns {Node}
*/
setBuildGraph: function (graph) {
this._graph = graph;
return this;
},

/**
* Возвращает абсолютный путь к файлу, лежащему в директории с нодой.
* @param {String} filename
Expand Down Expand Up @@ -351,54 +334,19 @@ module.exports = inherit(/** @lends Node.prototype */ {
loadTechs: function () {
var _this = this;
return Vow.all(this._techs.map(function (t) {
var NodeMirrorClass = function () {};
NodeMirrorClass.prototype = _this;
var mirror = new NodeMirrorClass();
return Vow.when(t.init(mirror)).then(function () {
return Vow.when(t.getTargets()).then(function (targets) {
if (_this._graph) {
targets.forEach(function (target) {
var targetPath = path.join(_this._path, target);
_this._graph.addTarget(targetPath, t.getName());
});
}
var origRequireSources = _this.requireSources;
var origRequireNodeSources = _this.requireNodeSources;
mirror.requireSources = function (sources) {
if (_this._graph) {
targets.forEach(function (target) {
var targetPath = path.join(_this._path, target);
sources.forEach(function (source) {
_this._graph.addDep(
targetPath,
path.join(_this._path, _this.unmaskTargetName(source))
);
});
});
}
return origRequireSources.apply(_this, arguments);
};
mirror.requireNodeSources = function (sources) {
if (_this._graph) {
Object.keys(sources).forEach(function (nodeName) {
targets.forEach(function (target) {
var targetPath = path.join(_this._path, target);
sources[nodeName].forEach(function (source) {
_this._graph.addDep(
targetPath,
path.join(nodeName, _this.unmaskNodeTargetName(nodeName, source))
);
});
});
});
}
return origRequireNodeSources.apply(_this, arguments);
};
});
});
return _this._initTech(t);
}));
},

/**
* Инициализирует технологию
* @param {Tech} tech
* @return {Promise}
*/
_initTech: function (tech) {
return tech.init(this);
},

/**
* Возвращает техническую информацию об указанном таргете.
* Формат результата: { tech: <ссылка на технологию>, started: true|false, promise: <промис на выполнение> }
Expand Down Expand Up @@ -475,9 +423,7 @@ module.exports = inherit(/** @lends Node.prototype */ {
if (!targetObj.isValid) {
this._logger.logAction('rebuild', target, targetObj.tech && targetObj.tech.getName());
}
if (this._graph) {
this._graph.resolveTarget(path.join(this._path, target));
}

targetObj.deferred.resolve(value);
return targetObj.deferred.promise();
},
Expand Down Expand Up @@ -694,6 +640,5 @@ module.exports = inherit(/** @lends Node.prototype */ {
this._nodeCache.destruct();
delete this._nodeCache;
delete this._techs;
delete this._graph;
}
});
2 changes: 1 addition & 1 deletion test/lib/make/build-targets.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ var vow = require('vow');
var vowFs = require('vow-fs');
var _ = require('lodash');
var MakePlatform = require('../../../lib/make');
var Node = require('../../../lib/node');
var Node = require('../../../lib/node/node');
var ProjectConfig = require('../../../lib/config/project-config');
var NodeConfig = require('../../../lib/config/node-config');
var NodeMaskConfig = require('../../../lib/config/node-mask-config');
Expand Down
2 changes: 1 addition & 1 deletion test/lib/make/build.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ var path = require('path');
var vow = require('vow');
var vowFs = require('vow-fs');
var _ = require('lodash');
var Node = require('../../../lib/node');
var Node = require('../../../lib/node/node');
var MakePlatform = require('../../../lib/make');
var ProjectConfig = require('../../../lib/config/project-config');
var NodeMaskConfig = require('../../../lib/config/node-mask-config');
Expand Down
2 changes: 1 addition & 1 deletion test/lib/make/clean-targets.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ var path = require('path');
var vow = require('vow');
var vowFs = require('vow-fs');
var _ = require('lodash');
var Node = require('../../../lib/node');
var Node = require('../../../lib/node/node');
var MakePlatform = require('../../../lib/make');
var ProjectConfig = require('../../../lib/config/project-config');
var NodeMaskConfig = require('../../../lib/config/node-mask-config');
Expand Down
2 changes: 1 addition & 1 deletion test/lib/make/constructor-desrtuctor.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
var fs = require('fs');
var MakePlatform = require('../../../lib/make');
var ProjectConfig = require('../../../lib/config/project-config');
var Node = require('../../../lib/node');
var Node = require('../../../lib/node/node');
var CacheStorage = require('../../../lib/cache/cache-storage');
var Cache = require('../../../lib/cache/cache');
var SharedResources = require('../../../lib/shared-resources');
Expand Down
Loading