Skip to content

Commit

Permalink
Merge pull request #138 from actions/error-utils
Browse files Browse the repository at this point in the history
Convert errors into Actions-compatible logging with annotations
  • Loading branch information
JamesMGreene authored Mar 28, 2024
2 parents b85f2a6 + fc47e3c commit 7781abd
Show file tree
Hide file tree
Showing 10 changed files with 574 additions and 31 deletions.
406 changes: 397 additions & 9 deletions dist/index.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion dist/index.js.map

Large diffs are not rendered by default.

46 changes: 46 additions & 0 deletions dist/licenses.txt
Original file line number Diff line number Diff line change
Expand Up @@ -513,6 +513,29 @@ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.


error-stack-parser
MIT
Copyright (c) 2017 Eric Wendelin and other contributors

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


eslint-visitor-keys
Apache-2.0
Apache License
Expand Down Expand Up @@ -766,6 +789,29 @@ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.


stackframe
MIT
Copyright (c) 2017 Eric Wendelin and other contributors

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


tunnel
MIT
The MIT License (MIT)
Expand Down
28 changes: 28 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,11 @@
"dependencies": {
"@actions/core": "^1.10.1",
"@actions/github": "^6.0.0",
"error-stack-parser": "^2.1.4",
"espree": "^9.6.1"
},
"devDependencies": {
"@octokit/request-error": "^5.0.1",
"@vercel/ncc": "^0.38.1",
"eslint": "^8.57.0",
"eslint-config-prettier": "^8.8.0",
Expand Down
11 changes: 6 additions & 5 deletions src/api-client.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const core = require('@actions/core')
const github = require('@actions/github')
const { convertErrorToAnnotationProperties } = require('./error-utils')

async function enablePagesSite({ githubToken }) {
const octokit = github.getOctokit(githubToken)
Expand Down Expand Up @@ -43,20 +44,20 @@ async function findOrCreatePagesSite({ githubToken, enablement = true }) {
} catch (error) {
if (!enablement) {
core.error(
'Get Pages site failed. Please verify that the repository has Pages enabled and configured to build using GitHub Actions, or consider exploring the `enablement` parameter for this action.',
error
`Get Pages site failed. Please verify that the repository has Pages enabled and configured to build using GitHub Actions, or consider exploring the \`enablement\` parameter for this action. Error: ${error.message}`,
convertErrorToAnnotationProperties(error)
)
throw error
}
core.warning('Get Pages site failed', error)
core.warning(`Get Pages site failed. Error: ${error.message}`, convertErrorToAnnotationProperties(error))
}

if (!pageObject && enablement) {
// Create a new Pages site if one doesn't exist
try {
pageObject = await enablePagesSite({ githubToken })
} catch (error) {
core.error('Create Pages site failed', error)
core.error(`Create Pages site failed. Error: ${error.message}`, convertErrorToAnnotationProperties(error))
throw error
}

Expand All @@ -66,7 +67,7 @@ async function findOrCreatePagesSite({ githubToken, enablement = true }) {
try {
pageObject = await getPagesSite({ githubToken })
} catch (error) {
core.error('Get Pages site still failed', error)
core.error(`Get Pages site still failed. Error: ${error.message}`, convertErrorToAnnotationProperties(error))
throw error
}
}
Expand Down
39 changes: 27 additions & 12 deletions src/api-client.test.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,24 @@
const core = require('@actions/core')
const apiClient = require('./api-client')
const { RequestError } = require('@octokit/request-error')

const mockGetPages = jest.fn()
const mockCreatePagesSite = jest.fn()

const generateRequestError = statusCode => {
const fakeRequest = { headers: {}, url: '/' }
const fakeResponse = { status: statusCode }
let message = 'Oops'
if (statusCode === 404) {
message = 'Not Found'
}
if (statusCode === 409) {
message = 'Too Busy'
}
const error = new RequestError(message, statusCode, { request: fakeRequest, response: fakeResponse })
return error
}

jest.mock('@actions/github', () => ({
context: {
repo: {
Expand Down Expand Up @@ -48,7 +63,7 @@ describe('apiClient', () => {
})

it('handles a 409 response when the page already exists', async () => {
mockCreatePagesSite.mockImplementationOnce(() => Promise.reject({ response: { status: 409 } }))
mockCreatePagesSite.mockImplementationOnce(() => Promise.reject(generateRequestError(409)))

// Simply assert that no error is raised
const result = await apiClient.enablePagesSite({
Expand All @@ -59,7 +74,7 @@ describe('apiClient', () => {
})

it('re-raises errors on failure status codes', async () => {
mockCreatePagesSite.mockImplementationOnce(() => Promise.reject({ response: { status: 404 } }))
mockCreatePagesSite.mockImplementationOnce(() => Promise.reject(generateRequestError(404)))

let erred = false
try {
Expand All @@ -86,7 +101,7 @@ describe('apiClient', () => {
})

it('re-raises errors on failure status codes', async () => {
mockGetPages.mockImplementationOnce(() => Promise.reject({ response: { status: 404 } }))
mockGetPages.mockImplementationOnce(() => Promise.reject(generateRequestError(404)))

let erred = false
try {
Expand All @@ -105,7 +120,7 @@ describe('apiClient', () => {
it('does not make a request to create a page if it already exists', async () => {
const PAGE_OBJECT = { html_url: 'https://actions.github.io/is-awesome/' }
mockGetPages.mockImplementationOnce(() => Promise.resolve({ status: 200, data: PAGE_OBJECT }))
mockCreatePagesSite.mockImplementationOnce(() => Promise.reject({ response: { status: 404 } }))
mockCreatePagesSite.mockImplementationOnce(() => Promise.reject(generateRequestError(404)))

const result = await apiClient.findOrCreatePagesSite({
githubToken: GITHUB_TOKEN
Expand All @@ -117,7 +132,7 @@ describe('apiClient', () => {

it('makes request to create a page by default if it does not exist', async () => {
const PAGE_OBJECT = { html_url: 'https://actions.github.io/is-awesome/' }
mockGetPages.mockImplementationOnce(() => Promise.reject({ response: { status: 404 } }))
mockGetPages.mockImplementationOnce(() => Promise.reject(generateRequestError(404)))
mockCreatePagesSite.mockImplementationOnce(() => Promise.resolve({ status: 201, data: PAGE_OBJECT }))

const result = await apiClient.findOrCreatePagesSite({
Expand All @@ -130,7 +145,7 @@ describe('apiClient', () => {

it('makes a request to create a page when explicitly enabled if it does not exist', async () => {
const PAGE_OBJECT = { html_url: 'https://actions.github.io/is-awesome/' }
mockGetPages.mockImplementationOnce(() => Promise.reject({ response: { status: 404 } }))
mockGetPages.mockImplementationOnce(() => Promise.reject(generateRequestError(404)))
mockCreatePagesSite.mockImplementationOnce(() => Promise.resolve({ status: 201, data: PAGE_OBJECT }))

const result = await apiClient.findOrCreatePagesSite({
Expand All @@ -143,8 +158,8 @@ describe('apiClient', () => {
})

it('does not make a request to create a page when explicitly disabled even if it does not exist', async () => {
mockGetPages.mockImplementationOnce(() => Promise.reject({ response: { status: 404 } }))
mockCreatePagesSite.mockImplementationOnce(() => Promise.reject({ response: { status: 500 } })) // just so they both aren't 404
mockGetPages.mockImplementationOnce(() => Promise.reject(generateRequestError(404)))
mockCreatePagesSite.mockImplementationOnce(() => Promise.reject(generateRequestError(500))) // just so they both aren't 404

let erred = false
try {
Expand All @@ -163,8 +178,8 @@ describe('apiClient', () => {
})

it('does not make a second request to get page if create fails for reason other than existence', async () => {
mockGetPages.mockImplementationOnce(() => Promise.reject({ response: { status: 404 } }))
mockCreatePagesSite.mockImplementationOnce(() => Promise.reject({ response: { status: 500 } })) // just so they both aren't 404
mockGetPages.mockImplementationOnce(() => Promise.reject(generateRequestError(404)))
mockCreatePagesSite.mockImplementationOnce(() => Promise.reject(generateRequestError(500))) // just so they both aren't 404

let erred = false
try {
Expand All @@ -184,9 +199,9 @@ describe('apiClient', () => {
it('makes second request to get page if create fails because of existence', async () => {
const PAGE_OBJECT = { html_url: 'https://actions.github.io/is-awesome/' }
mockGetPages
.mockImplementationOnce(() => Promise.reject({ response: { status: 404 } }))
.mockImplementationOnce(() => Promise.reject(generateRequestError(404)))
.mockImplementationOnce(() => Promise.resolve({ status: 200, data: PAGE_OBJECT }))
mockCreatePagesSite.mockImplementationOnce(() => Promise.reject({ response: { status: 409 } }))
mockCreatePagesSite.mockImplementationOnce(() => Promise.reject(generateRequestError(409)))

const result = await apiClient.findOrCreatePagesSite({
githubToken: GITHUB_TOKEN
Expand Down
24 changes: 24 additions & 0 deletions src/error-utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
const ErrorStackParser = require('error-stack-parser')

// Convert an Error's stack into `@actions/core` toolkit AnnotationProperties:
// https://github.com/actions/toolkit/blob/ef77c9d60bdb03700d7758b0d04b88446e72a896/packages/core/src/core.ts#L36-L71
function convertErrorToAnnotationProperties(error, title = error.name) {
if (!(error instanceof Error)) {
throw new TypeError('error must be an instance of Error')
}

const stack = ErrorStackParser.parse(error)
const firstFrame = stack && stack.length > 0 ? stack[0] : null
if (!firstFrame) {
throw new Error('Error stack is empty or unparseable')
}

return {
title,
file: firstFrame.fileName,
startLine: firstFrame.lineNumber,
startColumn: firstFrame.columnNumber
}
}

module.exports = { convertErrorToAnnotationProperties }
38 changes: 38 additions & 0 deletions src/error-utils.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
const { convertErrorToAnnotationProperties } = require('./error-utils')

describe('error-utils', () => {
describe('convertErrorToAnnotationProperties', () => {
it('throws a TypeError if the first argument is not an Error instance', () => {
expect(() => convertErrorToAnnotationProperties('not an Error')).toThrow(
TypeError,
'error must be an instance of Error'
)
})

it('throws an Error if the first argument is an Error instance without a parseable stack', () => {
const error = new Error('Test error')
error.stack = ''
expect(() => convertErrorToAnnotationProperties(error)).toThrow(Error, 'Error stack is empty or unparseable')
})

it('returns an AnnotationProperties-compatible object', () => {
const result = convertErrorToAnnotationProperties(new TypeError('Test error'))
expect(result).toEqual({
title: 'TypeError',
file: __filename,
startLine: expect.any(Number),
startColumn: expect.any(Number)
})
})

it('returns an AnnotationProperties-compatible object with a custom title', () => {
const result = convertErrorToAnnotationProperties(new TypeError('Test error'), 'custom title')
expect(result).toEqual({
title: 'custom title',
file: __filename,
startLine: expect.any(Number),
startColumn: expect.any(Number)
})
})
})
})
9 changes: 5 additions & 4 deletions src/set-pages-config.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const core = require('@actions/core')
const { ConfigParser } = require('./config-parser')
const removeTrailingSlash = require('./remove-trailing-slash')
const { convertErrorToAnnotationProperties } = require('./error-utils')

const SUPPORTED_FILE_EXTENSIONS = ['.js', '.cjs', '.mjs']

Expand Down Expand Up @@ -88,13 +89,13 @@ function setPagesConfig({ staticSiteGenerator, generatorConfigFile, siteUrl }) {
core.warning(
`Unsupported configuration file extension. Currently supported extensions: ${SUPPORTED_FILE_EXTENSIONS.map(
ext => JSON.stringify(ext)
).join(', ')}`,
error
).join(', ')}. Error: ${error.message}`,
convertErrorToAnnotationProperties(error)
)
} else {
core.warning(
`We were unable to determine how to inject the site metadata into your config. Generated URLs may be incorrect. The base URL for this site should be ${siteUrl}. Please ensure your framework is configured to generate relative links appropriately.`,
error
`We were unable to determine how to inject the site metadata into your config. Generated URLs may be incorrect. The base URL for this site should be ${siteUrl}. Please ensure your framework is configured to generate relative links appropriately. Error: ${error.message}`,
convertErrorToAnnotationProperties(error)
)
}
}
Expand Down

0 comments on commit 7781abd

Please sign in to comment.