Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion actions/cnb-delete-branch/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,9 @@ describe('删除 CNB 分支', () => {

it('分页拉取 Pull Request 列表', async () => {
const firstPage = Array.from({ length: 100 }, (_, index) => createPullRequest(String(index + 1)))
const secondPage = [createPullRequest('101')]
const secondPage = [
createPullRequest('101'),
]
mockFetchOnce(200, JSON.stringify(firstPage))
mockFetchOnce(200, JSON.stringify(secondPage))

Expand Down
8 changes: 6 additions & 2 deletions actions/cnb-delete-branch/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,13 +172,17 @@ export async function main(): Promise<void> {
core.info(`Branch "${branch}" does not exist; skip delete`)
}
catch (error) {
const message = error instanceof Error ? error.message : String(error)
const message = error instanceof Error
? error.message
: String(error)
core.setFailed(message)
}
}

if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
main().catch((error) => {
core.setFailed(`cnb-delete-branch failed: ${error instanceof Error ? error.message : String(error)}`)
core.setFailed(`cnb-delete-branch failed: ${error instanceof Error
? error.message
: String(error)}`)
})
}
4 changes: 3 additions & 1 deletion actions/issues-helper/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,7 @@ import * as core from '@actions/core'
import { main } from './main'

main().catch((error) => {
core.setFailed(`issues-helper failed: ${error instanceof Error ? error.message : String(error)}`)
core.setFailed(`issues-helper failed: ${error instanceof Error
? error.message
: String(error)}`)
})
47 changes: 37 additions & 10 deletions actions/issues-helper/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,16 @@ type IssueState = 'closed' | 'open'
type CloseReason = 'completed' | 'not_planned'

const actionNames = new Set<ActionName>(['create-comment', 'update-issue', 'mark-duplicate'])
const reactionContents = new Set<ReactionContent>(['+1', '-1', 'laugh', 'confused', 'heart', 'hooray', 'rocket', 'eyes'])
const reactionContents = new Set<ReactionContent>([
'+1',
'-1',
'laugh',
'confused',
'heart',
'hooray',
'rocket',
'eyes',
])
const permissionRanks: Record<string, number> = {
none: 0,
read: 1,
Expand Down Expand Up @@ -52,7 +61,9 @@ function getRepoParams() {

function getIssueNumber(): number {
const issueNumberInput = core.getInput('issue-number')
const issueNumber = issueNumberInput ? Number.parseInt(issueNumberInput, 10) : github.context.issue.number
const issueNumber = issueNumberInput
? Number.parseInt(issueNumberInput, 10)
: github.context.issue.number

if (!Number.isInteger(issueNumber) || issueNumber <= 0)
throw new Error('Missing issue number')
Expand All @@ -72,16 +83,22 @@ function isReactionContent(value: string): value is ReactionContent {
}

function getCloseReason(): CloseReason {
return core.getInput('close-reason') === 'completed' ? 'completed' : 'not_planned'
return core.getInput('close-reason') === 'completed'
? 'completed'
: 'not_planned'
}

function getIssueState(value: string | undefined): IssueState {
return value === 'closed' ? 'closed' : 'open'
return value === 'closed'
? 'closed'
: 'open'
}

function getLabelNames(labels: Array<string | { name?: string | null }>): string[] {
return labels
.map(label => (typeof label === 'string' ? label : label.name || ''))
.map(label => (typeof label === 'string'
? label
: label.name || ''))
.filter(Boolean)
}

Expand Down Expand Up @@ -145,21 +162,29 @@ async function updateIssue(octokit: Octokit) {
const state = core.getInput('state')
const labels = splitInput(core.getInput('labels'))
const assignees = splitInput(core.getInput('assignees'))
const updateMode = core.getInput('update-mode') === 'append' ? 'append' : 'replace'
const updateMode = core.getInput('update-mode') === 'append'
? 'append'
: 'replace'
const { data: issue } = await octokit.rest.issues.get(params)
const nextBody = body
? updateMode === 'append'
? `${issue.body || ''}\n${body}`
: body
: issue.body || ''

const nextState = state === 'closed' || state === 'open' ? state : getIssueState(issue.state)
const nextState = state === 'closed' || state === 'open'
? state
: getIssueState(issue.state)

await octokit.rest.issues.update({
...params,
assignees: assignees.length ? assignees : getAssigneeNames(issue.assignees),
assignees: assignees.length
? assignees
: getAssigneeNames(issue.assignees),
body: nextBody,
labels: labels.length ? labels : getLabelNames(issue.labels),
labels: labels.length
? labels
: getLabelNames(issue.labels),
state: nextState,
title: title || issue.title,
})
Expand All @@ -168,7 +193,9 @@ async function updateIssue(octokit: Octokit) {
async function setIssueLabels(octokit: Octokit, params: ReturnType<typeof getIssueParams>, labels: string[]) {
const { data: issue } = await octokit.rest.issues.get(params)
const baseLabels = getLabelNames(issue.labels)
const nextLabels = [...new Set(labels)]
const nextLabels = [
...new Set(labels),
]
const removeLabels = baseLabels.filter(label => !nextLabels.includes(label))
const addLabels = nextLabels.filter(label => !baseLabels.includes(label))

Expand Down
4 changes: 3 additions & 1 deletion actions/maintain-one-comment/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,7 @@ import * as core from '@actions/core'
import { main } from './main'

main().catch((error) => {
core.setFailed(`maintain-one-comment failed: ${error instanceof Error ? error.message : String(error)}`)
core.setFailed(`maintain-one-comment failed: ${error instanceof Error
? error.message
: String(error)}`)
})
20 changes: 15 additions & 5 deletions actions/maintain-one-comment/main.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,9 @@ describe('maintain-one-comment', () => {
})),
})
.mockResolvedValueOnce({
data: [{ body: 'comment-101', id: 101 }],
data: [
{ body: 'comment-101', id: 101 },
],
}),
updateComment: vi.fn(),
}
Expand Down Expand Up @@ -93,7 +95,9 @@ describe('maintain-one-comment', () => {

it('没有匹配评论时创建新评论', async () => {
const issues = {
createComment: vi.fn().mockResolvedValue({ data: { body: 'new body', id: 9 } }),
createComment: vi.fn().mockResolvedValue({
data: { body: 'new body', id: 9 },
}),
deleteComment: vi.fn(),
listComments: vi.fn().mockResolvedValue({ data: [] }),
updateComment: vi.fn(),
Expand Down Expand Up @@ -124,7 +128,9 @@ describe('maintain-one-comment', () => {
{ body: 'old <!-- tdesign-maintain-one-comment -->', id: 3 },
],
}),
updateComment: vi.fn().mockResolvedValue({ data: { body: 'new <!-- tdesign-maintain-one-comment -->', id: 3 } }),
updateComment: vi.fn().mockResolvedValue({
data: { body: 'new <!-- tdesign-maintain-one-comment -->', id: 3 },
}),
}

await expect(maintainOneComment(issues, {
Expand Down Expand Up @@ -153,7 +159,9 @@ describe('maintain-one-comment', () => {
{ body: 'duplicate <!-- marker -->', id: 5 },
],
}),
updateComment: vi.fn().mockResolvedValue({ data: { body: 'new <!-- marker -->', id: 3 } }),
updateComment: vi.fn().mockResolvedValue({
data: { body: 'new <!-- marker -->', id: 3 },
}),
}

await expect(maintainOneComment(issues, {
Expand Down Expand Up @@ -186,7 +194,9 @@ describe('maintain-one-comment', () => {
{ body: 'old body\n<!-- marker -->', id: 3 },
],
}),
updateComment: vi.fn().mockResolvedValue({ data: { body: 'new body\n<!-- marker -->', id: 3 } }),
updateComment: vi.fn().mockResolvedValue({
data: { body: 'new body\n<!-- marker -->', id: 3 },
}),
}

await expect(maintainOneComment(issues, {
Expand Down
4 changes: 3 additions & 1 deletion actions/maintain-one-comment/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@ export function findMatchingComments(comments: IssueComment[], selector: string)
}

export function buildCommentBody(body: string, bodyInclude?: string): string {
return bodyInclude && !body.includes(bodyInclude) ? `${body}\n${bodyInclude}` : body
return bodyInclude && !body.includes(bodyInclude)
? `${body}\n${bodyInclude}`
: body
}

export async function listIssueComments(
Expand Down
15 changes: 12 additions & 3 deletions actions/upgrade-deps/src/constants.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,16 @@
export const PACKAGE_MANAGER_COMMANDS = {
pnpm: { cmd: 'pnpm', args: ['up', '-r'] },
yarn: { cmd: 'yarn', args: ['upgrade', '--latest'] },
npm: { cmd: 'npm', args: ['install'] },
pnpm: {
cmd: 'pnpm',
args: ['up', '-r'],
},
yarn: {
cmd: 'yarn',
args: ['upgrade', '--latest'],
},
npm: {
cmd: 'npm',
args: ['install'],
},
} as const

export const PR_TEMPLATE_PATHS = [
Expand Down
29 changes: 23 additions & 6 deletions actions/upgrade-deps/src/dependencies.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ export function parseDependencyName(spec: string): string {
const value = spec.trim()
if (!value)
throw new Error('Empty dependency name')
const separator = value.startsWith('@') ? value.indexOf('@', value.indexOf('/') + 1) : value.lastIndexOf('@')
const separator = value.startsWith('@')
? value.indexOf('@', value.indexOf('/') + 1)
: value.lastIndexOf('@')
if (separator > 0)
throw new Error(`Dependency versions are not supported: ${spec}. Please pass package names only.`)
return value
Expand Down Expand Up @@ -71,7 +73,7 @@ export function updatePackageManifestVersions(
if (specifier === undefined)
continue
if (typeof specifier !== 'string')
throw new Error(`Unsupported version specifier for ${manifestPath}#${field}.${dep.name}: expected a string`)
throw new TypeError(`Unsupported version specifier for ${manifestPath}#${field}.${dep.name}: expected a string`)
if (specifier.startsWith('catalog:'))
continue
const nextSpecifier = updateVersionSpecifier(specifier, dep.version, `${manifestPath}#${field}.${dep.name}`)
Expand All @@ -92,12 +94,27 @@ export async function fetchPackageVersion(pkg: string): Promise<DependencyInfo>
const { version, repository } = await response.json() as { repository?: string | { directory?: string, url?: string }, version?: string }
if (!version)
throw new Error('no version found')
const repositoryUrl = typeof repository === 'string' ? repository : repository?.url
const repositoryDirectory = typeof repository === 'object' ? repository?.directory : undefined
return { name: pkg, version, ...(repositoryUrl ? { repositoryUrl } : {}), ...(repositoryDirectory ? { repositoryDirectory } : {}) }
const repositoryUrl = typeof repository === 'string'
? repository
: repository?.url
const repositoryDirectory = typeof repository === 'object'
? repository?.directory
: undefined
return {
name: pkg,
version,
...(repositoryUrl
? { repositoryUrl }
: {}),
...(repositoryDirectory
? { repositoryDirectory }
: {}),
}
}
catch (error) {
throw new Error(`Failed to get ${pkg} info from npm registry: ${error instanceof Error ? error.message : String(error)}`)
throw new Error(`Failed to get ${pkg} info from npm registry: ${error instanceof Error
? error.message
: String(error)}`)
}
}

Expand Down
21 changes: 16 additions & 5 deletions actions/upgrade-deps/src/github.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ export function parseGithubRepository(repositoryUrl?: string): GithubRepository
return undefined
const [owner, name] = url.pathname.replace(/^\//, '').split('/')
const repo = name?.replace(/\.git$/, '')
return owner && repo ? { owner, repo } : undefined
return owner && repo
? { owner, repo }
: undefined
}
catch {
return undefined
Expand All @@ -22,7 +24,9 @@ export function parseGithubRepository(repositoryUrl?: string): GithubRepository

function getMarkdownHeading(line: string): string | undefined {
const prefix = line.match(/^#{1,6}[ \t]+/)
return prefix ? line.slice(prefix[0].length).trim() : undefined
return prefix
? line.slice(prefix[0].length).trim()
: undefined
}

export function extractVersionChangelog(content: string, version: string): string | undefined {
Expand All @@ -38,7 +42,9 @@ export function extractVersionChangelog(content: string, version: string): strin
if (!level)
return undefined
const end = lines.findIndex((line, index) => index > start && (line.match(/^#{1,6}(?=[ \t])/)?.[0].length ?? 7) <= level)
return lines.slice(start, end === -1 ? undefined : end).join('\n').trim()
return lines.slice(start, end === -1
? undefined
: end).join('\n').trim()
}

export async function fetchDependencyRelease(dep: DependencyInfo, token: string): Promise<DependencyRelease | undefined> {
Expand All @@ -51,7 +57,10 @@ export async function fetchDependencyRelease(dep: DependencyInfo, token: string)
if (token && token !== 'test')
headers.Authorization = `Bearer ${token}`
try {
const changelogPath = [...(dep.repositoryDirectory?.split('/').filter(Boolean) ?? []), 'CHANGELOG.md'].map(encodeURIComponent).join('/')
const changelogPath = [
...(dep.repositoryDirectory?.split('/').filter(Boolean) ?? []),
'CHANGELOG.md',
].map(encodeURIComponent).join('/')
const response = await fetch(`https://api.github.com/repos/${repository.owner}/${repository.repo}/contents/${changelogPath}`, { headers })
if (response.status === 404) {
core.warning(`No CHANGELOG.md found for ${dep.name}`)
Expand All @@ -68,7 +77,9 @@ export async function fetchDependencyRelease(dep: DependencyInfo, token: string)
return { body, tag: `${dep.name}@${dep.version}`, url }
}
catch (error) {
core.warning(`Failed to get CHANGELOG.md for ${dep.name}@${dep.version}: ${error instanceof Error ? error.message : String(error)}`)
core.warning(`Failed to get CHANGELOG.md for ${dep.name}@${dep.version}: ${error instanceof Error
? error.message
: String(error)}`)
return undefined
}
}
Expand Down
4 changes: 3 additions & 1 deletion actions/upgrade-deps/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,7 @@ import * as core from '@actions/core'
import { main } from './main'

main().catch((error) => {
core.setFailed(`upgrade-deps failed: ${error instanceof Error ? error.message : String(error)}`)
core.setFailed(`upgrade-deps failed: ${error instanceof Error
? error.message
: String(error)}`)
})
21 changes: 18 additions & 3 deletions actions/upgrade-deps/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,12 @@ export async function updateDependencies(context: TriggerContext): Promise<void>
let depInfos = await resolveDependencyInfos(deps)
if (packageManager !== 'npm')
await exec.exec('corepack', ['enable'])
const gitHelper = new GitHelper({ repo: context.repo, owner: context.owner, token: context.token, dryRun: context.dryRun })
const gitHelper = new GitHelper({
repo: context.repo,
owner: context.owner,
token: context.token,
dryRun: context.dryRun,
})
const baseBranch = await gitHelper.clone()
await gitHelper.initSubmodule()
const template = await readPullRequestTemplate(`./${context.repo}`)
Expand All @@ -39,13 +44,23 @@ export async function updateDependencies(context: TriggerContext): Promise<void>
const body = buildPullRequestBody(template, depInfos, context.repo)
await gitHelper.commit(title)
await gitHelper.push(branchName)
const githubHelper = new GithubHelper({ owner: context.owner, repo: context.repo, token: context.token, dryRun: context.dryRun })
const githubHelper = new GithubHelper({
owner: context.owner,
repo: context.repo,
token: context.token,
dryRun: context.dryRun,
})
await githubHelper.createPR(title, branchName, body, baseBranch)
}

export async function main(): Promise<void> {
const repo = core.getInput('repo') || github.context.repo.repo
const owner = core.getInput('owner') || github.context.repo.owner
const token = core.getInput('token', { required: true })
await updateDependencies({ repo, owner, token, dryRun: core.getBooleanInput('dry-run') })
await updateDependencies({
repo,
owner,
token,
dryRun: core.getBooleanInput('dry-run'),
})
}
Loading
Loading