1 var path = require('path')
2 var fs = require('graceful-fs')
3 var crypto = require('crypto')
4 var mm = require('minimatch')
5 var extensions = require('./binary-extensions.json').extensions
7 var log = require('./logger').create('preprocess')
9 var sha1 = function (data) {
10 var hash = crypto.createHash('sha1')
12 return hash.digest('hex')
15 var isBinary = Object.create(null)
16 extensions.forEach(function (extension) {
17 isBinary['.' + extension] = true
20 // TODO(vojta): instantiate preprocessors at the start to show warnings immediately
21 var createPreprocessor = function (config, basePath, injector) {
22 var alreadyDisplayedWarnings = Object.create(null)
24 return function (file, done) {
25 var patterns = Object.keys(config)
26 var thisFileIsBinary = isBinary[path.extname(file.originalPath)]
27 var preprocessors = []
28 var nextPreprocessor = function (error, content) {
30 if (arguments.length === 1 && typeof error === 'string') {
37 file.contentPath = null
41 if (!preprocessors.length) {
42 file.contentPath = null
43 file.content = content
44 file.sha = sha1(content)
48 preprocessors.shift()(content, file, nextPreprocessor)
50 var instantiatePreprocessor = function (name) {
51 if (alreadyDisplayedWarnings[name]) {
56 preprocessors.push(injector.get('preprocessor:' + name))
58 if (e.message.indexOf('No provider for "preprocessor:' + name + '"') !== -1) {
59 log.warn('Can not load "%s", it is not registered!\n ' +
60 'Perhaps you are missing some plugin?', name)
62 log.warn('Can not load "%s"!\n ' + e.stack, name)
65 alreadyDisplayedWarnings[name] = true
69 // collects matching preprocessors
70 // TODO(vojta): should we cache this ?
71 for (var i = 0; i < patterns.length; i++) {
72 if (mm(file.originalPath, patterns[i])) {
73 if (thisFileIsBinary) {
74 log.warn('Ignoring preprocessing (%s) %s because it is a binary file.',
75 config[patterns[i]].join(', '), file.originalPath)
77 config[patterns[i]].forEach(instantiatePreprocessor)
82 return fs.readFile(file.originalPath, function (err, buffer) {
86 nextPreprocessor(null, thisFileIsBinary ? buffer : buffer.toString())
90 createPreprocessor.$inject = ['config.preprocessors', 'config.basePath', 'injector']
92 exports.createPreprocessor = createPreprocessor