Skip to content

Commit

Permalink
fix: prevent cli tool from choking because of $schema property in rc …
Browse files Browse the repository at this point in the history
…json file (#1297)
  • Loading branch information
vighnesh153 committed May 5, 2023
1 parent 89bb7ca commit 8ecf72c
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
9 changes: 8 additions & 1 deletion src/lib/getNcuRc.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import flatten from 'lodash/flatten'
import map from 'lodash/map'
import omit from 'lodash/omit'
import path from 'path'
import { rcFile } from 'rc-config-loader'
import { cliOptionsMap } from '../cli-options'
Expand All @@ -24,12 +25,18 @@ async function getNcuRc({ color, configFileName, configFilePath, packageFile }:
const { default: chalkDefault, Chalk } = await import('chalk')
const chalk = color ? new Chalk({ level: 1 }) : chalkDefault

const result = rcFile('ncurc', {
const rawResult = rcFile('ncurc', {
configFileName: configFileName || '.ncurc',
defaultExtension: ['.json', '.yml', '.js'],
cwd: configFilePath || (packageFile ? path.dirname(packageFile) : undefined),
})

const result = {
filePath: rawResult?.filePath,
// Prevent the cli tool from choking because of an unknown option "$schema"
config: omit(rawResult?.config, '$schema'),
}

// validate arguments here to provide a better error message
const unknownOptions = Object.keys(result?.config || {}).filter(arg => !cliOptionsMap[arg])
if (unknownOptions.length > 0) {
Expand Down
15 changes: 15 additions & 0 deletions test/rc-config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -203,4 +203,19 @@ describe('rc-config', () => {
await fs.rm(tempDir, { recursive: true, force: true })
}
})

it('should not crash if because of $schema property', async () => {
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'npm-check-updates-'))
const configFile = path.join(tempDir, '.ncurc.json')
const pkgFile = path.join(tempDir, 'package.json')
await fs.writeFile(configFile, JSON.stringify({ $schema: 'schema url' }), 'utf-8')
await fs.writeFile(pkgFile, JSON.stringify({ dependencies: { axios: '1.0.0' } }), 'utf-8')

try {
// awkwardly, we have to set mergeConfig to enable autodetecting the rcconfig because otherwise it is explicitly disabled for tests
await spawn('node', [bin, '--mergeConfig'], { cwd: tempDir })
} finally {
await fs.rm(tempDir, { recursive: true, force: true })
}
})
})

0 comments on commit 8ecf72c

Please sign in to comment.