Skip to content

Commit

Permalink
perf(@142vip/release-version): 修复一些语法问题,使用更好的代码风格 (#44)
Browse files Browse the repository at this point in the history
* perf(@142vip/release-version): 修复一些语法问题,使用更好的代码风格

* chore: update
  • Loading branch information
mmdapl authored Aug 6, 2024
1 parent 64edaee commit fc7defc
Show file tree
Hide file tree
Showing 20 changed files with 90 additions and 210 deletions.
3 changes: 3 additions & 0 deletions packages/release-version/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@
# 安装
pnpm i @142vip/release-version -D

# 查看版本
npx bumpx -v

# 查看使用
npx bumpx -h
```
Expand Down
10 changes: 4 additions & 6 deletions packages/release-version/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@
"keywords": [
"@142vip/release-version",
"version",
"bump",
"bumpx",
"package",
"git",
"commit",
"tag",
"push"
],
Expand Down Expand Up @@ -50,24 +50,22 @@
},
"devDependencies": {
"@types/js-yaml": "^4.0.9",
"@types/node": "^20.12.7",
"@types/prompts": "^2.4.9",
"@types/semver": "^7.5.8",
"detect-indent": "^7.0.1",
"detect-newline": "^4.0.1",
"log-symbols": "^6.0.0",
"npm-check": "^6.0.1",
"kolorist": "^1.8.0",
"rimraf": "^5.0.5"
"kolorist": "^1.8.0"
},
"author": {
"name": "James Messinger",
"url": "https://jamesmessinger.com"
},
"homepage": "https://github.com/antfu/bumpp",
"homepage": "https://github.com/142vip/core-x/tree/main/packages/release-version",
"repository": {
"type": "git",
"url": "https://github.com/142vip/release-version.git"
"url": "https://github.com/142vip/core-x.git"
},
"publishConfig": {
"access": "public",
Expand Down
50 changes: 5 additions & 45 deletions packages/release-version/src/bumpx-cli.ts
Original file line number Diff line number Diff line change
@@ -1,58 +1,18 @@
import process from 'node:process'
import symbols from 'log-symbols'
import { version as packageVersion } from '../package.json'
import { parseArgs } from './utils'
import { errorHandler, parseArgs, showProgress } from './utils'
import { versionBump } from './core/version-bump'
import type { VersionBumpProgress } from './types'
import { ExitCodeEnum, ProgressEvent } from './types'

function progress({ event, script, updatedFiles, skippedFiles, newVersion }: VersionBumpProgress) {
switch (event) {
case ProgressEvent.FileUpdated:
console.log(symbols.success, `Updated ${updatedFiles.pop()} to ${newVersion}`)
break

case ProgressEvent.FileSkipped:
console.log(symbols.info, `${skippedFiles.pop()} did not need to be updated`)
break

case ProgressEvent.GitCommit:
console.log(symbols.success, 'Git commit')
break

case ProgressEvent.GitTag:
console.log(symbols.success, 'Git tag')
break

case ProgressEvent.GitPush:
console.log(symbols.success, 'Git push')
break

case ProgressEvent.NpmScript:
console.log(symbols.success, `Npm run ${script}`)
break
}
}

function errorHandler(error: Error): void {
let message = error.message || String(error)

if (process.env.DEBUG || process.env.NODE_ENV === 'development')
message = error.stack || message

console.error(message)
process.exit(ExitCodeEnum.FatalError)
}
import { ExitCodeEnum } from './types'

/**
* The main entry point of the CLI
* cli入口
*/
export async function main() {
try {
process.on('uncaughtException', errorHandler)
process.on('unhandledRejection', errorHandler)

// Parse the command-line arguments
// 解析参数
const { help, version, quiet, options } = await parseArgs()

// 显示帮助信息
Expand All @@ -68,7 +28,7 @@ export async function main() {

// 是否显示进度
if (!quiet)
options.progress = options.progress ? options.progress : progress
options.progress = options.progress ?? showProgress

// 执行版本升级
await versionBump(options)
Expand Down
5 changes: 1 addition & 4 deletions packages/release-version/src/core/fs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,7 @@ export function readTextFile(name: string, cwd: string): Promise<TextFile> {
reject(err)
}
else {
resolve({
path: filePath,
data: text,
})
resolve({ path: filePath, data: text })
}
})
})
Expand Down
28 changes: 11 additions & 17 deletions packages/release-version/src/core/get-current-version.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ import { isManifest } from './manifest'
import type { Operation } from './operation'

/**
* Finds the current version number from files such as package.json.
* An error is thrown if no version number can be found.
* 从package.json等文件中查找当前版本号。
* 如果找不到版本号,则会抛出错误
* @param operation
*/
export async function getCurrentVersion(operation: Operation): Promise<Operation> {
if (operation.state.currentVersion)
Expand All @@ -22,35 +23,28 @@ export async function getCurrentVersion(operation: Operation): Promise<Operation

// Check each file, in order, and return the first valid version number we find
for (const file of filesToCheck) {
const version = await readVersion(file, cwd)
const currentVersion = await readVersion(file, cwd)

if (version) {
if (currentVersion) {
// We found the current version number!
return operation.update({
currentVersionSource: file,
currentVersion: version,
})
return operation.update({ currentVersionSource: file, currentVersion })
}
}

// If we get here, then no version number was found
throw new Error(
`Unable to determine the current version number. Checked ${filesToCheck.join(', ')}.`,
)
throw new Error(`Unable to determine the current version number. Checked ${filesToCheck.join(', ')}.`)
}

/**
* Tries to read the version number from the specified JSON file.
*
* @returns - The version number, or undefined if the file doesn't have a version number
* 尝试从指定的 JSON 文件中读取版本号。
* 版本号,如果文件没有版本号,则未定义
*/
async function readVersion(file: string, cwd: string): Promise<string | undefined> {
try {
const { data: manifest } = await readJsonFile(file, cwd)

if (isManifest(manifest)) {
if (isValidVersion(manifest.version))
return manifest.version
if (isManifest(manifest) && isValidVersion(manifest.version)) {
return manifest.version
}
}
catch {
Expand Down
26 changes: 12 additions & 14 deletions packages/release-version/src/core/get-new-version.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import process from 'node:process'
import c from 'picocolors'
import prompts from 'prompts'
import semver, { SemVer, clean as cleanVersion, valid as isValidVersion } from 'semver'
import { bold, green } from 'kolorist'
import type { BumpRelease, PromptRelease } from './normalize-options'
import type { Operation } from './operation'
import type { ReleaseType } from './release-type'
Expand All @@ -19,9 +19,7 @@ export async function getNewVersion(operation: Operation): Promise<Operation> {
return promptForNewVersion(operation)

case 'version':
return operation.update({
newVersion: new SemVer(release.version, true).version,
})
return operation.update({ newVersion: new SemVer(release.version, true).version })

default:
return operation.update({
Expand Down Expand Up @@ -93,22 +91,22 @@ async function promptForNewVersion(operation: Operation): Promise<Operation> {
{
type: 'autocomplete',
name: 'release',
message: `Current version ${c.green(currentVersion)}`,
message: `Current version ${green(currentVersion)}`,
initial: configCustomVersion ? 'config' : 'next',
choices: [
{ value: 'major', title: `${'major'.padStart(PADDING, ' ')} ${c.bold(next.major)}` },
{ value: 'minor', title: `${'minor'.padStart(PADDING, ' ')} ${c.bold(next.minor)}` },
{ value: 'patch', title: `${'patch'.padStart(PADDING, ' ')} ${c.bold(next.patch)}` },
{ value: 'next', title: `${'next'.padStart(PADDING, ' ')} ${c.bold(next.next)}` },
{ value: 'major', title: `${'major'.padStart(PADDING, ' ')} ${bold(next.major)}` },
{ value: 'minor', title: `${'minor'.padStart(PADDING, ' ')} ${bold(next.minor)}` },
{ value: 'patch', title: `${'patch'.padStart(PADDING, ' ')} ${bold(next.patch)}` },
{ value: 'next', title: `${'next'.padStart(PADDING, ' ')} ${bold(next.next)}` },
...configCustomVersion
? [
{ value: 'config', title: `${'from config'.padStart(PADDING, ' ')} ${c.bold(configCustomVersion)}` },
{ value: 'config', title: `${'from config'.padStart(PADDING, ' ')} ${bold(configCustomVersion)}` },
]
: [],
{ value: 'prepatch', title: `${'pre-patch'.padStart(PADDING, ' ')} ${c.bold(next.prepatch)}` },
{ value: 'preminor', title: `${'pre-minor'.padStart(PADDING, ' ')} ${c.bold(next.preminor)}` },
{ value: 'premajor', title: `${'pre-major'.padStart(PADDING, ' ')} ${c.bold(next.premajor)}` },
{ value: 'none', title: `${'as-is'.padStart(PADDING, ' ')} ${c.bold(currentVersion)}` },
{ value: 'prepatch', title: `${'pre-patch'.padStart(PADDING, ' ')} ${bold(next.prepatch)}` },
{ value: 'preminor', title: `${'pre-minor'.padStart(PADDING, ' ')} ${bold(next.preminor)}` },
{ value: 'premajor', title: `${'pre-major'.padStart(PADDING, ' ')} ${bold(next.premajor)}` },
{ value: 'none', title: `${'as-is'.padStart(PADDING, ' ')} ${bold(currentVersion)}` },
{ value: 'custom', title: 'custom ...'.padStart(PADDING + 4, ' ') },
],
},
Expand Down
14 changes: 5 additions & 9 deletions packages/release-version/src/core/git.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export async function gitCommit(operation: Operation): Promise<Operation> {
}

/**
* Tags the Git commit, if the `tag` option is enabled.
* 标记 Git 提交(如果启用了tag选项)
*/
export async function gitTag(operation: Operation): Promise<Operation> {
if (!operation.options.tag)
Expand Down Expand Up @@ -85,14 +85,10 @@ export async function gitPush(operation: Operation): Promise<Operation> {
}

/**
* Accepts a version string template (e.g. "release v" or "This is the %s release").
* If the template contains any "%s" placeholders, then they are replaced with the version number;
* otherwise, the version number is appended to the string.
* 接受版本字符串模板(例如“release v”或“This is the %s release”)。
* - 如果模板包含任何“%s”占位符,则它们将替换为版本号;
* - 否则,版本号将追加到字符串
*/
export function formatVersionString(template: string, newVersion: string): string {
if (template.includes('%s'))
return template.replace(/%s/g, newVersion)

else
return template + newVersion
return template.includes('%s') ? template.replace(/%s/g, newVersion) : `${template}${newVersion}`
}
4 changes: 1 addition & 3 deletions packages/release-version/src/core/manifest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,5 @@ export function isPackageLockManifest(
*/
function isOptionalString(value: any): value is string | undefined {
const type = typeof value
return value === null
|| type === 'undefined'
|| type === 'string'
return value === null || ['undefined', 'string'].includes(type)
}
7 changes: 3 additions & 4 deletions packages/release-version/src/core/normalize-options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,28 +10,27 @@ import { isReleaseType } from './release-type'
interface Interface {
input?: NodeJS.ReadableStream | NodeJS.ReadStream | false
output?: NodeJS.WritableStream | NodeJS.WriteStream | false

[key: string]: unknown
}

/**
* A specific version release.
* 特定版本发布
*/
export interface VersionRelease {
type: 'version'
version: string
}

/**
* Prompt the user for the release number.
* 提示用户输入版本号
*/
export interface PromptRelease {
type: 'prompt'
preid: string
}

/**
* A bump release, relative to the current version number.
* 相对于当前版本号的发布版本
*/
export interface BumpRelease {
type: ReleaseType
Expand Down
1 change: 0 additions & 1 deletion packages/release-version/src/core/npm-script.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ export async function runScript(script: NpmScript, operation: Operation): Promis
operation.update({ event: ProgressEvent.NpmScript, script })
}
}

return operation
}

Expand Down
4 changes: 2 additions & 2 deletions packages/release-version/src/core/operation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,14 +92,14 @@ export class Operation {
}

/**
* Updates the operation state and results, and reports the updated progress to the user.
* 更新操作状态和结果,并将更新后的进度报告给上层
*/
public update({ event, script, ...newState }: UpdateOperationState): this {
// Update the operation state
Object.assign(this.state, newState)

// Report the progress to the user
if (event && this._progress) {
// Report the progress to the user
this._progress({ event, script, ...this.results })
}

Expand Down
10 changes: 2 additions & 8 deletions packages/release-version/src/core/version-bump.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,7 @@ import { runScript } from './npm-script'
import { updateFiles } from './update-files'

/**
* Bumps the version number in one or more files, prompting the user if necessary.
*
* use:
* - versionBump():default to new version number
* - versionBump(release: string): explicit the new version number ,e.g: 0.1.10
* - versionBump(options: VersionBumpOptions):Optionally also commits, tags, and pushes to git
* 版本发布
*/
export async function versionBump(arg: (VersionBumpOptions) | string = {}): Promise<VersionBumpResults | undefined> {
if (typeof arg === 'string')
Expand Down Expand Up @@ -64,10 +59,10 @@ export async function versionBump(arg: (VersionBumpOptions) | string = {}): Prom
console.log(e)
process.exit(1)
}

console.log(symbols.success, 'Generate CHANGELOG.md Finished')
}

// 执行命令
if (operation.options.execute) {
console.log(symbols.info, 'Executing Script', operation.options.execute)
await execShell({ command: operation.options.execute, description: '执行execute提供的命令' })
Expand Down Expand Up @@ -111,7 +106,6 @@ export async function versionBumpInfo(arg: VersionBumpOptions | string = {}): Pr
* 打印参数
*/
function printSummary(operation: Operation) {
console.log(333, operation)
console.log()
console.log(` files ${operation.options.files.map(i => bold(i)).join('\n ')}`)

Expand Down
1 change: 0 additions & 1 deletion packages/release-version/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
export * from './core/release-type'
export * from './types'
export * from './utils'
export * from './core/version-bump'
Loading

0 comments on commit fc7defc

Please sign in to comment.