Skip to content

Commit f8af0db

Browse files
authored
Semver version (#272)
* semver version * add test
1 parent 7e98d1f commit f8af0db

File tree

2 files changed

+54
-1
lines changed

2 files changed

+54
-1
lines changed

src/grammar/base.pegjs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,10 @@ description = "\"" _ inner:(!"\"" i:. {return i})* "\"" {
3535
}
3636

3737
// version
38-
semver = semver:([0-9]+ "." [0-9]+ "." [0-9]+ ("-" [a-zA-Z0-9.-]+)?) { return semver.flat(2).join(""); }
38+
semver = semver:([0-9]+ "." [0-9]+ "." [0-9]+ preRelease) { return semver.flat(Infinity).join(""); }
39+
preRelease = ('-' preReleaseIdentifiers)?;
40+
preReleaseIdentifiers = identifier ('.' [0-9a-zA-Z-]+)*;
41+
identifier = [a-zA-Z-] ([a-zA-Z-] / [0-9])*;
3942

4043
// whitespace or comment
4144
_ = ([ \t\r\n]+ / comment)*

src/tests/semver.test.ts

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import {readFile} from "../parse";
2+
import peg from "pegjs";
3+
import * as path from "path";
4+
5+
const grammar = readFile(path.resolve(__dirname, '..'), "grammar", "base.pegjs")
6+
7+
const parser = peg.generate(grammar, {allowedStartRules: ["semver"]});
8+
9+
10+
describe("semver", () => {
11+
it("should parse a semantic version with a pre-release identifier", () => {
12+
const input_1 = "1.2.3-alpha";
13+
const expected_1 = "1.2.3-alpha";
14+
15+
const input_2 = "1.0.0-alpha.beta";
16+
const expected_2 = "1.0.0-alpha.beta";
17+
18+
const input_3 = "1.2.3----RC-SNAPSHOT.12.9.1--.12";
19+
const expected_3 = "1.2.3----RC-SNAPSHOT.12.9.1--.12";
20+
// Parse the input string
21+
const result_1 = parser.parse(input_1);
22+
const result_2 = parser.parse(input_2);
23+
const result_3 = parser.parse(input_3);
24+
25+
// Check the result
26+
expect(result_1).toBe(expected_1);
27+
expect(result_2).toBe(expected_2);
28+
expect(result_3).toBe(expected_3);
29+
});
30+
31+
it("should parse a semantic version with no pre-release identifier", () => {
32+
const input = "1.2.3";
33+
const expected = "1.2.3";
34+
35+
// Parse the input string
36+
const result = parser.parse(input);
37+
38+
// Check the result
39+
expect(result).toBe(expected);
40+
});
41+
42+
it("parse a invalid semantic version throw error", () => {
43+
const input_1 = "1.2.3-0123";
44+
const input_2 = "alpha_beta";
45+
46+
// Parsing an invalid semantic version should throw an error
47+
expect(() => parser.parse(input_1)).toThrow();
48+
expect(() => parser.parse(input_2)).toThrow();
49+
});
50+
});

0 commit comments

Comments
 (0)