Skip to content

Commit a1f230c

Browse files
committed
fix(version): 改进版本号解析的输入验证和错误处理
1 parent 7f2c8ef commit a1f230c

1 file changed

Lines changed: 13 additions & 7 deletions

File tree

packages/utils-core/src/version.ts

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { isInteger, isNumerical } from './regexp';
12
import { isUndefined } from './type';
23

34
/**
@@ -20,11 +21,16 @@ export type VersionObject = {
2021

2122
/**
2223
* 将数字转换为安全的数值,如果输入为NaN则返回0
23-
* @param n - 要转换的数字
24+
* @param pos - 位置描述,用于错误提示
25+
* @param str - 要转换的数字字符串
2426
* @returns 安全的数字(如果输入为NaN则返回0)
2527
*/
26-
function internal_numerical(n?: number) {
27-
return Number.isNaN(n) || isUndefined(n) ? 0 : n;
28+
function internal_numerical(pos: string, str?: string) {
29+
if (isUndefined(str)) throw new Error(`${pos}不存在`);
30+
if (!isInteger(str)) throw new Error(`${pos}不是整数`);
31+
const num = Number(str);
32+
if (num < 0) throw new Error(`${pos}不是正整数`);
33+
return num;
2834
}
2935

3036
/**
@@ -34,11 +40,11 @@ function internal_numerical(n?: number) {
3440
* @throws 如果版本号字符串格式无效将抛出错误
3541
*/
3642
export function versionParse(version: string): VersionObject {
37-
const [major, minor, patch] = version.split('.').map(Number);
43+
const [major, minor, patch] = version.split('.');
3844
return {
39-
major: internal_numerical(major),
40-
minor: internal_numerical(minor),
41-
patch: internal_numerical(patch),
45+
major: internal_numerical('主版本号', major),
46+
minor: internal_numerical('次版本号', minor),
47+
patch: internal_numerical('修订号', patch),
4248
};
4349
}
4450

0 commit comments

Comments
 (0)