@@ -6,11 +6,12 @@ var fs = require("fs")
6
6
var findCacheDir = require ( "find-cache-dir" )
7
7
var objectHash = require ( "object-hash" )
8
8
var os = require ( "os" )
9
+ var path = require ( "path" )
10
+ var mkdirp = require ( "mkdirp" )
9
11
10
12
var engines = { }
11
13
var rules = { }
12
14
var cache = null
13
- var cachePath = null
14
15
15
16
/**
16
17
* linter
@@ -65,7 +66,8 @@ function lint(input, config, webpack) {
65
66
rules : rulesHash ,
66
67
res : res ,
67
68
}
68
- fs . writeFileSync ( cachePath , JSON . stringify ( cache ) )
69
+ writeCache ( cache )
70
+ // let this function handle the writing of the cache
69
71
}
70
72
}
71
73
@@ -176,24 +178,54 @@ module.exports = function(input, map) {
176
178
// Read the cached information only once and if enable
177
179
if ( cache === null ) {
178
180
if ( config . cache ) {
179
- var thunk = findCacheDir ( {
180
- name : "eslint-loader" ,
181
- thunk : true ,
182
- create : true ,
183
- } )
184
- cachePath = thunk ( "data.json" ) || os . tmpdir ( ) + "/data.json"
185
- try {
186
- cache = require ( cachePath )
187
- }
188
- catch ( e ) {
189
- cache = { }
190
- }
191
- }
192
- else {
193
- cache = false
181
+ cache = readCache ( )
194
182
}
195
183
}
196
184
197
185
lint ( input , config , this )
198
186
this . callback ( null , input , map )
199
187
}
188
+
189
+ function writeCache ( cache ) {
190
+ var cachePath = getCachePath ( )
191
+ // here we should already get the safe path to write
192
+ try { // just in case
193
+ mkdirp . sync ( path . dirname ( cachePath ) ) // Create folders if not exists
194
+ fs . writeFileSync ( cachePath , JSON . stringify ( cache ) ) // Write it now
195
+ }
196
+ catch ( e ) {
197
+ // Maybe permission denied?
198
+ // Don't log errors, try it again in the next lint...
199
+ }
200
+ }
201
+
202
+ function readCache ( ) {
203
+ try {
204
+ return require ( getCachePath ( ) )
205
+ } // if we cannot read the safe path, just return {}
206
+ catch ( e ) {
207
+ return { }
208
+ }
209
+ }
210
+
211
+ function getCachePath ( ) {
212
+ var cachePath
213
+ try {
214
+ // findCacheDir could throw an error
215
+ var thunk = findCacheDir ( {
216
+ name : "eslint-loader" ,
217
+ thunk : true ,
218
+ create : true ,
219
+ } )
220
+ cachePath = thunk ( "data.json" )
221
+ }
222
+ catch ( e ) {
223
+ // Just check if cachePath is truthy for fallbacks, findCacheDir
224
+ // thunks could return a null value
225
+ }
226
+ if ( ! cachePath ) {
227
+ cachePath = path . join ( os . tmpdir ( ) , "eslint-loader" , "cache.json" )
228
+ // tmpdir should be safe enough to write
229
+ }
230
+ return cachePath
231
+ }
0 commit comments