Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: wrangler logs #256

Merged
merged 13 commits into from
Mar 10, 2024
5 changes: 5 additions & 0 deletions .changeset/cold-wombats-swim.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"github-actions-cloudflare-pages": minor
---

feat: wrangler output shown in summary and PR comment
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,9 @@ environment:
alias:
description: 'Cloudflare Pages deployed alias. Fallsback to deployed url if deployed alias is null'
value: ${{ steps.action.outputs.alias }}
wrangler:
description: 'Wrangler cli output'
values: ${{ steps.action.outputs.wrangler }}
```

## Comment Example
Expand Down
2 changes: 2 additions & 0 deletions __mocks__/@unlike/github-actions-core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,11 @@ export const notice = vi.fn()
export const debug = vi.fn()
export const isDebug = vi.fn().mockReturnValue(false)
export const setFailed = vi.fn()
export const info = vi.fn()

export const summary = core.summary
summary.addTable = vi.fn().mockReturnValue(summary)
summary.addHeading = vi.fn().mockReturnValue(summary)
summary.addBreak = vi.fn().mockReturnValue(summary)
summary.addRaw = vi.fn().mockReturnValue(summary)
summary.write = vi.fn()
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html

exports[`createCloudflareDeployment > api calls > handles success 1`] = `
exports[`createCloudflareDeployment > api calls > handles success 2`] = `
{
"aliases": [
"https://unknown-branch.cloudflare-pages-action-a5z.pages.dev",
Expand Down
23 changes: 15 additions & 8 deletions __tests__/cloudflare/deployment/create.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {setOutput, summary} from '@unlike/github-actions-core'
import {info, setOutput, summary} from '@unlike/github-actions-core'
import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest'

import type {MockApi} from '@/tests/helpers/api.js'
Expand All @@ -19,6 +19,7 @@ vi.mock('@unlike/github-actions-core')
describe('createCloudflareDeployment', () => {
describe('api calls', () => {
let mockApi: MockApi

beforeEach(() => {
mockApi = setMockApi()
})
Expand All @@ -28,8 +29,8 @@ describe('createCloudflareDeployment', () => {
})

test('handles thrown error from wrangler deploy', async () => {
expect.assertions(9)
vi.mocked(execAsync).mockRejectedValue({stderr: 'Oh no!'})
expect.assertions(10)
vi.mocked(execAsync).mockRejectedValue({stderr: 'Oh no!', stdout: ''})

// Expect Cloudflare Api Token and Account Id to be undefined.
expect(process.env[CLOUDFLARE_API_TOKEN]).toBeUndefined()
Expand All @@ -51,6 +52,7 @@ describe('createCloudflareDeployment', () => {
)

expect(execAsync).toHaveBeenCalledTimes(1)
expect(info).not.toHaveBeenCalled()
expect(process.env[CLOUDFLARE_API_TOKEN]).toBe(
'mock-cloudflare-api-token'
)
Expand All @@ -63,7 +65,7 @@ describe('createCloudflareDeployment', () => {
})

test('handles thrown error from getDeployments', async () => {
expect.assertions(4)
expect.assertions(5)
vi.mocked(execAsync).mockResolvedValue({
stdout: 'success',
stderr: ''
Expand All @@ -81,12 +83,13 @@ describe('createCloudflareDeployment', () => {
`[ParseError: A request to the Cloudflare API (https://api.cloudflare.com/client/v4/accounts/mock-cloudflare-account-id/pages/projects/mock-cloudflare-project-name/deployments) failed.]`
)
expect(execAsync).toHaveBeenCalledTimes(1)
expect(info).toHaveBeenLastCalledWith('success')
expect(setOutput).not.toHaveBeenCalled()
expect(summary.addTable).not.toHaveBeenCalled()
})

test('handles success', async () => {
expect.assertions(11)
expect.assertions(14)
vi.mocked(execAsync).mockResolvedValue({
stdout: 'success',
stderr: ''
Expand All @@ -106,14 +109,16 @@ describe('createCloudflareDeployment', () => {
200
)

const deployment = await createCloudflareDeployment()
const {deployment, wranglerOutput} = await createCloudflareDeployment()

expect(wranglerOutput).toMatchInlineSnapshot(`"success"`)
expect(deployment).toMatchSnapshot()
expect(deployment.id).toMatchInlineSnapshot(
'"206e215c-33b3-4ce4-adf4-7fc6c9b65483"'
)
expect(info).toHaveBeenLastCalledWith('success')

expect(setOutput).toHaveBeenCalledTimes(4)
expect(setOutput).toHaveBeenCalledTimes(5)
expect(setOutput).toHaveBeenNthCalledWith(
1,
'id',
Expand All @@ -130,6 +135,7 @@ describe('createCloudflareDeployment', () => {
'alias',
'https://unknown-branch.cloudflare-pages-action-a5z.pages.dev'
)
expect(setOutput).toHaveBeenNthCalledWith(5, 'wrangler', 'success')

expect(summary.addHeading).toHaveBeenCalledWith(
`Cloudflare Pages Deployment`
Expand Down Expand Up @@ -166,7 +172,8 @@ describe('createCloudflareDeployment', () => {
[
'Branch Preview URL:',
`<a href='https://unknown-branch.cloudflare-pages-action-a5z.pages.dev'>https://unknown-branch.cloudflare-pages-action-a5z.pages.dev</a>`
]
],
['Wrangler Output:', `success`]
])
})
})
Expand Down
6 changes: 3 additions & 3 deletions __tests__/github/comment.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ describe('addComment', () => {
query: MutationAddComment,
variables: {
subjectId: 'MDExOlB1bGxSZXF1ZXN0Mjc5MTQ3NDM3',
body: '## Cloudflare Pages Deployment\n **Environment:** production \n **Project:** cloudflare-pages-action \n **Built with commit:** mock-github-sha\n **Preview URL:** https://206e215c.cloudflare-pages-action-a5z.pages.dev \n **Branch Preview URL:** https://unknown-branch.cloudflare-pages-action-a5z.pages.dev'
body: '## Cloudflare Pages Deployment\n**Environment:** production\n**Project:** cloudflare-pages-action\n**Built with commit:** mock-github-sha\n**Preview URL:** https://206e215c.cloudflare-pages-action-a5z.pages.dev\n**Branch Preview URL:** https://unknown-branch.cloudflare-pages-action-a5z.pages.dev\n\n### Wrangler Output\nsuccess'
}
},
{
Expand All @@ -46,7 +46,7 @@ describe('addComment', () => {
}
)

const comment = await addComment(mockData)
const comment = await addComment(mockData, 'success')
expect(comment).toBe('1')
})

Expand All @@ -64,7 +64,7 @@ describe('addComment', () => {
payload: {}
} as Readonly<WorkflowEventExtract<typeof eventName>>)

await expect(addComment(mockData)).resolves.toBeUndefined()
await expect(addComment(mockData, 'success')).resolves.toBeUndefined()
}
)
})
7 changes: 6 additions & 1 deletion __tests__/main.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import type {MockApi} from '@/tests/helpers/api.js'
import RESPONSE_DEPLOYMENTS from '@/responses/api.cloudflare.com/pages/deployments/deployments.response.json'
import RESPONSE_PROJECT from '@/responses/api.cloudflare.com/pages/projects/project.response.json'
import {run} from '@/src/main.js'
import {execAsync} from '@/src/utils.js'
import {
MOCK_API_PATH,
MOCK_API_PATH_DEPLOYMENTS,
Expand Down Expand Up @@ -34,6 +35,10 @@ describe('main', () => {
describe('run', () => {
describe('handles resolve', () => {
beforeEach(() => {
vi.mocked(execAsync).mockResolvedValue({
stdout: 'success',
stderr: ''
})
mockApi.interceptCloudflare(MOCK_API_PATH, RESPONSE_PROJECT, 200)
mockApi.interceptCloudflare(
MOCK_API_PATH_DEPLOYMENTS,
Expand All @@ -49,7 +54,7 @@ describe('main', () => {

expect(main).toBeUndefined()

expect(spySetOutput).toHaveBeenCalledTimes(4)
expect(spySetOutput).toHaveBeenCalledTimes(5)
// TODO @andykenward add checks for setOutput
mockApi.mockAgent.assertNoPendingInterceptors()
})
Expand Down
2 changes: 2 additions & 0 deletions action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ outputs:
description: 'Cloudflare Pages deployed environment "production" or "preview"'
alias:
description: 'Cloudflare Pages deployed alias. Fallsback to deployed url if deployed alias is null'
wrangler:
description: 'Wrangler cli output'

runs:
using: node20
Expand Down
19 changes: 11 additions & 8 deletions dist/index.js

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions dist/index.js.map

Large diffs are not rendered by default.

Binary file modified docs/comment.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
25 changes: 18 additions & 7 deletions src/cloudflare/deployment/create.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import {strict} from 'node:assert'

import {setOutput, summary} from '@unlike/github-actions-core'
import {info, setOutput, summary} from '@unlike/github-actions-core'

import type {PagesDeployment} from '../types.js'

import {useContext} from '../../github/context.js'
import {useInputs} from '../../inputs.js'
Expand All @@ -12,7 +14,10 @@ export const CLOUDFLARE_API_TOKEN = 'CLOUDFLARE_API_TOKEN'
export const CLOUDFLARE_ACCOUNT_ID = 'CLOUDFLARE_ACCOUNT_ID'
const ERROR_KEY = `Create Deployment:`

export const createCloudflareDeployment = async () => {
export const createCloudflareDeployment = async (): Promise<{
deployment: PagesDeployment
wranglerOutput: string
}> => {
const {
cloudflareAccountId,
cloudflareProjectName,
Expand Down Expand Up @@ -41,12 +46,16 @@ export const createCloudflareDeployment = async () => {
/**
* Tried to use wrangler.unstable_pages.deploy. But wrangler is 8mb+ and the bundler is unable to tree shake it.
*/
await execAsync(
const {stdout} = await execAsync(
`npx wrangler@${WRANGLER_VERSION} pages deploy ${directory} --project-name=${cloudflareProjectName} --branch=${branch} --commit-dirty=true --commit-hash=${commitHash}`,
{
env: process.env
}
)
/**
* Log out wrangler output.
*/
info(stdout)
/**
* Get the latest deployment by commitHash and poll until required status.
*/
Expand All @@ -58,10 +67,11 @@ export const createCloudflareDeployment = async () => {

const alias: string = getCloudflareDeploymentAlias(deployment)
setOutput('alias', alias)
setOutput('wrangler', stdout)

await summary.addHeading('Cloudflare Pages Deployment').write()
await summary.addBreak().write()
await summary
.addHeading('Cloudflare Pages Deployment')
.addBreak()
.addTable([
[
{
Expand All @@ -88,11 +98,12 @@ export const createCloudflareDeployment = async () => {
],
['Status:', `<strong>${status.toUpperCase() || `UNKNOWN`}</strong>`],
['Preview URL:', `<a href='${deployment.url}'>${deployment.url}</a>`],
['Branch Preview URL:', `<a href='${alias}'>${alias}</a>`]
['Branch Preview URL:', `<a href='${alias}'>${alias}</a>`],
['Wrangler Output:', `${stdout}`]
])
.write()

return deployment
return {deployment, wranglerOutput: stdout}
} catch (error) {
if (error instanceof Error) {
throw error
Expand Down
11 changes: 3 additions & 8 deletions src/github/comment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ export const MutationAddComment = graphql(/* GraphQL */ `
`)

export const addComment = async (
deployment: PagesDeployment
deployment: PagesDeployment,
output: string
): Promise<string | undefined> => {
const {eventName, payload} = useContextEvent()

Expand All @@ -30,13 +31,7 @@ export const addComment = async (

const {sha} = useContext()

const rawBody = `## Cloudflare Pages Deployment\n **Environment:** ${
deployment.environment
} \n **Project:** ${
deployment.project_name
} \n **Built with commit:** ${sha}\n **Preview URL:** ${
deployment.url
} \n **Branch Preview URL:** ${getCloudflareDeploymentAlias(deployment)}`
const rawBody = `## Cloudflare Pages Deployment\n**Environment:** ${deployment.environment}\n**Project:** ${deployment.project_name}\n**Built with commit:** ${sha}\n**Preview URL:** ${deployment.url}\n**Branch Preview URL:** ${getCloudflareDeploymentAlias(deployment)}\n\n### Wrangler Output\n${output}`

const comment = await request({
query: MutationAddComment,
Expand Down
5 changes: 3 additions & 2 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ export async function run() {
}
}

const cloudflareDeployment = await createCloudflareDeployment()
const commentId = await addComment(cloudflareDeployment)
const {deployment: cloudflareDeployment, wranglerOutput} =
await createCloudflareDeployment()
const commentId = await addComment(cloudflareDeployment, wranglerOutput)
await createGitHubDeployment(cloudflareDeployment, commentId)
}