Skip to content

Commit

Permalink
feat: no comment when diff is empty (#12)
Browse files Browse the repository at this point in the history
  • Loading branch information
luist18 authored Nov 28, 2024
1 parent a6f7ced commit 3dac8da
Show file tree
Hide file tree
Showing 5 changed files with 125 additions and 42 deletions.
87 changes: 63 additions & 24 deletions __tests__/diff.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,7 @@ describe('summary function', () => {
jest.useRealTimers()
})

it('returns summary with "No schema changes detected" when sql is empty', () => {
it('returns empty summary if there are no schema changes', () => {
const sql = ''
const hash = 'abcd1234'

Expand All @@ -320,27 +320,7 @@ describe('summary function', () => {
projectId
)

expect(result).toContain(DIFF_COMMENT_IDENTIFIER)
expect(result).toContain(DIFF_HASH_COMMENT_TEMPLATE.replace('%s', hash))
expect(result).toContain('No schema changes detected')
expect(result).toContain(
`Schema diff between the compare branch ([${compareBranch.name}]`
)
expect(result).toContain(
`- Base branch: ${baseBranch.name} ([${baseBranch.id}](${getBranchURL(
projectId,
baseBranch.id
)}))`
)
expect(result).toContain(
`- Compare branch: ${compareBranch.name} ([${compareBranch.id}](${getBranchURL(
projectId,
compareBranch.id
)})) 🔒`
)
expect(result).toContain(
`This comment was last updated at 1/1/2023 12:00:00 PM`
)
expect(result).toBe('')
})

it('returns formatted diff when sql is not empty', () => {
Expand Down Expand Up @@ -385,7 +365,7 @@ describe('summary function', () => {
it('handles unprotected compare and base branches correctly', () => {
const unprotectedCompareBranch = { ...compareBranch, protected: false }
const unprotectedBaseBranch = { ...baseBranch, protected: false }
const sql = ''
const sql = 'sql content'
const hash = 'abcd1234'

const result = summary(
Expand Down Expand Up @@ -434,7 +414,8 @@ describe('upsertGitHubComment function', () => {
issues: {
listComments: jest.fn(),
updateComment: jest.fn(),
createComment: jest.fn()
createComment: jest.fn(),
deleteComment: jest.fn()
}
}
} as unknown as jest.Mocked<ReturnType<typeof github.getOctokit>>
Expand Down Expand Up @@ -553,4 +534,62 @@ describe('upsertGitHubComment function', () => {
'Failed to create a comment'
)
})

it('deletes the comment if the diff is empty and the comment exists', async () => {
const existingComment = {
id: 123,
body: `${DIFF_COMMENT_IDENTIFIER}\n${DIFF_HASH_COMMENT_TEMPLATE.replace('%s', hash)}\nExisting diff content`,
html_url: 'http://example.com/existing-comment'
}
;(
mockOctokit.rest.issues.listComments as unknown as jest.Mock
).mockResolvedValueOnce({ data: [existingComment] })
;(
mockOctokit.rest.issues.deleteComment as unknown as jest.Mock
).mockResolvedValueOnce({ status: 204 })

const result: SummaryComment = await upsertGitHubComment(token, '', hash)

expect(mockOctokit.rest.issues.deleteComment).toHaveBeenCalledWith({
...mockContext.repo,
comment_id: existingComment.id
})
expect(result).toEqual({
operation: 'deleted',
url: undefined
})
})

it('throw an error if deleting the comment fails', async () => {
const existingComment = {
id: 123,
body: `${DIFF_COMMENT_IDENTIFIER}\n${DIFF_HASH_COMMENT_TEMPLATE.replace('%s', hash)}\nExisting diff content`,
html_url: 'http://example.com/existing-comment'
}
;(
mockOctokit.rest.issues.listComments as unknown as jest.Mock
).mockResolvedValueOnce({ data: [existingComment] })
;(
mockOctokit.rest.issues.deleteComment as unknown as jest.Mock
).mockResolvedValueOnce({ status: 500 })

await expect(upsertGitHubComment(token, '', hash)).rejects.toThrow(
`Failed to delete comment`
)
})

it('skips comment creation if diff is empty and no comment exists', async () => {
// eslint-disable-next-line no-extra-semi
;(
mockOctokit.rest.issues.listComments as unknown as jest.Mock
).mockResolvedValueOnce({ data: [] })

const result: SummaryComment = await upsertGitHubComment(token, '', hash)

expect(mockOctokit.rest.issues.createComment).not.toHaveBeenCalled()
expect(result).toEqual({
operation: 'noop',
url: undefined
})
})
})
35 changes: 27 additions & 8 deletions dist/index.js

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

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

Large diffs are not rendered by default.

37 changes: 30 additions & 7 deletions src/diff.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ export type BranchDiff = {
}

export type SummaryComment = {
url: string
operation: 'created' | 'updated' | 'noop'
url?: string
operation: 'created' | 'updated' | 'noop' | 'deleted'
}

export async function diff(
Expand Down Expand Up @@ -160,13 +160,12 @@ export function summary(
role: string,
projectId: string
): string {
let diffContent
if (sql === '') {
diffContent = 'No schema changes detected'
} else {
diffContent = `\`\`\`diff\n${sql}\n\`\`\``
if (sql.trim() === '') {
return ''
}

const diffContent = `\`\`\`diff\n${sql}\n\`\`\``

const compareBranchURL = getBranchURL(projectId, compareBranch.id)
const baseBranchURL = getBranchURL(projectId, baseBranch.id)

Expand Down Expand Up @@ -208,8 +207,25 @@ export async function upsertGitHubComment(
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 (
Expand Down Expand Up @@ -238,6 +254,13 @@ export async function upsertGitHubComment(
}
}

// 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,
Expand Down
6 changes: 4 additions & 2 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,9 +98,11 @@ export async function run(): Promise<void> {
core.info(`Comment ${operation} successfully`)
}

core.setOutput('comment_url', url)
if (url) {
core.setOutput('comment_url', url)

core.info(`Comment URL: ${url}`)
core.info(`Comment URL: ${url}`)
}
} catch (error) {
// Fail the workflow run if an error occurs
if (error instanceof Error) core.setFailed(error.message)
Expand Down

0 comments on commit 3dac8da

Please sign in to comment.