跳转到内容

std.SemanticVersion

标准库Zig 0.17.1官方原文
源码std/SemanticVersion.zig

第 1 行

按照语义化版本 2.0.0 规范格式化的软件版本。

参见:https://semver.org

字段

major: usize
minor: usize
patch: usize
pre: ?[]const u8 = null
build: ?[]const u8 = null

std.SemanticVersion.expect

别名

第 159 行

别名目标 std.testing.expect

std.SemanticVersion.expectError

别名

第 160 行

别名目标 std.testing.expectError

std.SemanticVersion.format

函数

第 153 行

pub fn format(self: Version, w: *std.Io.Writer) std.Io.Writer.Error!void

参数

self: Version
w: *std.Io.Writer

错误

WriteFailed

详细诊断信息见 Writer 实现。

用法示例

test format {
    // 其中许多测试字符串来自 https://github.com/semver/semver.org/issues/59#issuecomment-390854010。

    // 应接受有效的版本字符串。
    for ([_][]const u8{
        "0.0.4",
        "1.2.3",
        "10.20.30",
        "1.1.2-prerelease+meta",
        "1.1.2+meta",
        "1.1.2+meta-valid",
        "1.0.0-alpha",
        "1.0.0-beta",
        "1.0.0-alpha.beta",
        "1.0.0-alpha.beta.1",
        "1.0.0-alpha.1",
        "1.0.0-alpha0.valid",
        "1.0.0-alpha.0valid",
        "1.0.0-alpha-a.b-c-somethinglong+build.1-aef.1-its-okay",
        "1.0.0-rc.1+build.1",
        "2.0.0-rc.1+build.123",
        "1.2.3-beta",
        "10.2.3-DEV-SNAPSHOT",
        "1.2.3-SNAPSHOT-123",
        "1.0.0",
        "2.0.0",
        "1.1.7",
        "2.0.0+build.1848",
        "2.0.1-alpha.1227",
        "1.0.0-alpha+beta",
        "1.2.3----RC-SNAPSHOT.12.9.1--.12+788",
        "1.2.3----R-S.12.9.1--.12+meta",
        "1.2.3----RC-SNAPSHOT.12.9.1--.12",
        "1.0.0+0.build.1-rc.10000aaa-kk-0.1",
        "5.4.0-1018-raspi",
        "5.7.123",
    }) |valid| try std.testing.expectFmt(valid, "{f}", .{try parse(valid)});

    // 应拒绝无效的版本字符串。
    for ([_][]const u8{
        "",
        "1",
        "1.2",
        "1.2.3-0123",
        "1.2.3-0123.0123",
        "1.1.2+.123",
        "+invalid",
        "-invalid",
        "-invalid+invalid",
        "-invalid.01",
        "alpha",
        "alpha.beta",
        "alpha.beta.1",
        "alpha.1",
        "alpha+beta",
        "alpha_beta",
        "alpha.",
        "alpha..",
        "beta\\",
        "1.0.0-alpha_beta",
        "-alpha.",
        "1.0.0-alpha..",
        "1.0.0-alpha..1",
        "1.0.0-alpha...1",
        "1.0.0-alpha....1",
        "1.0.0-alpha.....1",
        "1.0.0-alpha......1",
        "1.0.0-alpha.......1",
        "01.1.1",
        "1.01.1",
        "1.1.01",
        "1.2",
        "1.2.3.DEV",
        "1.2-SNAPSHOT",
        "1.2.31.2.3----RC-SNAPSHOT.12.09.1--..12+788",
        "1.2-RC-SNAPSHOT",
        "-1.0.3-gamma+b7718",
        "+justmeta",
        "9.8.7+meta+meta",
        "9.8.7-whatever+meta+meta",
        "2.6.32.11-svn21605",
        "2.11.2(0.329/5/3)",
        "2.13-DEVELOPMENT",
        "2.3-35",
        "1a.4",
        "3.b1.0",
        "1.4beta",
        "2.7.pre",
        "0..3",
        "8.008.",
        "01...",
        "55",
        "foobar",
        "",
        "-1",
        "+4",
        ".",
        "....3",
    }) |invalid| try expectError(error.InvalidVersion, parse(invalid));

    // 有效但可能溢出的版本字符串。
    const big_valid = "99999999999999999999999.999999999999999999.99999999999999999";
    if (parse(big_valid)) |ver| {
        try std.testing.expectFmt(big_valid, "{f}", .{ver});
    } else |err| try expect(err == error.Overflow);

    // 无效且可能溢出的版本字符串。
    const big_invalid = "99999999999999999999999.999999999999999999.99999999999999999----RC-SNAPSHOT.12.09.1--------------------------------..12";
    if (parse(big_invalid)) |ver| std.debug.panic("expected error, found {f}", .{ver}) else |_| {}
}

std.SemanticVersion.order

函数

第 33 行

pub fn order(lhs: Version, rhs: Version) std.math.Order

参数

lhs: Version
rhs: Version

std.SemanticVersion.parse

函数

第 85 行

pub fn parse(text: []const u8) !Version

参数

text: []const u8

std.SemanticVersion.parseNum

函数

第 143 行

fn parseNum(text: []const u8) error{ InvalidVersion, Overflow }!usize

参数

text: []const u8

错误

InvalidVersion
Overflow

std.SemanticVersion.Range

容器

第 14 行

字段

min: Version
max: Version

std.SemanticVersion.Range.includesVersion

函数

第 18 行

pub fn includesVersion(self: Range, ver: Version) bool

参数

self: Range
ver: Version

std.SemanticVersion.Range.isAtLeast

函数

第 26 行

检查系统是否保证至少为 version,或早于 version。 若需要运行期检查,则返回 null。

pub fn isAtLeast(self: Range, ver: Version) ?bool

参数

self: Range
ver: Version

std.SemanticVersion.std

别名

第 5 行

别名目标 std

std.SemanticVersion.Version

别名

第 6 行

别名目标 std.SemanticVersion

源码

std/SemanticVersion.zig

//! 按照语义化版本 2.0.0 规范格式化的软件版本。
//!
//! 参见:https://semver.org

const std = @import("std");
const Version = @This();

major: usize,
minor: usize,
patch: usize,
pre: ?[]const u8 = null,
build: ?[]const u8 = null,

pub const Range = struct {
    min: Version,
    max: Version,

    pub fn includesVersion(self: Range, ver: Version) bool {
        if (self.min.order(ver) == .gt) return false;
        if (self.max.order(ver) == .lt) return false;
        return true;
    }

    /// 检查系统是否保证至少为 `version`,或早于 `version`。
    /// 若需要运行期检查,则返回 `null`。
    pub fn isAtLeast(self: Range, ver: Version) ?bool {
        if (self.min.order(ver) != .lt) return true;
        if (self.max.order(ver) == .lt) return false;
        return null;
    }
};

pub fn order(lhs: Version, rhs: Version) std.math.Order {
    if (lhs.major < rhs.major) return .lt;
    if (lhs.major > rhs.major) return .gt;
    if (lhs.minor < rhs.minor) return .lt;
    if (lhs.minor > rhs.minor) return .gt;
    if (lhs.patch < rhs.patch) return .lt;
    if (lhs.patch > rhs.patch) return .gt;
    if (lhs.pre != null and rhs.pre == null) return .lt;
    if (lhs.pre == null and rhs.pre == null) return .eq;
    if (lhs.pre == null and rhs.pre != null) return .gt;

    // 遍历预发布标识符,直到找到差异。
    var lhs_pre_it = std.mem.splitScalar(u8, lhs.pre.?, '.');
    var rhs_pre_it = std.mem.splitScalar(u8, rhs.pre.?, '.');
    while (true) {
        const next_lid = lhs_pre_it.next();
        const next_rid = rhs_pre_it.next();

        // 预发布字段集合较大时,其优先级高于较小的集合。
        if (next_lid == null and next_rid != null) return .lt;
        if (next_lid == null and next_rid == null) return .eq;
        if (next_lid != null and next_rid == null) return .gt;

        const lid = next_lid.?; // 左侧标识符
        const rid = next_rid.?; // 右侧标识符

        // 尝试将标识符解析为数字。溢出由解析过程检查。
        const lnum: ?usize = std.fmt.parseUnsigned(usize, lid, 10) catch |err| switch (err) {
            error.InvalidCharacter => null,
            error.Overflow => unreachable,
        };
        const rnum: ?usize = std.fmt.parseUnsigned(usize, rid, 10) catch |err| switch (err) {
            error.InvalidCharacter => null,
            error.Overflow => unreachable,
        };

        // 数字标识符的优先级始终低于非数字标识符。
        if (lnum != null and rnum == null) return .lt;
        if (lnum == null and rnum != null) return .gt;

        // 仅由数字组成的标识符按数值比较。
        // 包含字母或连字符的标识符按 ASCII 顺序进行字典序比较。
        if (lnum != null and rnum != null) {
            if (lnum.? < rnum.?) return .lt;
            if (lnum.? > rnum.?) return .gt;
        } else {
            const ord = std.mem.order(u8, lid, rid);
            if (ord != .eq) return ord;
        }
    }
}

pub fn parse(text: []const u8) !Version {
    // 解析必需的主版本号、次版本号及补丁版本号。
    const extra_index = std.mem.findAny(u8, text, "-+");
    const required = text[0..(extra_index orelse text.len)];
    var it = std.mem.splitScalar(u8, required, '.');
    var ver = Version{
        .major = try parseNum(it.first()),
        .minor = try parseNum(it.next() orelse return error.InvalidVersion),
        .patch = try parseNum(it.next() orelse return error.InvalidVersion),
    };
    if (it.next() != null) return error.InvalidVersion;
    if (extra_index == null) return ver;

    // 切取可选的预发布或构建元数据分量。
    const extra: []const u8 = text[extra_index.?..text.len];
    if (extra[0] == '-') {
        const build_index = std.mem.findScalar(u8, extra, '+');
        ver.pre = extra[1..(build_index orelse extra.len)];
        if (build_index) |idx| ver.build = extra[(idx + 1)..];
    } else {
        ver.build = extra[1..];
    }

    // 检查可选预发布标识符的有效性。
    // 参见:https://semver.org/#spec-item-9
    if (ver.pre) |pre| {
        it = std.mem.splitScalar(u8, pre, '.');
        while (it.next()) |id| {
            // 标识符不得为空。
            if (id.len == 0) return error.InvalidVersion;

            // 标识符必须仅由 ASCII 字母、数字和连字符 [0-9A-Za-z-] 组成。
            for (id) |c| if (!std.ascii.isAlphanumeric(c) and c != '-') return error.InvalidVersion;

            // 数字标识符不得包含前导零。
            const is_num = for (id) |c| {
                if (!std.ascii.isDigit(c)) break false;
            } else true;
            if (is_num) _ = try parseNum(id);
        }
    }

    // 检查可选构建元数据标识符的有效性。
    // 参见:https://semver.org/#spec-item-10
    if (ver.build) |build| {
        it = std.mem.splitScalar(u8, build, '.');
        while (it.next()) |id| {
            // 标识符不得为空。
            if (id.len == 0) return error.InvalidVersion;

            // 标识符必须仅由 ASCII 字母、数字和连字符 [0-9A-Za-z-] 组成。
            for (id) |c| if (!std.ascii.isAlphanumeric(c) and c != '-') return error.InvalidVersion;
        }
    }

    return ver;
}

fn parseNum(text: []const u8) error{ InvalidVersion, Overflow }!usize {
    // 不允许前导零。
    if (text.len > 1 and text[0] == '0') return error.InvalidVersion;

    return std.fmt.parseUnsigned(usize, text, 10) catch |err| switch (err) {
        error.InvalidCharacter => return error.InvalidVersion,
        error.Overflow => |e| return e,
    };
}

pub fn format(self: Version, w: *std.Io.Writer) std.Io.Writer.Error!void {
    try w.print("{d}.{d}.{d}", .{ self.major, self.minor, self.patch });
    if (self.pre) |pre| try w.print("-{s}", .{pre});
    if (self.build) |build| try w.print("+{s}", .{build});
}

const expect = std.testing.expect;
const expectError = std.testing.expectError;

test format {
    // 其中许多测试字符串来自 https://github.com/semver/semver.org/issues/59#issuecomment-390854010。

    // 应接受有效的版本字符串。
    for ([_][]const u8{
        "0.0.4",
        "1.2.3",
        "10.20.30",
        "1.1.2-prerelease+meta",
        "1.1.2+meta",
        "1.1.2+meta-valid",
        "1.0.0-alpha",
        "1.0.0-beta",
        "1.0.0-alpha.beta",
        "1.0.0-alpha.beta.1",
        "1.0.0-alpha.1",
        "1.0.0-alpha0.valid",
        "1.0.0-alpha.0valid",
        "1.0.0-alpha-a.b-c-somethinglong+build.1-aef.1-its-okay",
        "1.0.0-rc.1+build.1",
        "2.0.0-rc.1+build.123",
        "1.2.3-beta",
        "10.2.3-DEV-SNAPSHOT",
        "1.2.3-SNAPSHOT-123",
        "1.0.0",
        "2.0.0",
        "1.1.7",
        "2.0.0+build.1848",
        "2.0.1-alpha.1227",
        "1.0.0-alpha+beta",
        "1.2.3----RC-SNAPSHOT.12.9.1--.12+788",
        "1.2.3----R-S.12.9.1--.12+meta",
        "1.2.3----RC-SNAPSHOT.12.9.1--.12",
        "1.0.0+0.build.1-rc.10000aaa-kk-0.1",
        "5.4.0-1018-raspi",
        "5.7.123",
    }) |valid| try std.testing.expectFmt(valid, "{f}", .{try parse(valid)});

    // 应拒绝无效的版本字符串。
    for ([_][]const u8{
        "",
        "1",
        "1.2",
        "1.2.3-0123",
        "1.2.3-0123.0123",
        "1.1.2+.123",
        "+invalid",
        "-invalid",
        "-invalid+invalid",
        "-invalid.01",
        "alpha",
        "alpha.beta",
        "alpha.beta.1",
        "alpha.1",
        "alpha+beta",
        "alpha_beta",
        "alpha.",
        "alpha..",
        "beta\\",
        "1.0.0-alpha_beta",
        "-alpha.",
        "1.0.0-alpha..",
        "1.0.0-alpha..1",
        "1.0.0-alpha...1",
        "1.0.0-alpha....1",
        "1.0.0-alpha.....1",
        "1.0.0-alpha......1",
        "1.0.0-alpha.......1",
        "01.1.1",
        "1.01.1",
        "1.1.01",
        "1.2",
        "1.2.3.DEV",
        "1.2-SNAPSHOT",
        "1.2.31.2.3----RC-SNAPSHOT.12.09.1--..12+788",
        "1.2-RC-SNAPSHOT",
        "-1.0.3-gamma+b7718",
        "+justmeta",
        "9.8.7+meta+meta",
        "9.8.7-whatever+meta+meta",
        "2.6.32.11-svn21605",
        "2.11.2(0.329/5/3)",
        "2.13-DEVELOPMENT",
        "2.3-35",
        "1a.4",
        "3.b1.0",
        "1.4beta",
        "2.7.pre",
        "0..3",
        "8.008.",
        "01...",
        "55",
        "foobar",
        "",
        "-1",
        "+4",
        ".",
        "....3",
    }) |invalid| try expectError(error.InvalidVersion, parse(invalid));

    // 有效但可能溢出的版本字符串。
    const big_valid = "99999999999999999999999.999999999999999999.99999999999999999";
    if (parse(big_valid)) |ver| {
        try std.testing.expectFmt(big_valid, "{f}", .{ver});
    } else |err| try expect(err == error.Overflow);

    // 无效且可能溢出的版本字符串。
    const big_invalid = "99999999999999999999999.999999999999999999.99999999999999999----RC-SNAPSHOT.12.09.1--------------------------------..12";
    if (parse(big_invalid)) |ver| std.debug.panic("expected error, found {f}", .{ver}) else |_| {}
}

test "precedence" {
    // SemVer 2 规范 11.2 的示例:1.0.0 < 2.0.0 < 2.1.0 < 2.1.1。
    try expect(order(try parse("1.0.0"), try parse("2.0.0")) == .lt);
    try expect(order(try parse("2.0.0"), try parse("2.1.0")) == .lt);
    try expect(order(try parse("2.1.0"), try parse("2.1.1")) == .lt);

    // SemVer 2 规范 11.3 的示例:1.0.0-alpha < 1.0.0。
    try expect(order(try parse("1.0.0-alpha"), try parse("1.0.0")) == .lt);

    // SemVer 2 规范 11.4 的示例:1.0.0-alpha < 1.0.0-alpha.1 < 1.0.0-alpha.beta < 1.0.0-beta <
    // 1.0.0-beta.2 < 1.0.0-beta.11 < 1.0.0-rc.1 < 1.0.0。
    try expect(order(try parse("1.0.0-alpha"), try parse("1.0.0-alpha.1")) == .lt);
    try expect(order(try parse("1.0.0-alpha.1"), try parse("1.0.0-alpha.beta")) == .lt);
    try expect(order(try parse("1.0.0-alpha.beta"), try parse("1.0.0-beta")) == .lt);
    try expect(order(try parse("1.0.0-beta"), try parse("1.0.0-beta.2")) == .lt);
    try expect(order(try parse("1.0.0-beta.2"), try parse("1.0.0-beta.11")) == .lt);
    try expect(order(try parse("1.0.0-beta.11"), try parse("1.0.0-rc.1")) == .lt);
    try expect(order(try parse("1.0.0-rc.1"), try parse("1.0.0")) == .lt);
}

test "zig_version" {
    // 早于此测试的大致 Zig 构建版本。
    const older_version: Version = .{ .major = 0, .minor = 8, .patch = 0, .pre = "dev.874" };

    // 使用 Zig 版本模拟兼容性检查。
    const compatible = comptime @import("builtin").zig_version.order(older_version) == .gt;
    if (!compatible) @compileError("zig_version test failed");
}