Created
March 27, 2014 10:29
-
-
Save Kuznetsov-Ilia/9804576 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const PLUGIN_NAME = 'gulp-sprites'; | |
var gutil = require('gulp-util'); | |
var log = gutil.log; | |
//var PluginError = gutil.PluginError; | |
var path = require('path'); | |
var sprite = require('node-sprite'); | |
var vow = require('vow'); | |
var exec = require('child_process').exec; | |
var fs = require('fs'); | |
var defaultStyles = [ | |
'.{I}', | |
' display: inline-block;', | |
' background: url("/images/{I}.png?{HASH}") no-repeat 0 0;', | |
'' | |
].join('\n'); | |
var defaultStylesTmpl = [ | |
'.i--{F}', | |
' width: {W}px;', | |
' height: {H}px;', | |
' background-position: -{PX}px -{PY}px;', | |
'' | |
].join('\n'); | |
module.exports = function (options) { | |
sprite.sprites({ | |
path: path.resolve(options.src) | |
}, function (err, result) { | |
if (err) { | |
log(gutil.colors.red(err)); | |
} else { | |
var spriteStr = ''; | |
var promises = []; | |
log('folders:', gutil.colors.green(Object.keys(result).join(','))); | |
Object.keys(result).forEach(function (e) { | |
var defer = vow.defer(); | |
var pack = result[e]; | |
var currentStyles = defaultStyles | |
.replace(/\{I\}/g, e) | |
.replace(/\{HASH\}/g, pack.shortsum()) | |
.replace('{S}', Math.round(pack.mapper.width)); | |
var spritePath = pack.path + '/' + pack.filename(); | |
var lnPath = ['build/', e, '.png'].join(''); | |
pack.images.forEach(function (file) { | |
currentStyles += defaultStylesTmpl | |
.replace('{F}', file.name) | |
.replace('{W}', Math.ceil(file.width)) | |
.replace('{H}', Math.ceil(file.height)) | |
.replace('{PX}', Math.round(file.positionX)) | |
.replace('{PY}', Math.round(file.positionY)) | |
}); | |
spriteStr += currentStyles; | |
promises.push(defer.promise()); | |
exec('ln -sf ' + [spritePath, lnPath].join(' '), {}, function (error, stdout, stderr) { | |
if (error) { | |
log(gutil.colors.red(error)); | |
} else { | |
log('ln -sf ', [spritePath, lnPath].join(' '), gutil.colors.green('successed!')); | |
defer.resolve(); | |
} | |
if (stderr) { | |
log(gutil.colors.red(stderr)); | |
} | |
if (stdout) { | |
log(stdout); | |
} | |
}); | |
}); | |
vow.all(promises).then(function () { | |
log(gutil.colors.green('all promises resolved!')); | |
fs.writeFile(path.resolve(options.dest), spriteStr, function (error, result) { | |
if (result) { | |
log(result); | |
} | |
if (error) { | |
log(gutil.colors.red(error)); | |
} else { | |
options.done(); | |
} | |
}); | |
}); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment