Skip to content

Commit

Permalink
fix: ignore "package.json" as config file when it's invalid JSON (#1281)
Browse files Browse the repository at this point in the history
  • Loading branch information
iiroj authored Apr 7, 2023
1 parent 05fb382 commit e7ed6f7
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 2 deletions.
17 changes: 15 additions & 2 deletions lib/loadConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,14 @@ import { resolveConfig } from './resolveConfig.js'

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

const PACKAGE_JSON = 'package.json'

/**
* The list of files `lint-staged` will read configuration
* from, in the declared order.
*/
export const searchPlaces = [
'package.json',
PACKAGE_JSON,
'.lintstagedrc',
'.lintstagedrc.json',
'.lintstagedrc.yaml',
Expand All @@ -27,7 +29,18 @@ export const searchPlaces = [
'lint-staged.config.cjs',
]

const jsonParse = (path, content) => JSON.parse(content)
const jsonParse = (path, content) => {
try {
return JSON.parse(content)
} catch (error) {
if (path.endsWith(PACKAGE_JSON)) {
debugLog('Ignoring invalid package file `%s` with content:\n%s', path, content)
return undefined
}

throw error
}
}

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

Expand Down
29 changes: 29 additions & 0 deletions test/unit/loadConfig.spec.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import fs from 'node:fs/promises'
import path from 'node:path'

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

expect(result).toMatchInlineSnapshot(`{}`)
})

it('should return empty object ".lintstagedrc.json" file is invalid', async () => {
expect.assertions(1)

const configFile = path.join(__dirname, '__mocks__', '.lintstagedrc.json')

await fs.writeFile(configFile, '{')

const result = await loadConfig({ configPath: configFile }, logger)

expect(result).toMatchInlineSnapshot(`{}`)

await fs.rm(configFile)
})

it('should return null config when package.json file is invalid', async () => {
expect.assertions(1)

const configFile = path.join(__dirname, '__mocks__', 'package.json')

await fs.writeFile(configFile, '{')

const { config } = await loadConfig({ configPath: configFile }, logger)

expect(config).toBeNull()

await fs.rm(configFile)
})
})

0 comments on commit e7ed6f7

Please sign in to comment.