Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 23 additions & 9 deletions src/runtime/cli/pm_version_command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -321,13 +321,22 @@ impl PmVersionCommand {
Ok(())
}

/// `npm version` refuses a major, minor or patch above Number.MAX_SAFE_INTEGER. Below that
/// limit, `+ 1` cannot wrap.
/// https://github.com/npm/node-semver/blob/v7.7.2/classes/semver.js#L50-L60
Comment thread
robobun marked this conversation as resolved.
Resolved
fn is_valid_version(result: &Semver::version::ParseResult<u64>) -> bool {
const MAX_SAFE_INTEGER: u64 = (1 << 53) - 1;
let version = result.version.min();
result.valid && version.major.max(version.minor).max(version.patch) <= MAX_SAFE_INTEGER
}

fn parse_version_argument(arg: &[u8]) -> (VersionType, Option<&[u8]>) {
if let Some(vtype) = VersionType::from_string(arg) {
return (vtype, None);
}

let version = Semver::Version::parse(Semver::SlicedString::init(arg, arg));
if version.valid {
if Self::is_valid_version(&version) {
return (VersionType::Specific, Some(arg));
}

Expand Down Expand Up @@ -498,7 +507,7 @@ impl PmVersionCommand {
}

let current = Semver::Version::parse(Semver::SlicedString::init(current_str, current_str));
if !current.valid {
if !Self::is_valid_version(&current) {
Output::err_generic(
"Current version \"{}\" is not a valid semver",
(BStr::new(current_str),),
Expand All @@ -518,7 +527,7 @@ impl PmVersionCommand {
break 'blk current_prerelease[..dot_index as usize].to_vec();
}

break 'blk if bun_core::fmt::parse_decimal::<u32>(current_prerelease).is_some() {
break 'blk if Self::next_prerelease_number(current_prerelease).is_some() {
Vec::new()
} else {
current_prerelease.to_vec()
Expand All @@ -530,6 +539,12 @@ impl PmVersionCommand {
Self::increment_version(current_str, &current, version_type, &prerelease_id)
}

/// The number after the prerelease identifier `identifier`. `None` when it is not a number
/// or `+ 1` does not fit. A u64 like `Tag::order_pre`: a u32 read 20250101123456 as a string.
Comment thread
robobun marked this conversation as resolved.
Resolved
fn next_prerelease_number(identifier: &[u8]) -> Option<u64> {
bun_core::fmt::parse_decimal::<u64>(identifier)?.checked_add(1)
}

fn increment_version(
current_str: &[u8],
current: &Semver::version::ParseResult<u64>,
Expand Down Expand Up @@ -613,34 +628,33 @@ impl PmVersionCommand {

if let Some(dot_index) = strings::last_index_of_char(current_prerelease, b'.') {
let number_str = &current_prerelease[(dot_index as usize) + 1..];
let next_num = bun_core::fmt::parse_decimal::<u32>(number_str).unwrap_or(0);
let next_num = Self::next_prerelease_number(number_str).unwrap_or(1);
return Ok(fmt_bytes(format_args!(
"{}.{}.{}-{}.{}",
new_version.major,
new_version.minor,
new_version.patch,
BStr::new(identifier),
next_num + 1
next_num
)));
} else {
let num = bun_core::fmt::parse_decimal::<u32>(current_prerelease);
if let Some(n) = num {
if let Some(next_num) = Self::next_prerelease_number(current_prerelease) {
if !preid.is_empty() {
return Ok(fmt_bytes(format_args!(
"{}.{}.{}-{}.{}",
new_version.major,
new_version.minor,
new_version.patch,
BStr::new(preid),
n + 1
next_num
)));
} else {
return Ok(fmt_bytes(format_args!(
"{}.{}.{}-{}",
new_version.major,
new_version.minor,
new_version.patch,
n + 1
next_num
)));
}
} else {
Expand Down
92 changes: 92 additions & 0 deletions test/cli/install/bun-pm-version.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,20 @@ describe.concurrent("bun pm version", () => {
expect(packageJson.version).toBe("2.0.0");
});

// `npm version patch` writes the same version, although both tools then refuse to increment it again.
it("increments a number equal to Number.MAX_SAFE_INTEGER", async () => {
await using testDir = tempDir(`version-${i++}`, {
"package.json": JSON.stringify({ name: "test", version: "1.0.9007199254740991" }, null, 2),
});

const { output, error, code } = await runCommand(
[bunExe(), "pm", "version", "patch", "--no-git-tag-version"],
testDir,
);

expect({ output, error, code }).toEqual({ output: "v1.0.9007199254740992\n", error: "", code: 0 });
});

it("should set specific version", async () => {
const testDir = setupTest();

Expand Down Expand Up @@ -274,6 +288,53 @@ describe.concurrent("bun pm version", () => {
expect(code5).toBe(0);
});

// `npm version` rejects these too (node-semver: "Invalid patch version"). The number used to wrap:
// the first three wrote 1.0.0, 1.0.0 and 0.0.0, and the `+ 1` aborted a debug build.
it.each([
["1.0.18446744073709551615", "patch"],
["1.18446744073709551615.0", "minor"],
["18446744073709551615.0.0", "major"],
["1.0.18446744073709551615", "prerelease"],
["1.0.9007199254740992", "patch"],
])("rejects %s as the version to increment with %s", async (version, increment) => {
await using testDir = tempDir(`version-${i++}`, {
"package.json": JSON.stringify({ name: "test", version }, null, 2),
});

const { output, error, code } = await runCommand(
[bunExe(), "pm", "version", increment, "--no-git-tag-version"],
testDir,
false,
);
const packageJson = await Bun.file(join(String(testDir), "package.json")).json();

expect({ output, error, code, version: packageJson.version }).toEqual({
output: "",
error: `error: Current version "${version}" is not a valid semver\n`,
code: 1,
version,
});
});

// The same limit applies to a version given as the argument. `npm version` prints "Invalid version".
it("rejects a specific version with a number above Number.MAX_SAFE_INTEGER", async () => {
const testDir = setupTest();

const { output, error, code } = await runCommand(
[bunExe(), "pm", "version", "1.0.9007199254740992", "--no-git-tag-version"],
testDir,
false,
);
const packageJson = await Bun.file(join(testDir, "package.json")).json();

expect({ output, error: error.split("\n")[0], code, version: packageJson.version }).toEqual({
output: "",
error: 'error: Invalid version argument: "1.0.9007199254740992"',
code: 1,
version: "1.0.0",
});
});

it("handles missing package.json like npm", async () => {
await using testDir = tempDir(`version-${i++}`, {
"README.md": "# Test project",
Expand Down Expand Up @@ -579,6 +640,37 @@ describe.concurrent("bun pm version", () => {
expect(output6.trim()).toBe("v1.0.0-4");
});

// The prerelease number used to be read as a u32: 4294967295 wrapped to 0 and a build timestamp
// (above 2^32 - 1) counted as 0, so both wrote a version lower than the current one.
it.each([
["1.0.0-beta.4294967295", [], "1.0.0-beta.4294967296"],
["1.0.0-4294967295", [], "1.0.0-4294967296"],
["1.0.0-4294967295", ["--preid", "rc"], "1.0.0-rc.4294967296"],
["1.0.0-canary.20250101123456", [], "1.0.0-canary.20250101123457"],
["1.0.0-20250101123456", [], "1.0.0-20250101123457"],
["1.0.0-beta.18446744073709551614", [], "1.0.0-beta.18446744073709551615"],
// No larger number fits, so this one counts as a name and gets a new field.
["1.0.0-18446744073709551615", [], "1.0.0-18446744073709551615.1"],
["1.0.9007199254740991-0", [], "1.0.9007199254740991-1"],
])("increments the prerelease number of %s", async (version, flags, expected) => {
await using testDir = tempDir(`version-${i++}`, {
"package.json": JSON.stringify({ name: "test", version }, null, 2),
});

const { output, error, code } = await runCommand(
[bunExe(), "pm", "version", "prerelease", ...flags, "--no-git-tag-version"],
testDir,
);
const packageJson = await Bun.file(join(String(testDir), "package.json")).json();

expect({ output, error, code, version: packageJson.version }).toEqual({
output: `v${expected}\n`,
error: "",
code: 0,
version: expected,
});
});

it("should preserve prerelease identifiers correctly", async () => {
const scenarios = [
{
Expand Down
Loading