-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathindex.js
87 lines (78 loc) · 3.1 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
'use strict';
var sassJs = require('sass.js'),
q = require('q'),
_ = require('lodash'),
path = require('path'),
fs = require('fs'),
getNodeModuleDir = require('./lib/get-node-module-dir'),
getResolvedPath = require('./lib/get-resolved-path'),
getPathVariations = require('./lib/get-path-variations');
module.exports = function(content) {
var callback = this.async();
var self = this;
sassJs.importer(function(request, done) {
// Adapted from
// eslint-disable-next-line max-len
// https://github.com/amiramw/grunt-contrib-sassjs/blob/a65f869df967a4e417c4260fd93239e4f0bc55ee/tasks/sass.js#L11
if (request.path) {
done();
} else if (request.resolved) {
var resolvedPath = getResolvedPath(request),
pathVariations = getPathVariations(resolvedPath),
ostensibleNodeModuleName = _.first(request.current.split(path.sep)),
rootNodeModulesDir = getRootNodeModulesDir(ostensibleNodeModuleName);
if (rootNodeModulesDir) {
Array.prototype.push.apply(
pathVariations,
getPathVariations(path.join(rootNodeModulesDir, request.current))
);
}
q.all(_.map(pathVariations, function(pathVariation) {
return q.nfcall(fs.readFile, pathVariation, 'utf-8')
.then(function(fileContents) {
self.addDependency(pathVariation);
return {
path: pathVariation,
content: fileContents
};
})
.catch(function(err) {
/**
* ENOENT happens when the file does not exist. That is expected,
* because we only expect one of the many path variations to exist.
* EISDIR happens when a path variation is also the name of a directory.
* This also does not need to be a problem if there's a different path
* variation is that is a valid file name.
*/
if (err.code === 'ENOENT' || err.code === 'EISDIR') {
return null;
}
throw err;
});
})).then(function(files) {
done(_(files).compact().first());
}).catch(function(err) {
done({error: JSON.stringify(err)});
});
} else {
done();
}
});
sassJs.compile(content, {inputPath: this.resourcePath}, function(result) {
if (!result.status) {
callback(null, result.text);
} else {
callback(new Error(result.formatted));
}
});
};
function getRootNodeModulesDir(name) {
try {
return getNodeModuleDir(require.resolve(name));
} catch (e) {
if (e.code === 'MODULE_NOT_FOUND') {
return null;
}
throw e;
}
}