This repository has been archived by the owner on Oct 19, 2021. It is now read-only.
/
configfinder.coffee
58 lines (50 loc) · 1.89 KB
/
configfinder.coffee
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
###
Helpers for finding CoffeeLint config in standard locations, similar to how
JSHint does.
###
fs = require 'fs'
path = require 'path'
stripComments = require 'strip-json-comments'
# Cache for findFile
findFileResults = {}
# Searches for a file with a specified name starting with 'dir' and going all
# the way up either until it finds the file or hits the root.
findFile = (name, dir) ->
dir = dir or process.cwd()
filename = path.normalize(path.join(dir, name))
return findFileResults[filename] if findFileResults[filename]
parent = path.resolve(dir, "../")
if fs.existsSync(filename)
findFileResults[filename] = filename
else if dir is parent
findFileResults[filename] = null
else
findFile name, parent
# Possibly find CoffeeLint configuration within a package.json file.
loadNpmConfig = (dir) ->
fp = findFile("package.json", dir)
loadJSON(fp)?.coffeelintConfig if fp
# Parse a JSON file gracefully.
loadJSON = (filename) ->
try
JSON.parse(stripComments(fs.readFileSync(filename).toString()))
catch e
process.stderr.write "Could not load JSON file '#{filename}': #{e}"
null
# Tries to find a configuration file in either project directory (if file is
# given), as either the package.json's 'coffeelintConfig' property, or a project
# specific 'coffeelint.json' or a global 'coffeelint.json' in the home
# directory.
exports.getConfig = (filename = null) ->
if filename
dir = path.dirname(path.resolve(filename))
else
dir = process.cwd()
npmConfig = loadNpmConfig(dir)
return npmConfig if npmConfig
projConfig = findFile("coffeelint.json", dir)
return loadJSON(projConfig) if projConfig
envs = process.env.USERPROFILE or process.env.HOME or process.env.HOMEPATH
home = path.normalize(path.join(envs, "coffeelint.json"))
if fs.existsSync(home)
return loadJSON(home)