diff --git a/lib/loadConfig.js b/lib/loadConfig.js index 43e281eff..7362ddee0 100644 --- a/lib/loadConfig.js +++ b/lib/loadConfig.js @@ -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', @@ -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) diff --git a/test/unit/loadConfig.spec.js b/test/unit/loadConfig.spec.js index 7dfbb7b52..3747519fd 100644 --- a/test/unit/loadConfig.spec.js +++ b/test/unit/loadConfig.spec.js @@ -1,3 +1,4 @@ +import fs from 'node:fs/promises' import path from 'node:path' import makeConsoleMock from 'consolemock' @@ -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) + }) })