Skip to content

Commit 0cd7dd0

Browse files
authored
add check before writing file
fix for facebook/create-react-app#1656
1 parent d7f003d commit 0cd7dd0

File tree

1 file changed

+25
-3
lines changed

1 file changed

+25
-3
lines changed

index.js

+25-3
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,13 @@ var fs = require("fs")
66
var findCacheDir = require("find-cache-dir")
77
var objectHash = require("object-hash")
88
var os = require("os")
9+
var path = require('path')
910

1011
var engines = {}
1112
var rules = {}
1213
var cache = null
1314
var cachePath = null
15+
var cacheFallback = path.join(os.tmpdir(), 'eslint-loader', 'cache.json')
1416

1517
/**
1618
* linter
@@ -59,13 +61,23 @@ function lint(input, config, webpack) {
5961
res = engine.executeOnText(input, resourcePath, true)
6062

6163
// Save new results in the cache
62-
if (config.cache) {
64+
if (config.cache && cachePath) {
6365
cache[resourcePath] = {
6466
hash: inputMD5,
6567
rules: rulesHash,
6668
res: res,
6769
}
68-
fs.writeFileSync(cachePath, JSON.stringify(cache))
70+
var cacheJson = JSON.stringify(cacheJson)
71+
try {
72+
safeWriteCache(cachePath)
73+
} catch(e){
74+
try {
75+
cachePath = cacheFallback
76+
safeWriteCache(cachePath)
77+
} catch(e){
78+
cache = false
79+
}
80+
}
6981
}
7082
}
7183

@@ -181,7 +193,7 @@ module.exports = function(input, map) {
181193
thunk: true,
182194
create: true,
183195
})
184-
cachePath = thunk("data.json") || os.tmpdir() + "/data.json"
196+
cachePath = thunk("data.json") || cacheFallback
185197
try {
186198
cache = require(cachePath)
187199
}
@@ -197,3 +209,13 @@ module.exports = function(input, map) {
197209
lint(input, config, this)
198210
this.callback(null, input, map)
199211
}
212+
213+
214+
function safeWriteCache(cacheJson){
215+
if (fs.existsSync(cachePath)){
216+
fs.writeFileSync(cachePath, cacheJson)
217+
} else {
218+
fs.mkdirSync(path.dirname(cachePath))
219+
fs.writeFileSync(cachePath, cacheJson)
220+
}
221+
}

0 commit comments

Comments
 (0)