Skip to content

Commit

Permalink
fix(update-assets): run on push instead of pr (#9276)
Browse files Browse the repository at this point in the history
* fix(update-assets): run on push instead of pr

* chore: remove unused log
  • Loading branch information
Bas950 authored Feb 18, 2025
1 parent 1d6f0d4 commit b425995
Show file tree
Hide file tree
Showing 5 changed files with 45 additions and 89 deletions.
12 changes: 6 additions & 6 deletions .github/workflows/assets-updater.yml
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
name: pmd

on:
pull_request:
types: [opened, reopened, synchronize]
pull_request_review:
types: [submitted]
push:
branches:
- main
paths:
- '**.ts'
- '**.json'

jobs:
check-and-run:
if: github.repository_owner == 'PreMiD'
name: Update assets
runs-on: ubuntu-latest
permissions:
pull-requests: write
contents: write
statuses: write

Expand All @@ -35,7 +36,6 @@ jobs:
env:
CDN_TOKEN: ${{ secrets.CDN_TOKEN }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
HEAD_REF: ${{ github.event.pull_request.head.ref }}
run: |
# Configure git
git config --local user.email "github-actions[bot]@users.noreply.github.com"
Expand Down
11 changes: 9 additions & 2 deletions cli/src/classes/AssetsManager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -745,7 +745,7 @@ describe('assetsManager', () => {
return Promise.resolve(`const img = "https://example.com/new-asset.png"`)
}
if (filePath.endsWith('metadata.json')) {
return Promise.resolve(`{"image": "https://example.com/new-asset.png"}`)
return Promise.resolve(`{"image": "https://example.com/new-asset.png", "version": "1.0.0"}`)
}
return Promise.resolve('')
})
Expand All @@ -769,7 +769,14 @@ describe('assetsManager', () => {
)
expect(mocks.writeFile).toHaveBeenCalledWith(
expect.stringMatching(/metadata\.json$/),
`{"image": "${assetsManager.baseUrl}/0.png"}`,
`{"image": "${assetsManager.baseUrl}/0.png", "version": "1.0.0"}`,
'utf-8',
)

//* With old image as we didn't actually write it due to the mocking
expect(mocks.writeFile).toHaveBeenCalledWith(
expect.stringMatching(/metadata\.json$/),
`{\n "image": "https://example.com/new-asset.png",\n "version": "1.0.1"\n}`,
'utf-8',
)
})
Expand Down
18 changes: 16 additions & 2 deletions cli/src/classes/AssetsManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import * as core from '@actions/core'
import FormData from 'form-data'
import { globby } from 'globby'
import got from 'got'
import { inc } from 'semver'
import sharp from 'sharp'
import { getFolderLetter } from '../util/getFolderLetter.js'
import { getJsonPosition } from '../util/getJsonPosition.js'
Expand Down Expand Up @@ -439,17 +440,25 @@ export class AssetsManager {
await this.deleteAssets(toBeDeleted)
}

let replacedAny = false
if (toBeMoved.size) {
await this.uploadAssets(toBeMoved)
await this.deleteAssets([...toBeMoved.keys()])

await this.replaceInFiles(toBeMoved)
replacedAny = await this.replaceInFiles(toBeMoved)
}

if (toBeUploaded.size) {
await this.uploadAssets(toBeUploaded)

await this.replaceInFiles(toBeUploaded)
replacedAny ||= await this.replaceInFiles(toBeUploaded)
}

if (replacedAny) {
const metadata: ActivityMetadata = JSON.parse(await readFile(resolve(this.cwd, 'metadata.json'), 'utf-8'))

metadata.version = inc(metadata.version, 'patch') ?? metadata.version
await writeFile(resolve(this.cwd, 'metadata.json'), JSON.stringify(metadata, null, 2), 'utf-8')
}

//* Return the number of assets updated
Expand Down Expand Up @@ -504,6 +513,7 @@ export class AssetsManager {
Array.from(assets).map(([url, { url: newUrl }]) => [url, newUrl]),
)

let changedAny = false
for (const file of await globby('**/*.ts', { cwd: this.cwd, absolute: true })) {
let content = await readFile(file, 'utf-8')
let changed = false
Expand All @@ -512,6 +522,7 @@ export class AssetsManager {
continue
content = content.replaceAll(oldUrl, newUrl)
changed = true
changedAny = true
}

if (changed)
Expand All @@ -525,10 +536,13 @@ export class AssetsManager {
continue
metadata = metadata.replaceAll(oldUrl, newUrl)
changed = true
changedAny = true
}

if (changed)
await writeFile(resolve(this.cwd, 'metadata.json'), metadata, 'utf-8')

return changedAny
}

async deleteCdnAssets(): Promise<number> {
Expand Down
88 changes: 13 additions & 75 deletions cli/src/commands/updateAssets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,12 @@ function hasGitChanges(): boolean {
return output.length > 0
}

//* Command to update assets and manage GitHub status checks in PRs
//* Command to update assets and manage GitHub status checks for push events
export async function updateAssets() {
if (!isCI) {
return exit(MESSAGES.ciOnly)
}

const pullRequest = github.context.payload.pull_request
if (!pullRequest) {
return exit(MESSAGES.noPullRequest)
}

//* Only run for PreMiD/Presences repository
if (github.context.repo.owner !== 'PreMiD' || github.context.repo.repo !== 'Presences') {
return success(MESSAGES.wrongRepository)
Expand All @@ -40,13 +35,9 @@ export async function updateAssets() {
return exit(MESSAGES.noCdnToken)
}

const headRef = process.env.HEAD_REF
if (!headRef) {
return exit(MESSAGES.noHeadRef)
}

const octokit = github.getOctokit(token)
const context = github.context
const sha = context.sha

const { changed, deleted } = await getChangedActivities()

Expand All @@ -56,7 +47,7 @@ export async function updateAssets() {
if (changed.length === 0 && deleted.length === 0) {
await octokit.rest.repos.createCommitStatus({
...context.repo,
sha: pullRequest.head.sha,
sha,
state: 'success',
description: MESSAGES.noActivities,
context: NAME,
Expand All @@ -65,66 +56,13 @@ export async function updateAssets() {
return success(MESSAGES.noActivities)
}

//* Fetch all pages of reviews
const reviews = await octokit.paginate(octokit.rest.pulls.listReviews, {
...context.repo,
pull_number: pullRequest.number,
})

core.info(`Found ${reviews.length} reviews for PR #${pullRequest.number}`)

//* Count only approved reviews from reviewers with write access (excluding PR author)
const uniqueApprovers = new Set(
reviews
.filter(review =>
review.state === 'APPROVED'
&& review.user?.login !== pullRequest.user.login,
)
.map(review => review.user?.login)
.filter((login): login is string => login !== undefined),
)

core.debug(`Found ${uniqueApprovers.size} unique approvers`)

let approvalCount = 0
for (const reviewer of uniqueApprovers) {
try {
const { data: permission } = await octokit.rest.repos.getCollaboratorPermissionLevel({
...context.repo,
username: reviewer,
})

if (['admin', 'write'].includes(permission.permission)) {
approvalCount++
}
}
catch {
//* Skip if we can't get permissions (user no longer has access, etc.)
continue
}
}

core.info(`Approval count: ${approvalCount}`)

if (approvalCount < 2) {
await octokit.rest.repos.createCommitStatus({
...context.repo,
sha: pullRequest.head.sha,
state: 'pending',
description: MESSAGES.waitingForApprovals,
context: NAME,
})

return success(MESSAGES.waitingForApprovals)
}

core.info('Approvals found, checking and updating assets...')
core.info('Checking and updating assets...')

try {
//* Create pending status while we process
await octokit.rest.repos.createCommitStatus({
...context.repo,
sha: pullRequest.head.sha,
sha,
state: 'pending',
description: MESSAGES.checkingAndUpdatingAssets,
context: NAME,
Expand All @@ -147,7 +85,7 @@ export async function updateAssets() {
if (!valid) {
await octokit.rest.repos.createCommitStatus({
...context.repo,
sha: pullRequest.head.sha,
sha,
state: 'failure',
description: MESSAGES.someInvalidAssets,
context: NAME,
Expand Down Expand Up @@ -187,7 +125,7 @@ export async function updateAssets() {
core.info('No changes to commit')
await octokit.rest.repos.createCommitStatus({
...context.repo,
sha: pullRequest.head.sha,
sha,
state: 'success',
description: MESSAGES.assetsUpdatedCount(count),
context: NAME,
Expand All @@ -209,7 +147,7 @@ export async function updateAssets() {
core.info('No changes to commit')
await octokit.rest.repos.createCommitStatus({
...context.repo,
sha: pullRequest.head.sha,
sha,
state: 'success',
description: MESSAGES.assetsUpdatedCount(count),
context: NAME,
Expand All @@ -221,21 +159,21 @@ export async function updateAssets() {
core.info('Committing and pushing changes')
execSync('git add .')
execSync('git commit -m "chore: update assets"')
execSync(`git push origin HEAD:"${headRef}"`)
execSync('git push')

await octokit.rest.repos.createCommitStatus({
...context.repo,
sha: pullRequest.head.sha,
state: 'pending',
description: MESSAGES.assetsUpdatedCount(count, true),
sha,
state: 'success',
description: MESSAGES.assetsUpdatedCount(count),
context: NAME,
})
}
catch (error) {
//* Update status to failure if something goes wrong
await octokit.rest.repos.createCommitStatus({
...context.repo,
sha: pullRequest.head.sha,
sha,
state: 'failure',
description: error instanceof Error ? error.message : MESSAGES.error,
context: NAME,
Expand Down
5 changes: 1 addition & 4 deletions cli/src/util/log.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,18 +23,15 @@ export function info(message: string) {

export const MESSAGES = {
ciOnly: 'This command can only be run in a CI environment',
noPullRequest: 'This command can only be run in a pull request',
noToken: 'GITHUB_TOKEN environment variable is required',
noCdnToken: 'CDN_TOKEN environment variable is required',
noMongoUrl: 'MONGO_URL environment variable is required',
noHeadRef: 'HEAD_REF environment variable is required',
noMongoConnection: 'Failed to connect to MongoDB',
noActivities: 'No activities changed',
waitingForApprovals: 'Waiting for 2 approvals...',
checkingAndUpdatingAssets: 'Checking and updating assets...',
someInvalidAssets: 'Some invalid assets were found, check the logs for more details',
assetsUpdated: 'Assets have been updated successfully',
error: 'An error occurred',
wrongRepository: 'This command can only be run in PreMiD/Presences repository',
assetsUpdatedCount: (count: number, committing = false) => count === 0 ? 'No assets updated' : `${count} assets updated successfully${committing ? ' and pushed to GitHub' : ''}`,
assetsUpdatedCount: (count: number) => count === 0 ? 'No assets updated' : `${count} assets updated successfully`,
}

0 comments on commit b425995

Please sign in to comment.