aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authornetop://ウィビ <paul@webb.page>2026-10-17 16:29:19 -0700
committernetop://ウィビ <paul@webb.page>2026-10-17 16:29:19 -0700
commit14279df2e5affd44f957f5b52ad5d6267e31fa57 (patch)
treefad5858161a34a4adc163a54c334d37c0a7529a0
parent6fdfb6f5758b354861d837982ab9de76020739b2 (diff)
downloadchronver-14279df2e5affd44f957f5b52ad5d6267e31fa57.tar.gz
chronver-14279df2e5affd44f957f5b52ad5d6267e31fa57.zip
stricter parsing - v3.0.0 - fixes CLI changeset flag, padded year, debug output - updates deno.json permissionsHEADprimary
Diffstat (limited to '')
-rw-r--r--README.md33
-rwxr-xr-xcli.ts22
-rw-r--r--deno.json8
-rw-r--r--mod.ts78
-rw-r--r--test.ts127
5 files changed, 215 insertions, 53 deletions
diff --git a/README.md b/README.md
index 5711b57..c6dad42 100644
--- a/README.md
+++ b/README.md
@@ -35,6 +35,37 @@ YYYY.MM.DD[.CHANGESET][-FEATURE|-break]
+## Rules
+
+A version is a date, then an optional changeset, then at most one label: a feature or `-break`. Every valid version has exactly one spelling, so `toString()` gives back the string it was parsed from.
+
+- **Date**: `YYYY.MM.DD`, always 4 + 2 + 2 digits. The year runs from `0001` to `9999` and is zero-padded. It must be a real calendar date: `2024.02.29` is valid, but `2023.02.29` and `2024.04.31` aren't.
+- **Changeset**: `.N`, where `N` is a whole number from 1 to 9007199254740991 (`Number.MAX_SAFE_INTEGER`) with no leading zeros. Leave it out for 0, since `.0` and `.01` are rejected.
+- **Feature**: `-name`, where the name uses letters, digits and hyphens and contains at least one letter or digit (`2024.04.03--` is rejected).
+- **Breaking**: `-break`. A version is a feature or breaking, never both. `2024.04.03-ui-break` is the feature `ui-break`, and `-breaking` is a feature too.
+- Nothing follows the label, so `2024.04.03-feature.5` and `2024.04.03-break.1` are rejected. Put the changeset first: `2024.04.03.5-feature`.
+- `new ChronVer()` with no argument is today's version, but an empty string is invalid.
+
+### Ordering
+
+Versions compare by year, month, day, then changeset. When all four match, `-break` sorts after the version without it. Features are ignored, so `2024.04.03-a`, `2024.04.03-b` and `2024.04.03` are equal.
+
+```
+2024.04.03 < 2024.04.03-break < 2024.04.03.1 < 2024.04.03.1-break < 2024.04.04
+```
+
+### Incrementing
+
+`increment()` works from today's local date:
+
+- **Same day**: the changeset goes up by 1 (`2025.07.21.1` → `2025.07.21.2`).
+- **Earlier day**: today's version with no changeset (`2025.07.20.3` → `2025.07.21`).
+- **Later day**: it throws, because a version dated in the future can't be incremented.
+
+The result never keeps the feature or `-break`: `2025.07.21.1-break` becomes `2025.07.21.2` that day.
+
+
+
## Installation
### Deno
@@ -127,7 +158,7 @@ console.log(v2.isNewerThan(v1)); // true
// increment version
const incremented = version.increment();
-console.log(incremented.toString()); // "2024.07.19.1" (if same day)
+console.log(incremented.toString()); // "2025.07.21.1" (if same day)
```
### Static Methods
diff --git a/cli.ts b/cli.ts
index 24011c5..832f300 100755
--- a/cli.ts
+++ b/cli.ts
@@ -40,7 +40,7 @@ if (import.meta.main) {
}
async function main(): Promise<void> {
- const args = parseArgs(Deno.args, {
+ const args = parseArgs(preserveNegativeNumbers(Deno.args), {
alias: { h: "help", v: "version" },
boolean: ["help", "version", "create", "sort-desc"],
collect: ["compare", "sort"],
@@ -236,11 +236,7 @@ function formatFromDate(dateStr: string, changeset?: string): void {
const [, year, month, day] = match;
const date = new Date(parseInt(year), parseInt(month) - 1, parseInt(day));
- const changesetNum = changeset ? parseInt(changeset) : 0;
-
- if (isNaN(changesetNum) || changesetNum < 0)
- throw new Error("Changeset must be a non-negative number");
-
+ const changesetNum = changeset ? Number(changeset) : 0; /*** fromDate validates it ***/
const version = ChronVer.fromDate(date, changesetNum);
console.log(version.toString());
} catch(error) {
@@ -325,6 +321,16 @@ function parseVersion(version: string): void {
}
}
+/*** "-1" would otherwise parse as a flag, so move negative numbers after "--" to keep them as values ***/
+export function preserveNegativeNumbers(args: string[]): string[] {
+ const isNegativeNumber = (arg: string) => /^-\d/.test(arg);
+
+ if (args.includes("--") || !args.some(isNegativeNumber))
+ return args;
+
+ return [...args.filter(arg => !isNegativeNumber(arg)), "--", ...args.filter(isNegativeNumber)];
+}
+
function showHelp(): void {
console.log(`
__
@@ -382,8 +388,6 @@ function sortVersions(versions: string[], descending = false): void {
console.log(`📊 Sorted (${direction}):`);
- console.log(versions);
-
sorted.forEach((version, index) => {
const prefix = descending ? "🔽" : "🔼";
console.log(`${prefix} ${index + 1}. ${version}`);
@@ -401,7 +405,7 @@ function validateVersion(version: string): void {
if (isValid) {
console.log(`✅ Valid: ${version}`);
const parsed = new ChronVer(version);
- console.log(` Components: ${parsed.year}-${parsed.month.toString().padStart(2, "0")}-${parsed.day.toString().padStart(2, "0")}`);
+ console.log(` Components: ${parsed.getDateString().replaceAll(".", "-")}`);
if (parsed.changeset > 0)
console.log(` Changeset: ${parsed.changeset}`);
diff --git a/deno.json b/deno.json
index dde5eb9..9e660e1 100644
--- a/deno.json
+++ b/deno.json
@@ -8,8 +8,10 @@
"lock": false,
"name": "@chronver/chronver",
"permissions": {
- "read": true,
- "write": true
+ "default": {
+ "read": true,
+ "write": true
+ }
},
- "version": "2.1.0"
+ "version": "3.0.0"
}
diff --git a/mod.ts b/mod.ts
index 7d4e55c..7130cda 100644
--- a/mod.ts
+++ b/mod.ts
@@ -5,7 +5,8 @@
export class ChronVer {
private static readonly DATE_REGEX = /^(\d{4})\.(\d{2})\.(\d{2})$/;
- private static readonly VERSION_REGEX = /^(\d{4})\.(?:0[1-9]|1[0-2])\.(?:0[1-9]|[12]\d|3[01])(?:\.(\d+))?(?:-(break|[a-zA-Z0-9-]+)(?:\.(\d+))?)?$/;
+ private static readonly FEATURE_REGEX = /^-*[a-zA-Z0-9][a-zA-Z0-9-]*$/; /*** at least one letter or digit ***/
+ private static readonly VERSION_REGEX = /^(\d{4})\.(?:0[1-9]|1[0-2])\.(?:0[1-9]|[12]\d|3[01])(?:\.([1-9]\d*))?(?:-(break|-*[a-zA-Z0-9][a-zA-Z0-9-]*))?$/;
readonly changeset: number; /*** changeset number (0 if not specified) ***/
readonly day: number; /*** day component (1-31) ***/
@@ -15,7 +16,7 @@ export class ChronVer {
readonly year: number; /*** year component ***/
constructor(version?: string) {
- if (!version) {
+ if (version === undefined) { /*** only undefined means today, "" is invalid ***/
const now = new Date();
this.changeset = 0;
@@ -51,7 +52,7 @@ export class ChronVer {
if (!match)
throw new ChronVerError(`Invalid ChronVer format: "${version}"`);
- const [, yearStr, changesetStr, label, featureChangeset] = match;
+ const [, yearStr, changesetStr, label] = match;
const parts = version.split(".");
if (parts.length < 3)
@@ -62,21 +63,16 @@ export class ChronVer {
const day = parseInt(parts[2], 10);
const isBreaking = label === "break";
- let changeset = changesetStr ?
+ const changeset = changesetStr ?
parseInt(changesetStr, 10) :
0;
- let feature: string | undefined;
+ if (!Number.isSafeInteger(changeset))
+ throw new ChronVerError(`Changeset must be at most ${Number.MAX_SAFE_INTEGER}`);
- if (label && !isBreaking) {
- feature = label;
-
- if (!changeset) {
- changeset = featureChangeset ?
- parseInt(featureChangeset, 10) :
- 0;
- }
- }
+ const feature = label && !isBreaking ?
+ label :
+ undefined;
return {
changeset,
@@ -89,8 +85,8 @@ export class ChronVer {
}
private validate(): void {
- if (this.year < 1)
- throw new ChronVerError("Year must be positive");
+ if (this.year < 1 || this.year > 9999)
+ throw new ChronVerError("Year must be between 1 and 9999");
if (this.month < 1 || this.month > 12)
throw new ChronVerError("Month must be between 1 and 12");
@@ -100,11 +96,11 @@ export class ChronVer {
if (this.day < 1 || this.day > maxDays)
throw new ChronVerError(`Day must be between 1 and ${maxDays} for ${this.year}-${this.month.toString().padStart(2, "0")}`);
- if (this.changeset < 0)
- throw new ChronVerError("Changeset cannot be negative");
+ if (!Number.isSafeInteger(this.changeset) || this.changeset < 0)
+ throw new ChronVerError("Changeset must be a non-negative integer");
- if (this.feature && !/^[a-zA-Z0-9-]+$/.test(this.feature))
- throw new ChronVerError("Feature name must contain only alphanumeric characters and hyphens");
+ if (this.feature !== undefined && (!ChronVer.FEATURE_REGEX.test(this.feature) || this.feature === "break"))
+ throw new ChronVerError(`Feature name must contain only alphanumeric characters and hyphens (at least one alphanumeric) and cannot be "break"`);
}
//// public methods
@@ -135,20 +131,20 @@ export class ChronVer {
}
getDateString(): string {
- return `${this.year}.${this.month.toString().padStart(2, "0")}.${this.day.toString().padStart(2, "0")}`;
+ return `${this.year.toString().padStart(4, "0")}.${this.month.toString().padStart(2, "0")}.${this.day.toString().padStart(2, "0")}`;
}
increment(): ChronVer {
- const today = new Date();
+ const today = new ChronVer();
+ const dateDiff = (this.year - today.year) || (this.month - today.month) || (this.day - today.day);
- const isToday = this.year === today.getFullYear() &&
- this.month === (today.getMonth() + 1) &&
- this.day === today.getDate();
+ if (dateDiff > 0)
+ throw new ChronVerError(`Cannot increment ${this.toString()}: its date is after today (${today.getDateString()})`);
- if (isToday) /*** already ran today, increment changeset ***/
- return new ChronVer(`${this.year}.${this.month.toString().padStart(2, "0")}.${this.day.toString().padStart(2, "0")}.${this.changeset + 1}`);
+ if (dateDiff === 0) /*** already ran today, increment changeset (drops feature and -break) ***/
+ return new ChronVer(`${this.getDateString()}.${this.changeset + 1}`);
- return new ChronVer();
+ return today;
}
isNewerThan(other: ChronVer): boolean {
@@ -160,8 +156,7 @@ export class ChronVer {
}
toString(): string {
- const base = `${this.year}.${this.month.toString().padStart(2, "0")}.${this.day.toString().padStart(2, "0")}`;
- let result = base;
+ let result = this.getDateString();
if (this.changeset > 0)
result += `.${this.changeset}`;
@@ -189,7 +184,16 @@ export class ChronVer {
}
static fromDate(date: Date, changeset: number = 0): ChronVer {
- const dateStr = `${date.getFullYear()}.${(date.getMonth() + 1).toString().padStart(2, "0")}.${date.getDate().toString().padStart(2, "0")}`;
+ if (Number.isNaN(date.getTime()))
+ throw new ChronVerError("Invalid date");
+
+ if (date.getFullYear() < 1 || date.getFullYear() > 9999)
+ throw new ChronVerError("Year must be between 1 and 9999");
+
+ if (!Number.isSafeInteger(changeset) || changeset < 0)
+ throw new ChronVerError("Changeset must be a non-negative integer");
+
+ const dateStr = `${date.getFullYear().toString().padStart(4, "0")}.${(date.getMonth() + 1).toString().padStart(2, "0")}.${date.getDate().toString().padStart(2, "0")}`;
return new ChronVer(changeset > 0 ? `${dateStr}.${changeset}` : dateStr);
}
@@ -254,10 +258,14 @@ export class ChronVer {
}
static sort(versions: string[], descending: boolean = false): string[] {
- return versions.slice().sort((a, b) => {
- const result = ChronVer.compare(a, b);
- return descending ? -result : result;
- });
+ const parsed = versions.map(version => ({ version, chronVer: new ChronVer(version) })); /*** validate every input up front ***/
+
+ return parsed
+ .sort((a, b) => {
+ const result = a.chronVer.compare(b.chronVer);
+ return descending ? -result : result;
+ })
+ .map(({ version }) => version);
}
}
diff --git a/test.ts b/test.ts
index c149137..75bbced 100644
--- a/test.ts
+++ b/test.ts
@@ -10,9 +10,12 @@ import {
assertThrows
} from "@std/assert";
+import { parseArgs } from "@std/cli";
+
//// util
import { ChronVer, ChronVerError } from "./mod.ts";
+import { preserveNegativeNumbers } from "./cli.ts";
const validVersions = [
"2024.04.03",
@@ -24,7 +27,13 @@ const validVersions = [
"2024.04.03-break",
"2024.04.03.1-break",
"2024.04.03-feature-name",
- "2024.04.03-feature.5"
+ "2024.04.03-feature-break",
+ "2024.04.03-breaking",
+ "2024.04.03--ui",
+ "2024.02.29",
+ "0001.01.01",
+ "9999.12.31",
+ "2024.04.03.9007199254740991"
];
const invalidVersions = [
@@ -39,7 +48,21 @@ const invalidVersions = [
"2024.04.03.1.2",
"24.04.03",
"2024.4.03",
- "2024.04.3"
+ "2024.04.3",
+ "",
+ "0000.01.01",
+ "2023.02.29",
+ "2024.04.31",
+ "2024.04.03.0",
+ "2024.04.03.01",
+ "2024.04.03.0-break",
+ "2024.04.03-feature.5",
+ "2024.04.03.1-feature.5",
+ "2024.04.03-break.5",
+ "2024.04.03--",
+ "2024.04.03---",
+ "2024.04.03-feature_name",
+ "2024.04.03.9007199254740992"
];
@@ -77,13 +100,29 @@ Deno.test("ChronVer constructor", async(test) => {
});
await test.step("should parse feature versions with changeset", () => {
- const version = new ChronVer("2024.04.03-feature.5");
+ const version = new ChronVer("2024.04.03.5-feature");
assertEquals(version.feature, "feature");
assertEquals(version.changeset, 5);
assertEquals(version.isBreaking, false);
});
+ await test.step("should reject a changeset after the label", () => {
+ assertThrows(() => new ChronVer("2024.04.03-feature.5"), ChronVerError);
+ assertThrows(() => new ChronVer("2024.04.03-break.5"), ChronVerError);
+ });
+
+ await test.step("should treat a feature containing break as a feature", () => {
+ const version = new ChronVer("2024.04.03-feature-break");
+
+ assertEquals(version.feature, "feature-break");
+ assertEquals(version.isBreaking, false);
+ });
+
+ await test.step("should reject an empty string (only undefined means today)", () => {
+ assertThrows(() => new ChronVer(""), ChronVerError);
+ });
+
await test.step("should parse breaking versions", () => {
const version = new ChronVer("2024.04.03.1-break");
@@ -120,6 +159,20 @@ Deno.test("ChronVer validation", async(test) => {
await test.step("should validate negative changesets", () => {
assertThrows(() => new ChronVer("2024.04.03.-1"), ChronVerError);
});
+
+ await test.step("should reject an explicit 0 and leading zeros in the changeset", () => {
+ assertThrows(() => new ChronVer("2024.04.03.0"), ChronVerError);
+ assertThrows(() => new ChronVer("2024.04.03.01"), ChronVerError);
+ });
+
+ await test.step("should reject changesets above Number.MAX_SAFE_INTEGER", () => {
+ assertEquals(new ChronVer(`2024.04.03.${Number.MAX_SAFE_INTEGER}`).changeset, Number.MAX_SAFE_INTEGER);
+ assertThrows(() => new ChronVer("2024.04.03.9007199254740992"), ChronVerError);
+ });
+
+ await test.step("should reject features made only of hyphens", () => {
+ assertThrows(() => new ChronVer("2024.04.03--"), ChronVerError);
+ });
});
Deno.test("ChronVer comparison", async(test) => {
@@ -200,7 +253,7 @@ Deno.test("ChronVer string output", async(test) => {
await test.step("should format feature versions correctly", () => {
assertEquals(new ChronVer("2024.04.03-feature").toString(), "2024.04.03-feature");
- assertEquals(new ChronVer("2024.04.03-feature.5").toString(), "2024.04.03.5-feature");
+ assertEquals(new ChronVer("2024.04.03.5-feature").toString(), "2024.04.03.5-feature");
});
await test.step("should format breaking versions correctly", () => {
@@ -212,6 +265,17 @@ Deno.test("ChronVer string output", async(test) => {
assertEquals(new ChronVer("2024.01.05").toString(), "2024.01.05");
assertEquals(new ChronVer("2024.12.25").toString(), "2024.12.25");
});
+
+ await test.step("should pad the year to 4 digits", () => {
+ assertEquals(new ChronVer("0001.01.01").toString(), "0001.01.01");
+ assertEquals(new ChronVer("0999.12.31").getDateString(), "0999.12.31");
+ });
+
+ await test.step("should return the parsed string for every valid version", () => {
+ for (const valid of validVersions) {
+ assertEquals(new ChronVer(valid).toString(), valid);
+ }
+ });
});
Deno.test("ChronVer increment", async(test) => {
@@ -232,6 +296,18 @@ Deno.test("ChronVer increment", async(test) => {
assertEquals(incremented.toString(), expectedDate);
});
+
+ await test.step("should drop the feature and -break on the same day", () => {
+ const today = new Date();
+ const todayStr = `${today.getFullYear()}.${(today.getMonth() + 1).toString().padStart(2, "0")}.${today.getDate().toString().padStart(2, "0")}`;
+
+ assertEquals(new ChronVer(todayStr + ".1-break").increment().toString(), todayStr + ".2");
+ assertEquals(new ChronVer(todayStr + "-feature").increment().toString(), todayStr + ".1");
+ });
+
+ await test.step("should throw when the version's date is after today", () => {
+ assertThrows(() => new ChronVer("9999.12.31").increment(), ChronVerError, "is after today");
+ });
});
Deno.test("ChronVer static methods", async(test) => {
@@ -247,7 +323,7 @@ Deno.test("ChronVer static methods", async(test) => {
}
for (const invalid of invalidVersions) {
- assertFalse(ChronVer.isValid(invalid));
+ assertFalse(ChronVer.isValid(invalid), invalid);
}
});
@@ -275,6 +351,29 @@ Deno.test("ChronVer static methods", async(test) => {
assertEquals(version.changeset, 5);
});
+ await test.step(`"fromDate" should pad the year`, () => {
+ const date = new Date(2024, 0, 1);
+ date.setFullYear(999);
+
+ assertEquals(ChronVer.fromDate(date).toString(), "0999.01.01");
+ });
+
+ await test.step(`"fromDate" should throw on a negative or non-integer changeset`, () => {
+ const date = new Date(2024, 3, 3);
+
+ assertThrows(() => ChronVer.fromDate(date, -1), ChronVerError);
+ assertThrows(() => ChronVer.fromDate(date, 1.5), ChronVerError);
+ assertThrows(() => ChronVer.fromDate(date, NaN), ChronVerError);
+ });
+
+ await test.step(`"fromDate" should throw on a year outside 1 to 9999 or an invalid date`, () => {
+ const date = new Date(2024, 0, 1);
+ date.setFullYear(10000);
+
+ assertThrows(() => ChronVer.fromDate(date), ChronVerError);
+ assertThrows(() => ChronVer.fromDate(new Date(NaN)), ChronVerError);
+ });
+
await test.step(`"sort" should order versions correctly`, () => {
const versions = [
"2024.04.05",
@@ -301,6 +400,11 @@ Deno.test("ChronVer static methods", async(test) => {
"2024.04.03"
]);
});
+
+ await test.step(`"sort" should validate every input up front`, () => {
+ assertThrows(() => ChronVer.sort(["invalid"]), ChronVerError);
+ assertThrows(() => ChronVer.sort(["2024.04.03", "2024.04.04", "invalid"]), ChronVerError);
+ });
});
Deno.test("ChronVer file operations", async(test) => {
@@ -350,6 +454,7 @@ Deno.test("ChronVer edge cases", async(test) => {
assertEquals(version.year, 1);
assertThrows(() => new ChronVer("0000.01.01"), ChronVerError);
+ assertEquals(new ChronVer("9999.12.31").year, 9999);
});
await test.step("should handle complex feature names", () => {
@@ -366,3 +471,15 @@ Deno.test("ChronVer edge cases", async(test) => {
assertThrows(() => ChronVer.compare("invalid", "2024.04.03"), ChronVerError);
});
});
+
+Deno.test("CLI argument handling", async(test) => {
+ await test.step("should keep a negative changeset as a value, not a flag", () => {
+ assertEquals(parseArgs(preserveNegativeNumbers(["format", "2024-04-03", "-1"]))._, ["format", "2024-04-03", "-1"]);
+ assertEquals(parseArgs(preserveNegativeNumbers(["--format", "2024-04-03", "-1"]), { string: ["format"] })._, ["-1"]);
+ });
+
+ await test.step("should leave arguments without negative numbers alone", () => {
+ const args = ["format", "2024-04-03", "5", "--sort-desc"];
+ assertEquals(preserveNegativeNumbers(args), args);
+ });
+});