Compare commits

..

5 Commits

Author SHA1 Message Date
James M. Greene
c7b5c1034e Update distributables 2023-06-15 15:14:49 -05:00
James M. Greene
b4d15f6490 Merge branch 'main' into error-count 2023-06-15 15:11:35 -05:00
James M. Greene
c883148031 Separate tests for Deployment##setOptionalUserInput to limit scope 2023-06-15 15:09:03 -05:00
Greta Parks
b1a18fc1bd little nits
Co-authored-by: James M. Greene <JamesMGreene@github.com>
2023-06-14 17:02:05 +00:00
Greta Parks
a378718509 adds a check for error_count variable 2023-05-22 22:59:30 +00:00
25 changed files with 8836 additions and 158744 deletions

View File

@@ -4,14 +4,8 @@ updates:
directory: '/'
schedule:
interval: 'weekly'
groups:
non-breaking-changes:
update-types: [minor, patch]
- package-ecosystem: 'npm'
directory: '/'
schedule:
interval: 'weekly'
groups:
non-breaking-changes:
update-types: [minor, patch]

View File

@@ -10,7 +10,7 @@ template: |
See details of [all code changes](https://github.com/$OWNER/$REPOSITORY/compare/$PREVIOUS_TAG...v$RESOLVED_VERSION) since previous release.
:warning: For use with products other than GitHub.com, such as GitHub Enterprise Server, please consult the [compatibility table](https://github.com/$OWNER/$REPOSITORY/#compatibility).
:warning: For use with products other than GitHub.com, such as GitHub Enterprise Server, please consult the [compatibility table](https://github.com/$OWNER/$REPOSITORY/#compatibilty).
categories:
- title: '🚀 Features'
labels:

View File

@@ -22,10 +22,10 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v3
- name: Setup Node.JS
uses: actions/setup-node@v4
uses: actions/setup-node@v3
with:
node-version-file: '.node-version'
cache: npm
@@ -46,7 +46,7 @@ jobs:
fi
# If index.js was different than expected, upload the expected version as an artifact
- uses: actions/upload-artifact@v4
- uses: actions/upload-artifact@v3
if: ${{ failure() && steps.diff.conclusion == 'failure' }}
with:
name: dist

View File

@@ -19,10 +19,10 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v3
- name: Setup Node.JS
uses: actions/setup-node@v4
uses: actions/setup-node@v3
with:
node-version-file: '.node-version'
cache: npm

View File

@@ -19,10 +19,10 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v3
- name: Setup Node.JS
uses: actions/setup-node@v4
uses: actions/setup-node@v3
with:
node-version-file: '.node-version'
cache: npm

View File

@@ -38,11 +38,11 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v3
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v3
uses: github/codeql-action/init@v2
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
@@ -53,7 +53,7 @@ jobs:
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v3
uses: github/codeql-action/autobuild@v2
# Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
@@ -67,4 +67,4 @@ jobs:
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v3
uses: github/codeql-action/analyze@v2

View File

@@ -11,6 +11,6 @@ jobs:
draft-release:
runs-on: ubuntu-latest
steps:
- uses: release-drafter/release-drafter@3f0f87098bd6b5c5b9a36d49c41d998ea58f9348 # v6.0.0
- uses: release-drafter/release-drafter@569eb7ee3a85817ab916c8f8ff03a5bd96c9c83e # v5.23.0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -1,20 +0,0 @@
name: 'Publish Immutable Action Version'
on:
release:
types: [published]
jobs:
publish:
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write
packages: write
steps:
- name: Checking out
uses: actions/checkout@v4
- name: Publish
id: publish
uses: actions/publish-immutable-action@0.0.3

View File

@@ -22,12 +22,12 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v3
with:
token: ${{ secrets.PAGES_AUTOMATION_PAT }}
- name: Setup Node.JS
uses: actions/setup-node@v4
uses: actions/setup-node@v3
with:
node-version-file: '.node-version'
cache: npm
@@ -45,7 +45,7 @@ jobs:
git add dist/
git config --local user.name "github-actions[bot]"
git config --local user.email "github-actions[bot]@users.noreply.github.com"
git commit -m "[dependabot skip] Update distributables after Dependabot 🤖"
git commit -m "Update distributables after Dependabot 🤖"
echo "Pushing branch ${{ github.ref_name }}"
git push origin ${{ github.ref_name }}
fi

View File

@@ -24,7 +24,7 @@ jobs:
steps:
- name: Update the ${{ env.TAG_NAME }} tag
id: update-major-tag
uses: actions/publish-action@v0.3.0
uses: actions/publish-action@v0.2.2
with:
source-tag: ${{ env.TAG_NAME }}
slack-webhook: ${{ secrets.SLACK_WEBHOOK }}

View File

@@ -14,10 +14,10 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v3
- name: Setup Node.JS
uses: actions/setup-node@v4
uses: actions/setup-node@v3
with:
node-version-file: '.node-version'
cache: npm

View File

@@ -1 +1 @@
20.10.0
18.9.0

View File

@@ -6,11 +6,11 @@ This action is used to deploy [Actions artifacts][artifacts] to [GitHub Pages](h
## Usage
See [action.yml](action.yml) for the various `inputs` this action supports (or [below](#inputs-📥)).
See [action.yml](action.yml) for the various `inputs` this action supports.
For examples that make use of this action, check out our [starter-workflows][starter-workflows] in a variety of frameworks.
This action deploys a Pages site previously uploaded as an artifact (e.g. using [`actions/upload-pages-artifact`][upload-pages-artifact]).
This action expects an artifact named `github-pages` to have been created prior to execution. This is done automatically when using [`actions/upload-pages-artifact`][upload-pages-artifact].
We recommend this action to be used in a dedicated job:
@@ -41,7 +41,7 @@ jobs:
steps:
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4 # or specific "vX.X.X" version tag for this action
uses: actions/deploy-pages@v2 # or the latest "vX.X.X" version tag for this action
```
### Inputs 📥
@@ -51,7 +51,7 @@ jobs:
| `token` | `true` | `${{ github.token }}` | The GitHub token used to create an authenticated client - Provided for you by default! |
| `timeout` | `false` | `"600000"` | Time in milliseconds after which to timeout and cancel the deployment (default: 10 minutes) |
| `error_count` | `false` | `"10"` | Maximum number of status report errors before cancelling a deployment (default: 10) |
| `reporting_interval` | `false` | `"5000"` | Time in milliseconds between two deployment status reports (default: 5 seconds) |
| `reporting_interval` | `false` | `"5000"` | Time in milliseconds between two deployment status report (default: 5 seconds) |
| `artifact_name` | `false` | `"github-pages"` | The name of the artifact to deploy |
| `preview` | `false` | `"false"` | Is this attempting to deploy a pull request as a GitHub Pages preview site? (NOTE: This feature is only in alpha currently and is not available to the public!) |
@@ -67,11 +67,15 @@ jobs:
| -------- | ----------- |
| `GITHUB_PAGES` | This environment variable is created and set to the string value `"true"` so that framework build tools may choose to differentiate their output based on the intended target hosting platform. |
## Scope
⚠️ Official support for building Pages with Actions is in public beta at the moment.
## Security Considerations
There are a few important considerations to be aware of:
1. The artifact being deployed must have been uploaded in a previous step, either in the same job or a separate job that doesn't execute until the upload is complete. See [`actions/upload-pages-artifact`][upload-pages-artifact] for more information about the format of the artifact we expect.
1. The artifact being deployed must have been uploaded in a previous step, either in the same job or a separate job that doesn't execute until the upload is complete.
2. The job that executes the deployment must at minimum have the following permissions:
- `pages: write`
@@ -83,26 +87,18 @@ There are a few important considerations to be aware of:
5. If your Pages site is using GitHub Actions as the source, while not required we highly recommend you also [protect your environment][environment-protection] (we will configure it by default for you).
## OIDC
When we invoke a job using GitHub Actions the job requests an OIDC token from GitHub's OIDC provider which responds with a JSON web token (JWT). Each token is unique to each workflow job [learn more about OIDC tokens](https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/about-security-hardening-with-openid-connect#understanding-the-oidc-token).
OIDC tokens are minted within the context of a single job, and are used to form a trust relationship which validates properties of the workflow run against a third-party (e.g. cloud providers such as AWS or Azure). In the context of GitHub Pages, this is most relevant to ensure a workflow respects branch protection settings. To do this, the OIDC token includes a claim about which branch/ref is executing the workflow. The token is passed to the pages deployment API as part of the request payload, where it's decoded internally to validate the claims and verify if that workflow is allowed to deploy to pages.
A common question regarding OIDC tokens is the need to use both `pages:write` and `id-token:write`. The pages permission relates to the `GITHUB_TOKEN` by giving it the permissions to create pages deployments when calling the GitHub API. The id-token permission is necessary to request the OIDC JWT token. For more information on the id-token, check the docs on [adding permissions settings](https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/configuring-openid-connect-in-cloud-providers#adding-permissions-settings).
## Compatibility
This action is primarily designed for use with GitHub.com's Actions workflows and Pages deployments. However, certain releases should also be compatible with GitHub Enterprise Server (GHES) `3.7` and above.
This action is primarily design for use with GitHub.com's Actions workflows and Pages deployments. However, certain releases should also be compatible with GitHub Enterprise Server (GHES) `3.7` and above.
| Release | GHES Compatibility |
|:---|:---|
| [`v4`](https://github.com/actions/deploy-pages/releases/tag/v4) | :warning: Incompatible at this time |
| [`v3`](https://github.com/actions/deploy-pages/releases/tag/v3) | `>= 3.9` |
| `v3.x.x` | `>= 3.9` |
| [`v2`](https://github.com/actions/deploy-pages/releases/tag/v2) | `>= 3.9` |
| `v2.x.x` | `>= 3.9` |
| [`v2`](https://github.com/actions/deploy-pages/releases/tag/v2) | 🛑 Incompatible. Anticipating compatibility with `>= 3.9`. |
| [`v2.0.1`](https://github.com/actions/deploy-pages/releases/tag/v2.0.1) | 🛑 Incompatible. Anticipating compatibility with `>= 3.9`. |
| [`v2.0.0`](https://github.com/actions/deploy-pages/releases/tag/v2.0.0) | 🛑 Incompatible. Anticipating compatibility with `>= 3.9`. |
| [`v1`](https://github.com/actions/deploy-pages/releases/tag/v1) | `>= 3.7` |
| [`v1.2.8`](https://github.com/actions/deploy-pages/releases/tag/v1.2.8) | `>= 3.7` |
| [`v1.2.7`](https://github.com/actions/deploy-pages/releases/tag/v1.2.7) | :warning: `>= 3.9` [Incompatible with prior versions!](https://github.com/actions/deploy-pages/issues/137) |
| [`v1.2.7`](https://github.com/actions/deploy-pages/releases/tag/v1.2.7) | :warning: [Incompatible](https://github.com/actions/deploy-pages/issues/137). Anticipating compatibility with `>= 3.9`. |
| [`v1.2.6`](https://github.com/actions/deploy-pages/releases/tag/v1.2.6) | `>= 3.7` |
| `v1.x.x` | `>= 3.7` |
@@ -114,7 +110,7 @@ In order to release a new version of this Action:
2. Publish the draft release from the `main` branch with semantic version as the tag name, _with_ the checkbox to publish to the GitHub Marketplace checked. :ballot_box_with_check:
3. After publishing the release, the [`release` workflow][release] will automatically run to create/update the corresponding major version tag such as `v1`.
3. After publishing the release, the [`release` workflow][release] will automatically run to create/update the corresponding the major version tag such as `v1`.
⚠️ Environment approval is required. Check the [Release workflow run list][release-workflow-runs].

View File

@@ -2,7 +2,7 @@ name: 'Deploy GitHub Pages site'
description: 'A GitHub Action to deploy an artifact as a GitHub Pages site'
author: 'GitHub'
runs:
using: 'node20'
using: 'node16'
main: 'dist/index.js'
inputs:
token:

View File

@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="116" height="20" role="img" aria-label="Coverage: 80.84%"><title>Coverage: 80.84%</title><linearGradient id="s" x2="0" y2="100%"><stop offset="0" stop-color="#bbb" stop-opacity=".1"/><stop offset="1" stop-opacity=".1"/></linearGradient><clipPath id="r"><rect width="116" height="20" rx="3" fill="#fff"/></clipPath><g clip-path="url(#r)"><rect width="63" height="20" fill="#555"/><rect x="63" width="53" height="20" fill="#dfb317"/><rect width="116" height="20" fill="url(#s)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="325" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="530">Coverage</text><text x="325" y="140" transform="scale(.1)" fill="#fff" textLength="530">Coverage</text><text aria-hidden="true" x="885" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="430">80.84%</text><text x="885" y="140" transform="scale(.1)" fill="#fff" textLength="430">80.84%</text></g></svg>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="116" height="20" role="img" aria-label="Coverage: 80.18%"><title>Coverage: 80.18%</title><linearGradient id="s" x2="0" y2="100%"><stop offset="0" stop-color="#bbb" stop-opacity=".1"/><stop offset="1" stop-opacity=".1"/></linearGradient><clipPath id="r"><rect width="116" height="20" rx="3" fill="#fff"/></clipPath><g clip-path="url(#r)"><rect width="63" height="20" fill="#555"/><rect x="63" width="53" height="20" fill="#dfb317"/><rect width="116" height="20" fill="url(#s)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="325" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="530">Coverage</text><text x="325" y="140" transform="scale(.1)" fill="#fff" textLength="530">Coverage</text><text aria-hidden="true" x="885" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="430">80.18%</text><text x="885" y="140" transform="scale(.1)" fill="#fff" textLength="430">80.18%</text></g></svg>

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

153810
dist/index.js generated vendored

File diff suppressed because one or more lines are too long

2
dist/index.js.map generated vendored

File diff suppressed because one or more lines are too long

2784
dist/licenses.txt generated vendored

File diff suppressed because it is too large Load Diff

9304
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -4,22 +4,21 @@
"description": "Deploy an actions artifact to GitHub Pages",
"main": "./dist/index.js",
"dependencies": {
"@actions/artifact": "^2.1.11",
"@actions/core": "^1.11.1",
"@actions/github": "^6.0.0",
"@octokit/request-error": "^5.0.1",
"@actions/core": "^1.10.0",
"@actions/github": "^5.1.1",
"@actions/http-client": "^2.1.0",
"@octokit/request-error": "^4.0.1",
"http-status-messages": "^1.1.0"
},
"devDependencies": {
"@vercel/ncc": "^0.38.2",
"eslint": "^8.57.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-github": "^4.10.2",
"jest": "^29.7.0",
"make-coverage-badge": "^1.2.0",
"nock": "^13.5.5",
"prettier": "^3.3.3",
"undici": "^6.20.1"
"@vercel/ncc": "^0.36.1",
"eslint": "^8.42.0",
"eslint-config-prettier": "^8.8.0",
"eslint-plugin-github": "^4.8.0",
"jest": "^29.5.0",
"nock": "^13.3.1",
"prettier": "^2.8.8",
"make-coverage-badge": "^1.2.0"
},
"scripts": {
"all": "npm run format && npm run lint && npm run prepare && npm run test && npm run coverage-badge",

View File

@@ -4,7 +4,9 @@ const path = require('path')
describe('with all environment variables set', () => {
beforeEach(() => {
process.env.ACTIONS_RUNTIME_URL = 'http://my-url'
process.env.GITHUB_RUN_ID = '123'
process.env.ACTIONS_RUNTIME_TOKEN = 'a-token'
process.env.GITHUB_REPOSITORY = 'actions/is-awesome'
process.env.GITHUB_TOKEN = 'gha-token'
process.env.GITHUB_SHA = '123abc'
@@ -24,7 +26,7 @@ describe('with all environment variables set', () => {
describe('with variables missing', () => {
it('execution fails if there are missing variables', done => {
delete process.env.GITHUB_RUN_ID
delete process.env.ACTIONS_RUNTIME_URL
const ip = path.join(__dirname, '../index.js')
cp.exec(`node ${ip}`, { env: process.env }, (err, stdout) => {
expect(stdout).toBe('')

File diff suppressed because it is too large Load Diff

View File

@@ -1,118 +1,119 @@
const core = require('@actions/core')
const github = require('@actions/github')
const { DefaultArtifactClient } = require('@actions/artifact')
const hc = require('@actions/http-client')
const { RequestError } = require('@octokit/request-error')
const HttpStatusMessages = require('http-status-messages')
function wrapTwirpResponseLikeOctokit(twirpResponse, requestOptions) {
// All variables we need from the runtime are loaded here
const getContext = require('./context')
async function processRuntimeResponse(res, requestOptions) {
// Parse the response body as JSON
let obj = null
try {
const contents = await res.readBody()
if (contents && contents.length > 0) {
obj = JSON.parse(contents)
}
} catch (error) {
// Invalid resource (contents not json); leaving resulting obj as null
}
// Specific response shape aligned with Octokit
const response = {
url: requestOptions.url,
status: 200,
url: res.message?.url || requestOptions.url,
status: res.message?.statusCode || 0,
headers: {
...requestOptions.headers
...res.message?.headers
},
data: twirpResponse
}
return response
data: obj
}
// Forcibly throw errors for negative HTTP status codes!
// @actions/http-client doesn't do this by default.
// Mimic the errors thrown by Octokit for consistency.
function wrapTwirpErrorLikeOctokit(twirpError, requestOptions) {
const rawErrorMsg = twirpError?.message || twirpError?.toString() || ''
const statusCodeMatch = rawErrorMsg.match(/Failed request: \((?<statusCode>\d+)\)/)
const statusCode = statusCodeMatch?.groups?.statusCode ?? 500
// Try to provide the best error message
if (response.status >= 400) {
// Try to get an error message from the response body
const errorMsg =
rawErrorMsg ||
(typeof response.data === 'string' && response.data) ||
response.data?.error ||
response.data?.message ||
// Try the Node HTTP IncomingMessage's statusMessage property
res.message?.statusMessage ||
// Fallback to the HTTP status message based on the status code
HttpStatusMessages[statusCode] ||
HttpStatusMessages[response.status] ||
// Or if the status code is unexpected...
`Unknown error (${statusCode})`
`Unknown error (${response.status})`
// RequestError is an Octokit-specific class
return new RequestError(errorMsg, statusCode, {
response: {
url: requestOptions.url,
status: statusCode,
headers: {
...requestOptions.headers
},
data: rawErrorMsg ? { message: rawErrorMsg } : ''
},
throw new RequestError(errorMsg, response.status, {
response,
request: requestOptions
})
}
function getArtifactsServiceOrigin() {
const resultsUrl = process.env.ACTIONS_RESULTS_URL
return resultsUrl ? new URL(resultsUrl).origin : ''
return response
}
async function getArtifactMetadata({ artifactName }) {
const artifactClient = new DefaultArtifactClient()
async function getSignedArtifactMetadata({ runtimeToken, workflowRunId, artifactName }) {
const { runTimeUrl: RUNTIME_URL } = getContext()
const artifactExchangeUrl = `${RUNTIME_URL}_apis/pipelines/workflows/${workflowRunId}/artifacts?api-version=6.0-preview`
// Primarily for debugging purposes, accuracy is not critical
const httpClient = new hc.HttpClient()
let data = null
try {
const requestHeaders = {
accept: 'application/json',
authorization: `Bearer ${runtimeToken}`
}
const requestOptions = {
method: 'POST',
url: `${getArtifactsServiceOrigin()}/twirp/github.actions.results.api.v1.ArtifactService/ListArtifacts`,
method: 'GET',
url: artifactExchangeUrl,
headers: {
'content-type': 'application/json'
...requestHeaders
},
body: {}
body: null
}
try {
core.info(`Fetching artifact metadata for "${artifactName}" in this workflow run`)
core.info(`Artifact exchange URL: ${artifactExchangeUrl}`)
const res = await httpClient.get(artifactExchangeUrl, requestHeaders)
let response
try {
const twirpResponse = await artifactClient.listArtifacts()
response = wrapTwirpResponseLikeOctokit(twirpResponse, requestOptions)
} catch (twirpError) {
core.error('Listing artifact metadata failed', twirpError)
const octokitError = wrapTwirpErrorLikeOctokit(twirpError, requestOptions)
throw octokitError
// May throw a RequestError (HttpError)
const response = await processRuntimeResponse(res, requestOptions)
data = response.data
core.debug(JSON.stringify(data))
} catch (error) {
core.error('Getting signed artifact URL failed', error)
throw error
}
const filteredArtifacts = response.data.artifacts.filter(artifact => artifact.name === artifactName)
const artifactCount = filteredArtifacts.length
core.debug(`List artifact count: ${artifactCount}`)
if (artifactCount === 0) {
const artifact = data?.value?.find(artifact => artifact.name === artifactName)
const artifactRawUrl = artifact?.url
if (!artifactRawUrl) {
throw new Error(
`No artifacts named "${artifactName}" were found for this workflow run. Ensure artifacts are uploaded with actions/upload-artifact@v4 or later.`
)
} else if (artifactCount > 1) {
throw new Error(
`Multiple artifacts named "${artifactName}" were unexpectedly found for this workflow run. Artifact count is ${artifactCount}.`
'No uploaded artifact was found! Please check if there are any errors at build step, or uploaded artifact name is correct.'
)
}
const artifact = filteredArtifacts[0]
core.debug(`Artifact: ${JSON.stringify(artifact)}`)
const signedArtifactUrl = `${artifactRawUrl}&%24expand=SignedContent`
if (!artifact.size) {
const artifactSize = artifact?.size
if (!artifactSize) {
core.warning('Artifact size was not found. Unable to verify if artifact size exceeds the allowed size.')
}
return artifact
} catch (error) {
core.error(
'Fetching artifact metadata failed. Is githubstatus.com reporting issues with API requests, Pages, or Actions? Please re-run the deployment at a later time.',
error
)
throw error
return {
url: signedArtifactUrl,
size: artifactSize
}
}
async function createPagesDeployment({ githubToken, artifactId, buildVersion, idToken, isPreview = false }) {
async function createPagesDeployment({ githubToken, artifactUrl, buildVersion, idToken, isPreview = false }) {
const octokit = github.getOctokit(githubToken)
const payload = {
artifact_id: artifactId,
artifact_url: artifactUrl,
pages_build_version: buildVersion,
oidc_token: idToken
}
@@ -172,7 +173,7 @@ async function cancelPagesDeployment({ githubToken, deploymentId }) {
}
module.exports = {
getArtifactMetadata,
getSignedArtifactMetadata,
createPagesDeployment,
getPagesDeploymentStatus,
cancelPagesDeployment

View File

@@ -3,7 +3,9 @@ const core = require('@actions/core')
// Load variables from Actions runtime
function getRequiredVars() {
return {
runTimeUrl: process.env.ACTIONS_RUNTIME_URL,
workflowRun: process.env.GITHUB_RUN_ID,
runTimeToken: process.env.ACTIONS_RUNTIME_TOKEN,
repositoryNwo: process.env.GITHUB_REPOSITORY,
buildVersion: process.env.GITHUB_SHA,
buildActor: process.env.GITHUB_ACTOR,

View File

@@ -3,7 +3,7 @@ const core = require('@actions/core')
// All variables we need from the runtime are loaded here
const getContext = require('./context')
const {
getArtifactMetadata,
getSignedArtifactMetadata,
createPagesDeployment,
getPagesDeploymentStatus,
cancelPagesDeployment
@@ -30,7 +30,9 @@ const SIZE_LIMIT_DESCRIPTION = '1 GB'
class Deployment {
constructor() {
const context = getContext()
this.runTimeUrl = context.runTimeUrl
this.repositoryNwo = context.repositoryNwo
this.runTimeToken = context.runTimeToken
this.buildVersion = context.buildVersion
this.buildActor = context.buildActor
this.actionsId = context.actionsId
@@ -43,26 +45,41 @@ class Deployment {
this.isPreview = context.isPreview === true
this.timeout = MAX_TIMEOUT
this.startTime = null
this.maxErrorCount = null
}
// Call GitHub api to fetch artifacts matching the provided name and deploy to GitHub Pages
// by creating a deployment with that artifact id
async create(idToken) {
if (Number(core.getInput('timeout')) > MAX_TIMEOUT) {
setOptionalUserInput() {
const timeoutInput = Number(core.getInput('timeout'))
if (timeoutInput > MAX_TIMEOUT) {
core.warning(
`Warning: timeout value is greater than the allowed maximum - timeout set to the maximum of ${MAX_TIMEOUT} milliseconds.`
)
}
const timeoutInput = Number(core.getInput('timeout'))
this.timeout = !timeoutInput || timeoutInput <= 0 ? MAX_TIMEOUT : Math.min(timeoutInput, MAX_TIMEOUT)
const maxErrorCountInput = Number(core.getInput('error_count'))
if (!maxErrorCountInput || maxErrorCountInput <= 0) {
core.warning('Invalid error_count value will be ignored. Please ensure the value is a positive integer.')
} else {
this.maxErrorCount = maxErrorCountInput
}
}
// Ask the runtime for the unsigned artifact URL and deploy to GitHub Pages
// by creating a deployment with that artifact
async create(idToken) {
try {
this.setOptionalUserInput()
core.debug(`Actor: ${this.buildActor}`)
core.debug(`Action ID: ${this.actionsId}`)
core.debug(`Actions Workflow Run ID: ${this.workflowRun}`)
const artifactData = await getArtifactMetadata({ artifactName: this.artifactName })
const artifactData = await getSignedArtifactMetadata({
runtimeToken: this.runTimeToken,
workflowRunId: this.workflowRun,
artifactName: this.artifactName
})
if (artifactData?.size > ONE_GIGABYTE) {
core.warning(
@@ -72,7 +89,7 @@ class Deployment {
const deployment = await createPagesDeployment({
githubToken: this.githubToken,
artifactId: artifactData.id,
artifactUrl: artifactData.url,
buildVersion: this.buildVersion,
idToken,
isPreview: this.isPreview
@@ -95,12 +112,12 @@ class Deployment {
} catch (error) {
core.error(error.stack)
// output raw error in debug mode.
core.debug(JSON.stringify(error))
// build customized error message based on server response
if (error.response) {
let errorMessage = `Failed to create deployment (status: ${error.status}) with build version ${this.buildVersion}. `
if (error.response.headers['x-github-request-id']) {
errorMessage += ` Request ID ${error.response.headers['x-github-request-id']}`
}
if (error.status === 400) {
errorMessage += `Responded with: ${error.message}`
} else if (error.status === 403) {
@@ -139,7 +156,6 @@ class Deployment {
const deploymentId = this.deploymentInfo.id || this.buildVersion
const reportingInterval = Number(core.getInput('reporting_interval'))
const maxErrorCount = Number(core.getInput('error_count'))
let errorCount = 0
@@ -182,6 +198,9 @@ class Deployment {
} catch (error) {
core.error(error.stack)
// output raw error in debug mode.
core.debug(JSON.stringify(error))
// build customized error message based on server response
if (error.response) {
errorStatus = error.status || error.response.status
@@ -195,7 +214,7 @@ class Deployment {
}
}
if (errorCount >= maxErrorCount) {
if (errorCount >= this.maxErrorCount) {
core.error('Too many errors, aborting!')
core.setFailed('Failed with status code: ' + errorStatus)