Skip to content

Commit e7ed6f7

Browse files
authoredApr 7, 2023
fix: ignore "package.json" as config file when it's invalid JSON (#1281)
1 parent 05fb382 commit e7ed6f7

File tree

2 files changed

+44
-2
lines changed

2 files changed

+44
-2
lines changed
 

‎lib/loadConfig.js

+15-2
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,14 @@ import { resolveConfig } from './resolveConfig.js'
99

1010
const debugLog = debug('lint-staged:loadConfig')
1111

12+
const PACKAGE_JSON = 'package.json'
13+
1214
/**
1315
* The list of files `lint-staged` will read configuration
1416
* from, in the declared order.
1517
*/
1618
export const searchPlaces = [
17-
'package.json',
19+
PACKAGE_JSON,
1820
'.lintstagedrc',
1921
'.lintstagedrc.json',
2022
'.lintstagedrc.yaml',
@@ -27,7 +29,18 @@ export const searchPlaces = [
2729
'lint-staged.config.cjs',
2830
]
2931

30-
const jsonParse = (path, content) => JSON.parse(content)
32+
const jsonParse = (path, content) => {
33+
try {
34+
return JSON.parse(content)
35+
} catch (error) {
36+
if (path.endsWith(PACKAGE_JSON)) {
37+
debugLog('Ignoring invalid package file `%s` with content:\n%s', path, content)
38+
return undefined
39+
}
40+
41+
throw error
42+
}
43+
}
3144

3245
const yamlParse = (path, content) => YAML.parse(content)
3346

‎test/unit/loadConfig.spec.js

+29
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import fs from 'node:fs/promises'
12
import path from 'node:path'
23

34
import makeConsoleMock from 'consolemock'
@@ -177,4 +178,32 @@ describe('loadConfig', () => {
177178

178179
expect(result).toMatchInlineSnapshot(`{}`)
179180
})
181+
182+
it('should return empty object ".lintstagedrc.json" file is invalid', async () => {
183+
expect.assertions(1)
184+
185+
const configFile = path.join(__dirname, '__mocks__', '.lintstagedrc.json')
186+
187+
await fs.writeFile(configFile, '{')
188+
189+
const result = await loadConfig({ configPath: configFile }, logger)
190+
191+
expect(result).toMatchInlineSnapshot(`{}`)
192+
193+
await fs.rm(configFile)
194+
})
195+
196+
it('should return null config when package.json file is invalid', async () => {
197+
expect.assertions(1)
198+
199+
const configFile = path.join(__dirname, '__mocks__', 'package.json')
200+
201+
await fs.writeFile(configFile, '{')
202+
203+
const { config } = await loadConfig({ configPath: configFile }, logger)
204+
205+
expect(config).toBeNull()
206+
207+
await fs.rm(configFile)
208+
})
180209
})

0 commit comments

Comments
 (0)
Please sign in to comment.