diff --git a/packages/github/__tests__/invalid-payload.json b/packages/github/__tests__/invalid-payload.json new file mode 100644 index 0000000000..98232c64fc --- /dev/null +++ b/packages/github/__tests__/invalid-payload.json @@ -0,0 +1 @@ +{ diff --git a/packages/github/__tests__/lib.test.ts b/packages/github/__tests__/lib.test.ts index e77e79c627..6ce8e624ac 100644 --- a/packages/github/__tests__/lib.test.ts +++ b/packages/github/__tests__/lib.test.ts @@ -1,5 +1,6 @@ import * as path from 'path' import {readFileSync} from 'fs' +import {EOL} from 'os' import {Context} from '../src/context.js' describe('@actions/context', () => { @@ -25,6 +26,21 @@ describe('@actions/context', () => { expect(context.payload).toEqual({}) }) + it('returns an empty payload when the event payload is invalid JSON', () => { + process.env.GITHUB_EVENT_PATH = path.join(__dirname, 'invalid-payload.json') + const write = jest + .spyOn(process.stdout, 'write') + .mockImplementation(() => true) + + context = new Context() + + expect(context.payload).toEqual({}) + expect(write).toHaveBeenCalledWith( + `GITHUB_EVENT_PATH ${process.env.GITHUB_EVENT_PATH} contains invalid JSON${EOL}` + ) + write.mockRestore() + }) + it('returns attributes from the GITHUB_REPOSITORY', () => { expect(context.repo).toEqual({owner: 'actions', repo: 'toolkit'}) }) diff --git a/packages/github/src/context.ts b/packages/github/src/context.ts index 60554fd322..4822960b5e 100644 --- a/packages/github/src/context.ts +++ b/packages/github/src/context.ts @@ -30,9 +30,20 @@ export class Context { this.payload = {} if (process.env.GITHUB_EVENT_PATH) { if (existsSync(process.env.GITHUB_EVENT_PATH)) { - this.payload = JSON.parse( - readFileSync(process.env.GITHUB_EVENT_PATH, {encoding: 'utf8'}) - ) + try { + this.payload = JSON.parse( + readFileSync(process.env.GITHUB_EVENT_PATH, {encoding: 'utf8'}) + ) + } catch (error) { + if (error instanceof SyntaxError) { + const path = process.env.GITHUB_EVENT_PATH + process.stdout.write( + `GITHUB_EVENT_PATH ${path} contains invalid JSON${EOL}` + ) + } else { + throw error + } + } } else { const path = process.env.GITHUB_EVENT_PATH process.stdout.write(`GITHUB_EVENT_PATH ${path} does not exist${EOL}`)