From f8af0dbdcd8299b9df415a9bcaa8bd1f6bc0b13f Mon Sep 17 00:00:00 2001 From: fulin <83196518+xufulin1994@users.noreply.github.com> Date: Mon, 1 Apr 2024 16:11:04 +0800 Subject: [PATCH] Semver version (#272) * semver version * add test --- src/grammar/base.pegjs | 5 +++- src/tests/semver.test.ts | 50 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 src/tests/semver.test.ts diff --git a/src/grammar/base.pegjs b/src/grammar/base.pegjs index 20b787b..7be3caf 100644 --- a/src/grammar/base.pegjs +++ b/src/grammar/base.pegjs @@ -35,7 +35,10 @@ description = "\"" _ inner:(!"\"" i:. {return i})* "\"" { } // version -semver = semver:([0-9]+ "." [0-9]+ "." [0-9]+ ("-" [a-zA-Z0-9.-]+)?) { return semver.flat(2).join(""); } +semver = semver:([0-9]+ "." [0-9]+ "." [0-9]+ preRelease) { return semver.flat(Infinity).join(""); } +preRelease = ('-' preReleaseIdentifiers)?; +preReleaseIdentifiers = identifier ('.' [0-9a-zA-Z-]+)*; +identifier = [a-zA-Z-] ([a-zA-Z-] / [0-9])*; // whitespace or comment _ = ([ \t\r\n]+ / comment)* diff --git a/src/tests/semver.test.ts b/src/tests/semver.test.ts new file mode 100644 index 0000000..98fd770 --- /dev/null +++ b/src/tests/semver.test.ts @@ -0,0 +1,50 @@ +import {readFile} from "../parse"; +import peg from "pegjs"; +import * as path from "path"; + +const grammar = readFile(path.resolve(__dirname, '..'), "grammar", "base.pegjs") + +const parser = peg.generate(grammar, {allowedStartRules: ["semver"]}); + + +describe("semver", () => { + it("should parse a semantic version with a pre-release identifier", () => { + const input_1 = "1.2.3-alpha"; + const expected_1 = "1.2.3-alpha"; + + const input_2 = "1.0.0-alpha.beta"; + const expected_2 = "1.0.0-alpha.beta"; + + const input_3 = "1.2.3----RC-SNAPSHOT.12.9.1--.12"; + const expected_3 = "1.2.3----RC-SNAPSHOT.12.9.1--.12"; + // Parse the input string + const result_1 = parser.parse(input_1); + const result_2 = parser.parse(input_2); + const result_3 = parser.parse(input_3); + + // Check the result + expect(result_1).toBe(expected_1); + expect(result_2).toBe(expected_2); + expect(result_3).toBe(expected_3); + }); + + it("should parse a semantic version with no pre-release identifier", () => { + const input = "1.2.3"; + const expected = "1.2.3"; + + // Parse the input string + const result = parser.parse(input); + + // Check the result + expect(result).toBe(expected); + }); + + it("parse a invalid semantic version throw error", () => { + const input_1 = "1.2.3-0123"; + const input_2 = "alpha_beta"; + + // Parsing an invalid semantic version should throw an error + expect(() => parser.parse(input_1)).toThrow(); + expect(() => parser.parse(input_2)).toThrow(); + }); +});