Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: ignore "package.json" as config file when it's invalid JSON #1281

Merged
merged 1 commit into from
Apr 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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)
})
})