Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/github/__tests__/invalid-payload.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{
16 changes: 16 additions & 0 deletions packages/github/__tests__/lib.test.ts
Original file line number Diff line number Diff line change
@@ -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', () => {
Expand All @@ -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()
})
Comment on lines +31 to +42

it('returns attributes from the GITHUB_REPOSITORY', () => {
expect(context.repo).toEqual({owner: 'actions', repo: 'toolkit'})
})
Expand Down
17 changes: 14 additions & 3 deletions packages/github/src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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}`)
Expand Down