From e57148332bb634c342412756db428b9a5b658387 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matheus=20Catarino=20Fran=C3=A7a?= Date: Thu, 28 Mar 2024 12:49:50 -0300 Subject: [PATCH] fix: https://github.com/kassane/zig-esp-idf-sample/issues/7 --- imports/version.zig | 47 +++++++++++++++++++++++---------------------- 1 file changed, 24 insertions(+), 23 deletions(-) diff --git a/imports/version.zig b/imports/version.zig index a6e3c56..0f28071 100644 --- a/imports/version.zig +++ b/imports/version.zig @@ -1,38 +1,35 @@ +const std = @import("std"); + pub const Version = struct { major: ?u32 = null, minor: ?u32 = null, patch: ?u32 = null, pub fn get() Version { - var final_version: Version = .{ - .major = 0, - .minor = 0, - .patch = 0, - }; + var final_version: Version = .{}; const idf_version = std.mem.span(@import("sys").esp_get_idf_version()); if (!std.mem.startsWith(u8, idf_version, "v")) return final_version; - // skip [0] == 'v' and remove [idf_version.len - 4] == "-dev" - var it = if (std.mem.endsWith(u8, idf_version, "-dev")) - std.mem.split(u8, idf_version[1 .. idf_version.len - 4], ".") - else - std.mem.split(u8, idf_version[1..], "."); - - final_version.major = std.fmt.parseUnsigned(u32, it.first(), 10) catch |err| - @panic(@errorName(err)); + var strip = std.mem.split(u8, idf_version, "-"); + var it = std.mem.tokenize(u8, strip.first(), "."); while (it.next()) |token| { - if (!std.ascii.isDigit(token[0])) - continue; - const digit = std.fmt.parseUnsigned(u32, token, 10) catch |err| - @panic(@errorName(err)); - if (digit != final_version.minor and final_version.minor == 0) { + // skip [0] == 'v' + const digit = if (std.mem.startsWith(u8, token, "v")) + std.fmt.parseUnsigned(u32, token[1..], 10) catch |err| + @panic(@errorName(err)) + else + std.fmt.parseUnsigned(u32, token, 10) catch |err| + @panic(@errorName(err)); + + if (final_version.major == null) { + final_version.major = digit; + } else if (final_version.minor == null) { final_version.minor = digit; - continue; - } - if (digit != final_version.patch) + } else if (final_version.patch == null) { final_version.patch = digit; + } } return final_version; @@ -44,12 +41,16 @@ pub const Version = struct { if (!std.mem.startsWith(u8, idf_version, "v")) return idf_version else - return std.fmt.allocPrint(allocator, "{d}.{d}.{d}", .{ + return std.fmt.allocPrint(allocator, "v{d}.{d}.{d}", .{ self.major.?, self.minor.?, self.patch.?, }) catch |err| @panic(@errorName(err)); } - const std = @import("std"); }; + +test "Valid version" { + const testing = std.testing; + try testing.expectEqual(Version.get().toString(testing.allocator), "v5.1.3"); +}