Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: add test case #31

Merged
merged 23 commits into from
Oct 16, 2024
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
50 changes: 50 additions & 0 deletions src/generator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { readFileSync } from 'node:fs'
import process from 'node:process'
import { getInput, info, setOutput } from '@actions/core'
import dayjs from 'dayjs'
import { getPullNumbers, renderMarkdown } from './renderer'
import type { PullsData } from './types'
import { useOctokit } from './useOctokit'

export async function generatorLogStart(context) {
const GITHUB_TOKEN = process.env.GITHUB_TOKEN || ''
const { generateReleaseNotes, getPullRequest } = useOctokit({ token: GITHUB_TOKEN })
let tag = getInput('tag', { required: false })
if (!tag) {
const pkg = JSON.parse(readFileSync('./package.json', 'utf-8'))
tag = pkg.version
}
const { owner, repo } = context.repo
info(`owner:${owner}, repo:${repo}`)

const releases = await generateReleaseNotes(
owner,
repo,
tag,
'develop',
)

const PRNumbers = getPullNumbers(releases.data.body)

const PRListRes = await Promise.all(PRNumbers.map(pull_number => getPullRequest(
owner,
repo,
pull_number,
)))

const PRList = PRListRes.map(res => res.data as PullsData)

info(`PRList:${JSON.stringify(PRList)}`)

const logRelease = `(删除此行代表确认该日志): 修改并确认日志后删除这一行,机器人会提交到 本 PR 的 CHANGELOG.md 文件中
## 🌈 ${tag} \`${dayjs().format('YYYY-MM-DD')}\` \n${renderMarkdown(PRList)}\n`

info(logRelease)

setActionOutput(logRelease)
return logRelease
}

function setActionOutput(changelog: string) {
setOutput('changelog', changelog)
}
55 changes: 4 additions & 51 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,9 @@
import fs from 'node:fs'
import process from 'node:process'
import { getInput, info, setFailed, setOutput } from '@actions/core'
import { context, getOctokit } from '@actions/github'
import dayjs from 'dayjs'
import { getPReformatNotes, renderMarkdown } from './renderer'
import type { PullsData } from './types'
import { info, setFailed } from '@actions/core'
import { context } from '@actions/github'
import { generatorLogStart } from './generator'

const GITHUB_TOKEN = process.env.GITHUB_TOKEN

info(`github.context:${JSON.stringify(context)}`)

// console.log('payload', context.payload);
Expand All @@ -18,50 +14,7 @@ if (!GITHUB_TOKEN) {
)
}

const octokit = getOctokit(GITHUB_TOKEN)

async function generatorLogStart() {
let tag = getInput('tag', { required: false })
if (!tag) {
const pkg = JSON.parse(fs.readFileSync('./package.json', 'utf-8'))
tag = pkg.version
}
const { owner, repo } = context.repo
info(`owner:${owner}, repo:${repo}`)

const releases = await octokit.rest.repos.generateReleaseNotes({
owner,
repo,
tag_name: tag, // 'package.version'
target_commitish: 'develop', // 也可以从上下文中拿
})

const PRNumbers = getPReformatNotes(releases.data.body)

const PRListRes = await Promise.all(PRNumbers.map(pull_number => octokit.rest.pulls.get({
owner,
repo,
pull_number,
})))

const PRList = PRListRes.map(res => res.data as PullsData)

info(`PRList:${JSON.stringify(PRList)}`)

const logRelease = `(删除此行代表确认该日志): 修改并确认日志后删除这一行,机器人会提交到 本 PR 的 CHANGELOG.md 文件中
## 🌈 ${tag} \`${dayjs().format('YYYY-MM-DD')}\` \n${renderMarkdown(PRList)}\n`

info(logRelease)

setActionOutput(logRelease)
return logRelease
}

generatorLogStart().catch((error) => {
generatorLogStart(context).catch((error) => {
console.error(error)
setFailed(`💥 Auto Release failed with error: ${error.message}`)
})

function setActionOutput(changelog: string) {
setOutput('changelog', changelog)
}
61 changes: 29 additions & 32 deletions src/renderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,29 @@ const skipChangelogLabel = ['skip-changelog']
const fixLabel = ['fix', 'bug', 'hotfix']
const breakingLabel = ['break', 'breaking', 'breaking changes']
const featureLabel = ['feature', 'feat', 'enhancement']

export function getPReformatNotes(body: string) {
const reg = /in\shttps:\/\/github\.com\/.+\/pull\/(\d+)\s/g

const arr = [...body.matchAll(reg)]

return arr.map(n => Number(n[1])) // pr number list
const docsLabel = ['docs', 'doc', 'documentation']
const refactorLabel = ['pref', 'refactor']

export const CHANGELOG_REG = /-\s([A-Z]+)(?:\(([A-Z\s]*)\))?:\s(.+)/gi
export const PULL_NUMBER_REG = /in\shttps:\/\/github\.com\/.+\/pull\/(\d+)/g
export const SKIP_CHANGELOG_REG = /\[x\] 本条 PR 不需要纳入 changelog/i
export function getPullNumbers(body: string) {
const arr = [...body.matchAll(PULL_NUMBER_REG)]
const pullNumbers = arr.map(n => Number(n[1])) // pr number list
const uniquePullNumbers = [...new Set(pullNumbers)]
return uniquePullNumbers
}

function regToPrObj(arr: string[]) {
return {
cate: arr[1],
component: arr[2],
component: arr[2] || '',
desc: arr[3],
}
}
function renderCate(cate: PRChangelog[]) {
return `${cate.sort().map((pr) => {
const title = pr.changelog ? `\`${pr.changelog.component}\`: ${pr.changelog.desc}` : pr.title
const title = pr.changelog ? `\`${pr.changelog.component || pr.changelog.cate}\`: ${pr.changelog.desc}` : pr.title
return `- ${title} @${pr.user.login} ([#${pr.number}](${pr.html_url}))`
}).join('\n')}`
}
Expand All @@ -35,6 +39,8 @@ export function renderMarkdown(pullRequestList: PullsData[]) {
breaking: [] as PRChangelog[],
features: [] as PRChangelog[],
bugfix: [] as PRChangelog[],
refactor: [] as PRChangelog[],
docs: [] as PRChangelog[],
extra: [] as PRChangelog[],
}

Expand All @@ -47,15 +53,13 @@ export function renderMarkdown(pullRequestList: PullsData[]) {
return
}
// 在 pr body 明确填了 跳过 label
if (/\[x\] 本条 PR 不需要纳入 changelog/i.test(pr.body)) {
if (SKIP_CHANGELOG_REG.test(pr.body)) {
info(`pr ${pr.number} 显示不需要纳入 changelog`)
return
}

if (pr.body.includes('### 📝 更新日志')) {
const reg = /-\s([A-Z]+)\(([A-Z]+)\):\s(.+)/gi

const arr = [...pr.body.matchAll(reg)]
const arr = [...pr.body.matchAll(CHANGELOG_REG)]

if (arr.length === 0) {
info(`没有找到任何一条日志内容 number:${pr.number}, body:${pr.body}`)
Expand All @@ -82,6 +86,12 @@ export function renderMarkdown(pullRequestList: PullsData[]) {
else if (isInLabel(fixLabel)) {
categories.bugfix.push(logItem)
}
else if (isInLabel(refactorLabel)) {
categories.refactor.push(logItem)
}
else if (isInLabel(docsLabel)) {
categories.docs.push(logItem)
}
else {
categories.extra.push(logItem)
}
Expand All @@ -95,24 +105,11 @@ export function renderMarkdown(pullRequestList: PullsData[]) {
})

return [
categories.breaking.length
? `### ❗ Breaking Changes
${renderCate(categories.breaking)}`
: '',

categories.features.length
? `### 🚀 Features
${renderCate(categories.features)}`
: '',

categories.bugfix.length
? `### 🐞 Bug Fixes
${renderCate(categories.bugfix)}`
: '',

categories.extra.length
? `### 🚧 Others
${renderCate(categories.extra)}`
: '',
categories.breaking.length ? `### ❗ Breaking Changes\n${renderCate(categories.breaking)}` : '',
categories.features.length ? `### 🚀 Features\n${renderCate(categories.features)}` : '',
categories.bugfix.length ? `### 🐞 Bug Fixes\n${renderCate(categories.bugfix)}` : '',
categories.refactor.length ? `### 📈 Performance\n${renderCate(categories.refactor)}` : '',
categories.docs.length ? `### 📝 Documentation\n${renderCate(categories.docs)}` : '',
categories.extra.length ? `### 🚧 Others\n${renderCate(categories.extra)}` : '',
].filter(n => n).join('\n')
}
34 changes: 34 additions & 0 deletions src/useOctokit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { getOctokit } from '@actions/github'

export interface OctokitContext {
token: string
owner?: string
repo?: string
}
export function useOctokit(context: OctokitContext) {
const octokit = getOctokit(context.token)

const generateReleaseNotes = async (owner: string, repo: string, tag_name: string, target_commitish: string) => {
const res = octokit.rest.repos.generateReleaseNotes({
owner,
repo,
tag_name,
target_commitish,
})
return res
}

const getPullRequest = (owner: string, repo: string, pull_number: number) => {
const res = octokit.rest.pulls.get({
owner,
repo,
pull_number,
})
return res
}

return {
generateReleaseNotes,
getPullRequest,
}
}
27 changes: 27 additions & 0 deletions test/__snapshots__/generatorLog.test.ts.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html

exports[`generatorLog > : generatorLogStart 1`] = `
"(删除此行代表确认该日志): 修改并确认日志后删除这一行,机器人会提交到 本 PR 的 CHANGELOG.md 文件中
## 🌈 x.x.x \`2024-02-24\`
### ❗ Breaking Changes
- \`C\`: a major update label in break @liweijie0812 ([#29](https://github.com/TDesignOteam/tdesign-changelog-action/pull/29))
- \`C\`: a major update label in breaking @liweijie0812 ([#29](https://github.com/TDesignOteam/tdesign-changelog-action/pull/29))
- \`g\`: a minor fix label in break @liweijie0812 ([#29](https://github.com/TDesignOteam/tdesign-changelog-action/pull/29))
- \`H H\`: a major update label in break @liweijie0812 ([#29](https://github.com/TDesignOteam/tdesign-changelog-action/pull/29))
### 🚀 Features
- \`B\`: a feature label in feat @liweijie0812 ([#29](https://github.com/TDesignOteam/tdesign-changelog-action/pull/29))
- \`B\`: a feature label in feature @liweijie0812 ([#29](https://github.com/TDesignOteam/tdesign-changelog-action/pull/29))
- \`B\`: a feature label in enhancement @liweijie0812 ([#29](https://github.com/TDesignOteam/tdesign-changelog-action/pull/29))
- \`D\`: a feature label in feat @liweijie0812 ([#29](https://github.com/TDesignOteam/tdesign-changelog-action/pull/29))
### 🐞 Bug Fixes
- \`A\`: a bug fix label in fix @liweijie0812 ([#29](https://github.com/TDesignOteam/tdesign-changelog-action/pull/29))
- \`A\`: a bug fix label in hotfix @liweijie0812 ([#29](https://github.com/TDesignOteam/tdesign-changelog-action/pull/29))
- \`A\`: a bug fix label in bug @liweijie0812 ([#29](https://github.com/TDesignOteam/tdesign-changelog-action/pull/29))
### 📈 Performance
- \`I\`: a refactor label in refactor @liweijie0812 ([#29](https://github.com/TDesignOteam/tdesign-changelog-action/pull/29))
### 📝 Documentation
- \`docs\`: a doc change label in docs @liweijie0812 ([#29](https://github.com/TDesignOteam/tdesign-changelog-action/pull/29))
### 🚧 Others
- \`chore\`: a chore label in chore @liweijie0812 ([#29](https://github.com/TDesignOteam/tdesign-changelog-action/pull/29))
"
`;
Loading