Skip to content
This repository has been archived by the owner on Sep 28, 2020. It is now read-only.

add checks before writing and reading cache #158

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 54 additions & 17 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,12 @@ var fs = require("fs")
var findCacheDir = require("find-cache-dir")
var objectHash = require("object-hash")
var os = require("os")
var path = require("path")
var mkdirp = require("mkdirp")

var engines = {}
var rules = {}
var cache = null
var cachePath = null

/**
* linter
Expand Down Expand Up @@ -65,7 +66,8 @@ function lint(input, config, webpack) {
rules: rulesHash,
res: res,
}
fs.writeFileSync(cachePath, JSON.stringify(cache))
writeCache(cache, config.quiet ? false : webpack.emitWarning)
// let this function handle the writing of the cache
}
}

Expand Down Expand Up @@ -176,24 +178,59 @@ module.exports = function(input, map) {
// Read the cached information only once and if enable
if (cache === null) {
if (config.cache) {
var thunk = findCacheDir({
name: "eslint-loader",
thunk: true,
create: true,
})
cachePath = thunk("data.json") || os.tmpdir() + "/data.json"
try {
cache = require(cachePath)
}
catch (e) {
cache = {}
}
}
else {
cache = false
cache = readCache()
}
}

lint(input, config, this)
this.callback(null, input, map)
}

function writeCache(cache, emitter) {
var cachePath = getCachePath()
// here we should already get the safe path to write
try { // just in case
fs.writeFileSync(cachePath, JSON.stringify(cache)) // Write it now
}
catch (e) {
// Maybe permission denied?
if (emitter) {
emitter([
"eslint-loader is configured with cache: true",
"but it could not write the file in " + cachePath,
].join(" "))
}
}
}

function readCache() {
try {
return require(getCachePath())
} // if we cannot read the safe path, just return {}
catch (e) {
return {}
}
}

function getCachePath() {
var cachePath
try {
// findCacheDir could throw an error
var thunk = findCacheDir({
name: "eslint-loader",
thunk: true,
create: true,
})
cachePath = thunk("data.json")
}
catch (e) {
// Just check if cachePath is truthy for fallbacks, findCacheDir
// thunks could return a null value
}
if (!cachePath) {
cachePath = path.join(os.tmpdir(), "eslint-loader", "cache.json")
mkdirp.sync(path.dirname(cachePath)) // Create folders if not exists
}
// cachePath should be safe enough now to write
return cachePath
}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
"dependencies": {
"find-cache-dir": "^0.1.1",
"loader-utils": "^1.0.2",
"mkdirp": "^0.5.1",
"object-assign": "^4.0.1",
"object-hash": "^1.1.4"
},
Expand Down