-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathmain.ts
243 lines (226 loc) Β· 8.39 KB
/
main.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
import * as core from '@actions/core'
import {context, getOctokit} from '@actions/github'
import type {GitHub} from '@actions/github/lib/utils'
import {ReposCreateDeploymentResponseData} from '@octokit/types/dist-types/generated/Endpoints'
import {OctokitResponse} from '@octokit/types/dist-types/OctokitResponse'
import NetlifyAPI from 'netlify'
import * as path from 'path'
import {defaultInputs, Inputs} from './inputs'
import * as crypto from 'crypto'
function getCommentIdentifier(siteId: string): string {
const sha256SiteId: string = crypto
.createHash('sha256')
.update(siteId)
.digest('hex')
return `<!-- NETLIFY DEPLOY COMMENT GENERATED BY ACTIONS_NETLIFY - APP ID SHA256: ${sha256SiteId} -->`
}
async function findIssueComment(
githubClient: InstanceType<typeof GitHub>,
siteId: string
): Promise<number | undefined> {
const listCommentsRes = await githubClient.issues.listComments({
owner: context.issue.owner,
repo: context.issue.repo,
// eslint-disable-next-line @typescript-eslint/camelcase
issue_number: context.issue.number
})
const comments = listCommentsRes.data
const commentIdentifier = getCommentIdentifier(siteId)
for (const comment of comments) {
// If comment contains the comment identifier
if (comment.body.includes(commentIdentifier)) {
return comment.id
}
}
return undefined
}
async function createGitHubDeployment(
githubClient: InstanceType<typeof GitHub>,
environmentUrl: string,
environment: string,
description: string | undefined
): Promise<void> {
const deployRef = context.payload.pull_request?.head.sha ?? context.sha
const deployment = await githubClient.repos.createDeployment({
// eslint-disable-next-line @typescript-eslint/camelcase
auto_merge: false,
owner: context.repo.owner,
repo: context.repo.repo,
ref: deployRef,
environment,
description,
// eslint-disable-next-line @typescript-eslint/camelcase
required_contexts: []
})
await githubClient.repos.createDeploymentStatus({
state: 'success',
// eslint-disable-next-line @typescript-eslint/camelcase
environment_url: environmentUrl,
owner: context.repo.owner,
repo: context.repo.repo,
// eslint-disable-next-line @typescript-eslint/camelcase
deployment_id: (
deployment as OctokitResponse<ReposCreateDeploymentResponseData>
).data.id
})
}
export async function run(inputs: Inputs): Promise<void> {
try {
const netlifyAuthToken = process.env.NETLIFY_AUTH_TOKEN
const siteId = process.env.NETLIFY_SITE_ID
// NOTE: Non-collaborators PRs don't pass GitHub secrets to GitHub Actions.
if (!(netlifyAuthToken && siteId)) {
const errorMessage = 'Netlify credentials not provided, not deployable'
if (inputs.failsWithoutCredentials()) {
throw new Error(errorMessage)
}
process.stderr.write(errorMessage)
return
}
const dir = inputs.publishDir()
const functionsDir: string | undefined = inputs.functionsDir()
const deployMessage: string | undefined = inputs.deployMessage()
const productionBranch: string | undefined = inputs.productionBranch()
const enablePullRequestComment: boolean = inputs.enablePullRequestComment()
const enableCommitComment: boolean = inputs.enableCommitComment()
const overwritesPullRequestComment: boolean =
inputs.overwritesPullRequestComment()
const netlifyConfigPath: string | undefined = inputs.netlifyConfigPath()
const alias: string | undefined = inputs.alias()
const branchMatchesProduction: boolean =
!!productionBranch && context.ref === `refs/heads/${productionBranch}`
const productionDeploy: boolean =
branchMatchesProduction || inputs.productionDeploy()
// Create Netlify API client
const netlifyClient = new NetlifyAPI(netlifyAuthToken)
// Resolve publish directory
const deployFolder = path.resolve(process.cwd(), dir)
// Resolve functions directory
const functionsFolder =
functionsDir && path.resolve(process.cwd(), functionsDir)
// Deploy to Netlify
const deploy = await netlifyClient.deploy(siteId, deployFolder, {
draft: !productionDeploy,
message: deployMessage,
configPath: netlifyConfigPath,
...(productionDeploy ? {} : {branch: alias}),
fnDir: functionsFolder
})
if (productionDeploy && alias !== undefined) {
// eslint-disable-next-line no-console
console.warn(
`Only production deployment was conducted. The alias ${alias} was ignored.`
)
}
// Create a message
const message = productionDeploy
? `π Published on ${deploy.deploy.ssl_url} as production\nπ Deployed on ${deploy.deploy.deploy_ssl_url}`
: `π Deployed on ${deploy.deploy.deploy_ssl_url}`
// Print the URL
process.stdout.write(`${message}\n`)
// Set the deploy URL to outputs for GitHub Actions
const deployUrl = productionDeploy
? deploy.deploy.ssl_url
: deploy.deploy.deploy_ssl_url
core.setOutput('deploy-url', deployUrl)
// Get GitHub token
const githubToken = inputs.githubToken()
if (githubToken === '') {
return
}
const markdownComment = `${getCommentIdentifier(siteId)}\n${message}`
// Create GitHub client
const githubClient = getOctokit(githubToken)
if (enableCommitComment) {
const commitCommentParams = {
owner: context.repo.owner,
repo: context.repo.repo,
// eslint-disable-next-line @typescript-eslint/camelcase
commit_sha: context.sha,
body: markdownComment
}
// TODO: Remove try
// NOTE: try-catch is experimentally used because commit message may not be done in some conditions.
try {
// Comment to the commit
await githubClient.repos.createCommitComment(commitCommentParams)
} catch (err) {
// eslint-disable-next-line no-console
console.error(err, JSON.stringify(commitCommentParams, null, 2))
}
}
// If it is a pull request and enable comment on pull request
if (context.issue.number !== undefined) {
if (enablePullRequestComment) {
let commentId: number | undefined = undefined
if (overwritesPullRequestComment) {
// Find issue comment
commentId = await findIssueComment(githubClient, siteId)
}
// NOTE: if not overwrite, commentId is always undefined
if (commentId !== undefined) {
// Update comment of the deploy URL
await githubClient.issues.updateComment({
owner: context.issue.owner,
repo: context.issue.repo,
// eslint-disable-next-line @typescript-eslint/camelcase
comment_id: commentId,
body: markdownComment
})
} else {
// Comment the deploy URL
await githubClient.issues.createComment({
// eslint-disable-next-line @typescript-eslint/camelcase
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: markdownComment
})
}
}
}
try {
const environment =
inputs.githubDeploymentEnvironment() ??
(productionDeploy
? 'production'
: context.issue.number !== undefined
? 'pull request'
: 'commit')
const description = inputs.githubDeploymentDescription()
// Create GitHub Deployment
await createGitHubDeployment(
githubClient,
deployUrl,
environment,
description
)
} catch (err) {
// eslint-disable-next-line no-console
console.error(err)
}
if (inputs.enableCommitStatus()) {
try {
// When "pull_request", context.payload.pull_request?.head.sha is expected SHA.
// (base: https://github.community/t/github-sha-isnt-the-value-expected/17903/2)
const sha = context.payload.pull_request?.head.sha ?? context.sha
await githubClient.repos.createCommitStatus({
owner: context.repo.owner,
repo: context.repo.repo,
context: 'Netlify',
description: 'Netlify deployment',
state: 'success',
sha,
// eslint-disable-next-line @typescript-eslint/camelcase
target_url: deployUrl
})
} catch (err) {
// eslint-disable-next-line no-console
console.error(err)
}
}
} catch (error) {
core.setFailed(error.message)
}
}
run(defaultInputs)