diff --git a/scripts/ci/validate-hooks.js b/scripts/ci/validate-hooks.js index 65aac98e2..ff24bfe25 100644 --- a/scripts/ci/validate-hooks.js +++ b/scripts/ci/validate-hooks.js @@ -293,6 +293,7 @@ function checkHookDuplicates(source, eventMap) { const events = new Map(); const ids = new Map(); const rootProperties = []; + let eventMapLine = null; function checkEvent(key, line) { if (events.has(key)) { @@ -306,7 +307,12 @@ function checkHookDuplicates(source, eventMap) { const parent = getPath(); if (parent.length === 1 && parent[0] === eventMap) { checkEvent(key, line); - } else if (parent.length === 0 && eventMap === 'hooks') { + } else if (parent.length === 0 && key === eventMap) { + if (eventMapLine !== null) { + throw new Error(`line ${line + 1}: duplicate root key '${key}' (first on line ${eventMapLine})`); + } + eventMapLine = line + 1; + } else if (parent.length === 0 && eventMap === 'hooks' && eventMapLine === null) { rootProperties.push({ key, line }); } }, @@ -326,7 +332,7 @@ function checkHookDuplicates(source, eventMap) { // A hooks wrapper can appear after other root properties. Only an unwrapped // manifest uses those root properties as its event map. - if (!rootProperties.some(({ key }) => key === 'hooks')) { + if (eventMapLine === null) { for (const { key, line } of rootProperties) checkEvent(key, line); } } diff --git a/tests/ci/validators.test.js b/tests/ci/validators.test.js index e1eeb3014..83ce8f4ea 100644 --- a/tests/ci/validators.test.js +++ b/tests/ci/validators.test.js @@ -3038,6 +3038,31 @@ function runTests() { cleanupTestDir(testDir); } })) passed++; else failed++; + + if (test(`rejects a repeated root ${eventMap} key in ${file}`, () => { + const testDir = createTestDir(); + try { + const hooksFile = path.join(testDir, 'hooks.json'); + writeJson(hooksFile, { hooks: {} }); + const firstEntry = eventMap === 'hooks' + ? { id: 'first', hooks: [{ type: 'command', command: 'echo first' }] } + : { id: 'first', fingerprint: '0123456789ab' }; + fs.writeFileSync(path.join(testDir, file), `{"${eventMap}": + ${JSON.stringify({ Stop: [firstEntry] })}, + "${eventMap}": {} +}`); + const result = runValidatorWithDirs('validate-hooks', { + HOOKS_FILE: hooksFile, + HOOKS_SCHEMA_PATH: path.join(repoRoot, 'schemas', 'hooks.schema.json'), + METADATA_SCHEMA_PATH: path.join(repoRoot, 'schemas', 'hooks-metadata.schema.json'), + }); + assert.strictEqual(result.code, 1, result.stdout); + const diagnostic = `${file}: line 3: duplicate root key '${eventMap}' (first on line 1)`; + assert.ok(result.stderr.includes(diagnostic), result.stderr); + } finally { + cleanupTestDir(testDir); + } + })) passed++; else failed++; } if (test('reports duplicate root events in a schema-free unwrapped hook map', () => {