Skip to content

Commit

Permalink
Merge pull request #312 from 142vip/feat/changelog-types
Browse files Browse the repository at this point in the history
feat(@142vip/changelog): 补充类型,移除无用函数,简化逻辑
  • Loading branch information
mmdapl authored Jan 19, 2025
2 parents aa6a1ca + faa6dad commit 3dd70e5
Show file tree
Hide file tree
Showing 5 changed files with 36 additions and 55 deletions.
12 changes: 5 additions & 7 deletions packages/changelog/src/core/changelog.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
/* eslint-disable no-console */
import process from 'node:process'
import { getGitDiff, parseGitCommit } from 'changelogen'
import { VipCommander, vipColor } from '@142vip/utils'
import { VipCommander, VipJSON, vipColor } from '@142vip/utils'
import { name as packageName, version as packageVersion } from '../../package.json'
import {
generateMarkdown,
Expand All @@ -23,9 +22,8 @@ import { ChangelogDefaultConfig } from './config'
/**
* 加载配置
* 将用户自定义配置和默认配置合并
* @param options
*/
async function resolveConfig(options: ChangelogOptions) {
async function resolveConfig(options: ChangelogOptions): Promise<ResolvedChangelogOptions> {
const { loadConfig } = await import('c12')
const config = await loadConfig<ChangelogOptions>({
// 配置文件名,eg: changelog.config.ts
Expand Down Expand Up @@ -53,7 +51,7 @@ async function resolveConfig(options: ChangelogOptions) {
config.scopeName = options.scopeName

if (typeof config.repo !== 'string')
throw new Error(`无效的 GitHub 存储库,需要一个字符串,但实际repo参数是: ${JSON.stringify(config.repo)}`)
throw new Error(`无效的 GitHub 存储库,需要一个字符串,但实际repo参数是: ${VipJSON.stringify(config.repo)}`)

return config as ResolvedChangelogOptions
}
Expand Down Expand Up @@ -100,14 +98,14 @@ async function generate(options: ChangelogOptions) {
/**
* 处理changelog业务
*/
async function dealChangelog(args: ChangelogOptions) {
async function dealChangelog(args: ChangelogOptions): Promise<void> {
args.token = args.token || process.env.GITHUB_TOKEN

let webUrl = ''

try {
console.log()
console.log(vipColor.dim(`${vipColor.bold('@142vip/changelog')} `) + vipColor.dim(`v${packageVersion}`))
console.log(vipColor.dim(`${vipColor.bold(packageName)} `) + vipColor.dim(`v${packageVersion}`))

const { config, markdown, commits } = await generate(args)
webUrl = generateWebUrl(config, markdown)
Expand Down
3 changes: 2 additions & 1 deletion packages/changelog/src/core/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export const ChangelogDefaultConfig: ChangelogOptions = {
titles: {
breakingChanges: '🚨 Breaking Changes',
},
// token令牌信息
tokens: {
github: process.env.GITHUB_TOKEN || process.env.TOKEN,
},
Expand All @@ -31,6 +32,6 @@ export const ChangelogDefaultConfig: ChangelogOptions = {
/**
* 定义配置文件
*/
export function defineChangelogDefaultConfig(config: ChangelogOptions) {
export function defineChangelogDefaultConfig(config: ChangelogOptions): ChangelogOptions {
return config
}
26 changes: 8 additions & 18 deletions packages/changelog/src/utils/git.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import semver from 'semver'
/**
* 获取github仓库
*/
export async function getGitHubRepo(baseUrl: string) {
export async function getGitHubRepo(baseUrl: string): Promise<string> {
const url = await execCommand('git', ['config', '--get', 'remote.origin.url'])
const escapedBaseUrl = baseUrl.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
const regex = new RegExp(`${escapedBaseUrl}[\/:]([\\w\\d._-]+?)\\/([\\w\\d._-]+?)(\\.git)?$`, 'i')
Expand All @@ -13,20 +13,20 @@ export async function getGitHubRepo(baseUrl: string) {
return `${match[1]}/${match[2]}`
}

export async function getCurrentGitBranch() {
export async function getCurrentGitBranch(): Promise<string> {
return await execCommand('git', ['tag', '--points-at', 'HEAD']) || await execCommand('git', ['rev-parse', '--abbrev-ref', 'HEAD'])
}

export async function isRepoShallow() {
export async function isRepoShallow(): Promise<boolean> {
return (await execCommand('git', ['rev-parse', '--is-shallow-repository'])).trim() === 'true'
}

export async function getGitTags() {
export async function getGitTags(): Promise<string[]> {
return (await execCommand('git', ['--no-pager', 'tag', '-l', '--sort=creatordate']).then(r => r.split('\n')))
.reverse()
}

function getTagWithoutPrefix(tag: string) {
function getTagWithoutPrefix(tag: string): string {
return tag.replace(/^v/, '')
}

Expand Down Expand Up @@ -54,25 +54,15 @@ export async function getLastMatchingTag(inputTag: string) {
return tag
}

export async function isRefGitTag(to: string) {
const { execa } = await import('execa')
try {
await execa('git', ['show-ref', '--verify', `refs/tags/${to}`], { reject: true })
}
catch {
return false
}
}

export async function getFirstGitCommit() {
export async function getFirstGitCommit(): Promise<string> {
return await execCommand('git', ['rev-list', '--max-parents=0', 'HEAD'])
}

export function isPrerelease(version: string) {
export function isPrerelease(version: string): boolean {
return !/^[^.]*(?:\.[\d.]*|\d)$/.test(version)
}

async function execCommand(cmd: string, args: string[]) {
async function execCommand(cmd: string, args: string[]): Promise<string> {
const { execa } = await import('execa')
const res = await execa(cmd, args)
return res.stdout.trim()
Expand Down
32 changes: 11 additions & 21 deletions packages/changelog/src/utils/github.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,7 @@ import type {
Commit,
} from '../types'

export async function sendRelease(
options: ChangelogOptions,
content: string,
) {
export async function sendRelease(options: ChangelogOptions, content: string): Promise<void> {
const headers = getHeaders(options)
let url = `https://${options.baseUrlApi}/repos/${options.repo}/releases`
let method = 'POST'
Expand Down Expand Up @@ -68,8 +65,7 @@ export async function resolveAuthorInfo(options: ChangelogOptions, info: AuthorI
})
info.login = data.items[0].login
}
catch {
}
catch { }

if (info.login)
return info
Expand All @@ -81,8 +77,7 @@ export async function resolveAuthorInfo(options: ChangelogOptions, info: AuthorI
})
info.login = data.author.login
}
catch {
}
catch { }
}
return info
}
Expand Down Expand Up @@ -133,10 +128,8 @@ export async function resolveAuthors(commits: Commit[], options: ChangelogOption

/**
* 判断是否有tag
* @param tag
* @param options
*/
export async function hasTagOnGitHub(tag: string, options: ChangelogOptions) {
export async function hasTagOnGitHub(tag: string, options: ChangelogOptions): Promise<boolean> {
try {
await $fetch(`https://${options.baseUrlApi}/repos/${options.repo}/git/ref/tags/${tag}`, {
headers: getHeaders(options),
Expand All @@ -151,7 +144,7 @@ export async function hasTagOnGitHub(tag: string, options: ChangelogOptions) {
/**
* 生成webUrl链接
*/
export function generateWebUrl(config: any, markdown: string) {
export function generateWebUrl(config: any, markdown: string): string {
const baseUrl = `https://${config.baseUrl}/${config.repo}/releases/new`
const queryParams = vipQs.stringify({
title: config.name || config.to,
Expand All @@ -166,14 +159,11 @@ export function generateWebUrl(config: any, markdown: string) {
/**
* 打印手动发布地址
* - 默认成功输出
* @param webUrl
* @param success
*/
export function printUrl(webUrl: string, success: boolean = true) {
if (success) {
console.error(`\n${vipColor.yellow('使用以下链接手动发布新的版本:')}\n${vipColor.yellow(webUrl)}\n`)
}
else {
console.error(`\n${vipColor.red('无法创建发布。使用以下链接手动创建:')}\n${vipColor.yellow(webUrl)}\n`)
}
export function printUrl(webUrl: string, success: boolean = true): void {
const errMsg = success
? `\n${vipColor.yellow('使用以下链接手动发布新的版本:')}\n`
: `\n${vipColor.red('无法创建发布。使用以下链接手动创建:')}\n`

console.error(`${errMsg}${vipColor.yellow(webUrl)}\n`)
}
18 changes: 10 additions & 8 deletions packages/changelog/src/utils/markdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,13 @@ function formatReferences(references: Reference[], baseUrl: string, github: stri
return referencesString
}

function formatLine(commit: Commit, options: ResolvedChangelogOptions) {
function formatLine(commit: Commit, options: ResolvedChangelogOptions): string {
const prRefs = formatReferences(commit.references, options.baseUrl, options.repo as string, 'issues')
const hashRefs = formatReferences(commit.references, options.baseUrl, options.repo as string, 'hash')

let authors = join([...new Set(commit.resolvedAuthors?.map(i => i.login ? `@${i.login}` : `**${i.name}**`))])?.trim()
let authors = join([
...new Set(commit.resolvedAuthors?.map(i => i.login ? `@${i.login}` : `**${i.name}**`)),
])?.trim()

if (authors)
authors = `by ${authors}`
Expand All @@ -52,7 +54,7 @@ function formatLine(commit: Commit, options: ResolvedChangelogOptions) {
/**
* 格式化标题
*/
function formatTitle(name: string, options: ResolvedChangelogOptions) {
function formatTitle(name: string, options: ResolvedChangelogOptions): string {
// 加表情包
if (!options.emoji)
name = name.replace(emojisRE, '')
Expand All @@ -63,7 +65,7 @@ function formatTitle(name: string, options: ResolvedChangelogOptions) {
/**
* 格式化Section
*/
function formatSection(commits: Commit[], sectionName: string, options: ResolvedChangelogOptions) {
function formatSection(commits: Commit[], sectionName: string, options: ResolvedChangelogOptions): string[] {
if (!commits.length)
return []

Expand Down Expand Up @@ -117,7 +119,7 @@ function formatSection(commits: Commit[], sectionName: string, options: Resolved
/**
* 生成Markdown文档
*/
export async function generateMarkdown(commits: Commit[], options: ResolvedChangelogOptions) {
export async function generateMarkdown(commits: Commit[], options: ResolvedChangelogOptions): Promise<string> {
const lines: string[] = []

const breaking = commits.filter(c => c.isBreaking)
Expand Down Expand Up @@ -173,7 +175,7 @@ function formatDateToYMD(date: Date = new Date()): string {
/**
* 更新changelog
*/
export async function updateChangelog(outputPath: string, markdown: string, releaseVersionName: string) {
export async function updateChangelog(outputPath: string, markdown: string, releaseVersionName: string): Promise<void> {
let changelogMD: string
if (existsSync(outputPath)) {
console.info(`Updating ${outputPath}`)
Expand Down Expand Up @@ -202,7 +204,7 @@ export async function updateChangelog(outputPath: string, markdown: string, rele
/**
* 分组
*/
function groupBy<T>(items: T[], key: string, groups: Record<string, T[]> = {}) {
function groupBy<T>(items: T[], key: string, groups: Record<string, T[]> = {}): Record<string, T[]> {
for (const item of items) {
const v = (item as any)[key] as string
groups[v] = groups[v] || []
Expand All @@ -211,7 +213,7 @@ function groupBy<T>(items: T[], key: string, groups: Record<string, T[]> = {}) {
return groups
}

function capitalize(str: string) {
function capitalize(str: string): string {
return str.charAt(0).toUpperCase() + str.slice(1)
}

Expand Down

0 comments on commit 3dd70e5

Please sign in to comment.