From 61f80fbf83d18dc9868afaa67501492573deff39 Mon Sep 17 00:00:00 2001 From: Erica Marigold Date: Thu, 21 Nov 2024 17:20:48 +0000 Subject: [PATCH] feat: implement tostring for `SemverImpl` * `SemverImpl:__tostring` - Allows for stringifying a parsed semver instance * Add TODO comment for future erroring for bad ordinal format --- lib/init.luau | 22 ++++++++++++++++++++++ tests/tostring.luau | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 tests/tostring.luau diff --git a/lib/init.luau b/lib/init.luau index 511a881..5339d2b 100644 --- a/lib/init.luau +++ b/lib/init.luau @@ -296,6 +296,8 @@ function Semver.parse(ver: string): SemverResult local potentialOrdinalNumber, potentialBuildMetadata = string.match(components[4], "(%d)+(.*)") if potentialOrdinalNumber == nil then return badPrereleaseType(components[4]) + -- TODO: If there are components after the 4th index, we + -- should error end if potentialBuildMetadata ~= nil then @@ -395,4 +397,24 @@ function Semver.__le(left: SemverImpl, right: SemverImpl): boolean else prereleaseLe(left.prerelease:unwrapOrNil(), right.prerelease:unwrapOrNil()) end +function Semver.__tostring(self: SemverImpl): string + local base = `{self.major}.{self.minor}.{self.patch}` + local prerelease = self.prerelease + :map(function(prerelease: PrereleaseVersion) + return `-{prerelease.type}{prerelease.ordinal + :map(function(ord: number) + return `.{ord}` + end) + :unwrapOr("")}` + end) + :unwrapOr("") + local build = self.buildMetadata + :map(function(buildMetadata: string) + return `+{buildMetadata}` + end) + :unwrapOr("") + + return base .. prerelease .. build +end + return Semver diff --git a/tests/tostring.luau b/tests/tostring.luau new file mode 100644 index 0000000..1ee058b --- /dev/null +++ b/tests/tostring.luau @@ -0,0 +1,33 @@ +local frktest = require("@pkg/frktest") +local test = frktest.test +local check = frktest.assert.check + +local Option = require("../luau_packages/option") +type Option = Option.Option + +local Semver = require("../lib") + +return function() + test.suite("Stringification tests", function() + test.case("A parsed version when stringified should not change", function() + local versions = { + "1.2.3", + "1.0.0-alpha", + "2.3.4-beta.1", + "3.0.0-rc.1+build.123", + "4.5.6+sha.xyz", + "5.0.0-alpha.1+build.999", + "6.7.8-beta.2+exp.sha.5114f85", + "7.0.0-alpha.1", + "9.9.9+20230615", + } + + for _, version in versions do + local parsed = Semver.parse(version):unwrap() + local stringified = tostring(parsed) + + check.equal(stringified, version) + end + end) + end) +end