-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdiff.ts
More file actions
279 lines (238 loc) · 7.34 KB
/
Copy pathdiff.ts
File metadata and controls
279 lines (238 loc) · 7.34 KB
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
import * as github from '@actions/github'
import { type Branch, createApiClient } from '@neondatabase/api-client'
import { createPatch } from 'diff'
import { BranchComparisonInput, getBranchURL, PointInTime } from './utils.js'
import { version } from './version.js'
const DIFF_COMMENT_IDENTIFIER =
'<!--- [schema diff GitHub action comment identifier] -->'
const DIFF_HASH_COMMENT_TEMPLATE = '<!--- [diff digest: %s] -->'
export type BranchDiff = {
sql: string
hash: string
compareBranch: Branch
baseBranch: Branch
database: string
}
export type SummaryComment = {
url?: string
operation: 'created' | 'updated' | 'noop' | 'deleted'
}
export async function diff(
projectId: string,
compareBranchInput: BranchComparisonInput,
apiKey: string,
apiHost: string,
database: string,
pointInTime?: PointInTime
): Promise<BranchDiff> {
const client = createApiClient({
apiKey,
baseURL: apiHost,
timeout: 60000,
headers: {
// action version from the package.json
'User-Agent': `neon-schema-diff-action v${version}`
}
})
// Get all branches for the project
const branches = await client.listProjectBranches({
projectId
})
if (branches.status !== 200) {
throw new Error(`Failed to list branches for project ${projectId}`)
}
const { compare: compareInput, base: baseInput } = compareBranchInput
// Find a branch by id or name
const compareBranch = branches.data?.branches.find(
(branch) =>
branch.id === compareInput.value || branch.name === compareInput.value
)
if (!compareBranch) {
throw new Error(
`Branch ${compareInput.value} not found in project ${projectId}`
)
}
// Get the parent branch either from the base branch or from the
// parent of the child branch
let baseBranch: Branch | undefined
if (baseInput) {
baseBranch = branches.data?.branches.find(
(branch) =>
branch.id === baseInput.value || branch.name === baseInput.value
)
if (!baseBranch) {
throw new Error(
`Branch ${baseInput.value} not found in project ${projectId}`
)
}
} else {
if (!compareBranch.parent_id) {
throw new Error(
`Branch ${compareInput.value} has no parent to compare to, please provide a base branch`
)
}
baseBranch = branches.data?.branches.find(
(branch) => branch.id === compareBranch.parent_id
)
if (!baseBranch) {
throw new Error(`Parent branch for ${compareInput.value} not found`)
}
}
const compareSchema = await client.getProjectBranchSchema({
projectId,
branchId: compareBranch.id,
db_name: database,
lsn: pointInTime?.type === 'lsn' ? pointInTime.value : undefined,
timestamp: pointInTime?.type === 'timestamp' ? pointInTime.value : undefined
})
if (compareSchema.status !== 200) {
throw new Error(
`Failed to get schema for branch ${compareInput.value} in project ${projectId}`
)
}
const baseSchema = await client.getProjectBranchSchema({
projectId,
branchId: baseBranch.id,
db_name: database
})
if (baseSchema.status !== 200) {
throw new Error(
`Failed to get schema for the base branch ${baseInput?.value || baseBranch.name} in project ${projectId}`
)
}
if (compareSchema.data?.sql === baseSchema.data?.sql) {
return {
sql: '',
hash: '',
compareBranch,
baseBranch,
database: database
}
}
const diff = createPatch(
`${database}-schema.sql`,
baseSchema.data?.sql || '',
compareSchema.data?.sql || '',
`Branch ${baseBranch.name}`,
`Branch ${compareBranch.name}`
)
const hashBuffer = await crypto.subtle.digest(
'SHA-256',
new TextEncoder().encode(diff)
)
const hash = Array.from(new Uint8Array(hashBuffer))
.map((b) => b.toString(16).padStart(2, '0'))
.join('')
return {
sql: diff,
hash: hash,
compareBranch,
baseBranch,
database: database
}
}
export function summary(
sql: string,
hash: string,
compareBranch: Branch,
baseBranch: Branch,
database: string,
projectId: string
): string {
if (sql.trim() === '') {
return ''
}
const diffContent = `\`\`\`diff\n${sql}\n\`\`\``
const compareBranchURL = getBranchURL(projectId, compareBranch.id)
const baseBranchURL = getBranchURL(projectId, baseBranch.id)
return `
${DIFF_COMMENT_IDENTIFIER}
${DIFF_HASH_COMMENT_TEMPLATE.replace('%s', hash)}
# <picture><source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/neondatabase/schema-diff-action/refs/heads/main/docs/logos/logo-dark.svg"><img alt="Neon logo" src="https://raw.githubusercontent.com/neondatabase/schema-diff-action/refs/heads/main/docs/logos/logo-light.svg" width="24" height="24"></picture> Neon Schema Diff summary
Schema diff between the compare branch ([${compareBranch.name}](${compareBranchURL})) and the base branch ([${baseBranch.name}](${baseBranchURL})).
- Base branch: ${baseBranch.name} ([${baseBranch.id}](${baseBranchURL})) ${baseBranch.protected ? '🔒' : ''}
- Compare branch: ${compareBranch.name} ([${compareBranch.id}](${compareBranchURL})) ${compareBranch.protected ? '🔒' : ''}
- Database: ${database}
<details><summary>Diff</summary>
<p>
${diffContent}
</p>
</details>
This comment was last updated at ${new Date().toUTCString()}
`
}
export async function upsertGitHubComment(
token: string,
diff: string,
hash: string
): Promise<SummaryComment> {
const { context } = github
const oktokit = github.getOctokit(token)
// Search the current pr for the comment
const comments = await oktokit.rest.issues.listComments({
...context.repo,
issue_number: context.issue.number
})
const comment = comments.data.find((comment) =>
comment.body?.includes(DIFF_COMMENT_IDENTIFIER)
)
const emptyDiff = diff.trim() === ''
// If we can find the comment we update it, otherwise we create a new comment
if (comment) {
if (emptyDiff) {
// If the diff is empty, we delete the comment.
const deletedComment = await oktokit.rest.issues.deleteComment({
...context.repo,
comment_id: comment.id
})
if (deletedComment.status !== 204) {
throw new Error('Failed to delete comment')
}
return {
operation: 'deleted'
}
}
// Before updating the comment, check if the hash is the same, if it is,
// we don't need to update the comment as the diff hasn't changed
if (
comment.body &&
comment.body.includes(DIFF_HASH_COMMENT_TEMPLATE.replace('%s', hash))
) {
return {
url: comment.html_url,
operation: 'noop'
}
}
const updatedComment = await oktokit.rest.issues.updateComment({
...context.repo,
comment_id: comment.id,
body: diff
})
if (updatedComment.status !== 200) {
throw new Error(`Failed to update comment ${comment.id}`)
}
return {
url: updatedComment.data.html_url,
operation: 'updated'
}
}
// If the diff is empty, we don't need to create a comment
if (emptyDiff) {
return {
operation: 'noop'
}
}
// Create a new comment
const createdComment = await oktokit.rest.issues.createComment({
...context.repo,
issue_number: context.issue.number,
body: diff
})
if (createdComment.status !== 201) {
throw new Error('Failed to create a comment')
}
return {
url: createdComment.data.html_url,
operation: 'created'
}
}