Skip to content

Instantly share code, notes, and snippets.

@2no
Last active December 16, 2015 14:49
Show Gist options
  • Save 2no/5451075 to your computer and use it in GitHub Desktop.
Save 2no/5451075 to your computer and use it in GitHub Desktop.
grunt-ect 用パスヘルパー。require('./lib/helper').Path.setRoot でルートを指定することも可能
'use strict';
module.exports = function(grunt)
{
var Path = require('./lib/helper').Path;
grunt.task.renameTask('ect', 'grunt-ect_ect');
grunt.task.registerMultiTask('ect', 'overwrite by grunt-ect helper',
function() {
var config = {}
, variables = this.data.variables || this.options({
variables: {}
}).variables
;
variables.Path = Path.setCurrent(this.data.dest);
delete this.data.variables;
this.data.options.variables = variables;
config[this.target] = this.data;
grunt.config.set('grunt-ect_ect', config);
grunt.task.run(['grunt-ect_ect']);
});
};
// lib/helper.js
'use strict';
var grunt = require('grunt')
, path = require('path')
, currentPath = null
, currentRootPath = null
, rootPath = null
;
function trimRootPath(_path)
{
if (grunt.file.arePathsEquivalent(currentRootPath, _path) ||
grunt.file.doesPathContain(currentRootPath, _path)
) {
_path = path.relative(currentRootPath, _path);
}
return _path;
}
function getRootPath(_path)
{
var root = _path.split(path.sep).slice(0, 2).join(path.sep);
return path.dirname(root);
}
exports.Path = {
getRelative: function(to, from)
{
var _path, dirTo, dirFrom, basename;
to = this.normalize(to);
from = this.normalize(from) || currentPath;
dirTo = grunt.file.isFile(to) ? path.dirname(to) : to;
dirFrom = grunt.file.isFile(from) ? path.dirname(from) : from;
dirTo = trimRootPath(dirTo) || '.';
dirFrom = trimRootPath(dirFrom) || '.';
_path = path.relative(dirFrom, dirTo);
if (grunt.file.isFile(to)) {
basename = trimRootPath(path.basename(to));
_path = _path + (_path ? path.sep : '') + basename;
}
return path.normalize(_path);
}
, getAbsolute: function(to, from)
{
return this.toAbsolute(this.getRelative(to, from));
}
, toAbsolute: function(_path)
{
return path.normalize(path.sep + _path);
}
, setRoot: function(_path)
{
rootPath = path.normalize(_path + path.sep);
return this;
}
, getRoot: function()
{
return this.getRelative(currentRootPath, currentPath);
}
, setCurrent: function(_path)
{
currentPath = path.normalize(_path);
currentRootPath = rootPath || getRootPath(currentPath);
return this;
}
, getCurrent: function()
{
return trimRootPath(currentPath);
}
, getDirname: function(_path)
{
return path.dirname(_path);
}
, getBasename: function(_path)
{
return path.basename(_path);
}
, normalize: function(_path)
{
if (_path && _path.indexOf(path.sep) === 0) {
_path = path.normalize(currentRootPath + _path);
}
return _path;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment