Skip to content
Closed
Show file tree
Hide file tree
Changes from 5 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
2 changes: 2 additions & 0 deletions docs/runtime/semver.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ semver.satisfies("1.0.0", "1.0.0 - 1.0.1"); // true

`satisfies` returns `false` if `version` is invalid, or if either argument contains a non-ASCII character. Bun ignores the parts of `range` that it cannot parse. A `range` with no parseable part behaves like `*`.

A major, minor, or patch number above 2^64 - 1 makes a version invalid. No version satisfies a `range` that has such a number before any wildcard. A number after a wildcard, as in `1.x.5`, has no effect on a `range`.

## `Bun.semver.order(versionA: string, versionB: string): 0 | 1 | -1`

Returns `0` if `versionA` and `versionB` are equal, `1` if `versionA` is greater than `versionB`, and `-1` if `versionA` is less than `versionB`.
Expand Down
26 changes: 26 additions & 0 deletions src/semver/SemverQuery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -472,6 +472,25 @@ impl Group {
}
}

/// A group that no version satisfies.
fn null_set(input: &[u8]) -> Group {
Group {
head: List {
head: Query {
range: Range {
left: Comparator::null_set(),
..Default::default()
},
next: None,
},
tail: None,
next: None,
},
input: std::ptr::from_ref::<[u8]>(input),
..Default::default()
}
}
Comment thread
robobun marked this conversation as resolved.
Resolved

pub fn is_exact(&self) -> bool {
self.head.next.is_none()
&& self.head.head.next.is_none()
Expand Down Expand Up @@ -945,6 +964,10 @@ pub fn parse(input: &[u8], sliced: SlicedString) -> Result<Group, AllocError> {

if !skip_round {
let parse_result = Version::parse(sliced.sub(&input[i..]));
// node-semver rejects the whole range for a number it cannot hold.
if parse_result.overflow {
return Ok(Group::null_set(input));
}
let version = parse_result.version.min();
if version.tag.has_build() {
list.flags.set(Flags::BUILD);
Expand Down Expand Up @@ -997,6 +1020,9 @@ pub fn parse(input: &[u8], sliced: SlicedString) -> Result<Group, AllocError> {

if hyphenate {
let second_parsed = Version::parse(sliced.sub(&input[i..]));
if second_parsed.overflow {
return Ok(Group::null_set(input));
}
let mut second_version = second_parsed.version.min();
if second_version.tag.has_build() {
list.flags.set(Flags::BUILD);
Expand Down
17 changes: 16 additions & 1 deletion src/semver/SemverRange.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
use core::cmp::Ordering;
use core::fmt;

use crate::Version;
use crate::query::token::Wildcard;
use crate::version::Tag;
use crate::{SlicedString, Version};

#[repr(u8)]
#[derive(Copy, Clone, PartialEq, Eq, Default)]
Expand Down Expand Up @@ -183,6 +184,20 @@ pub struct Comparator {
}

impl Comparator {
/// `<0.0.0-0`: no version satisfies it. node-semver uses it for the empty set.
pub(crate) fn null_set() -> Comparator {
Comparator {
op: Op::Lt,
version: Version {
tag: Tag {
pre: SlicedString::init(b"0", b"0").external(),
..Default::default()
},
..Default::default()
},
}
}

/// `< {major+1}.0.0`, or `<= u64::MAX.u64::MAX.u64::MAX` when `major+1`
/// would overflow so the desugared range stays non-empty at the ceiling.
pub(crate) fn lt_next_major(major: u64) -> Comparator {
Expand Down
36 changes: 20 additions & 16 deletions src/semver/Version.rs
Original file line number Diff line number Diff line change
Expand Up @@ -528,23 +528,23 @@ impl<T: VersionInt> VersionType<T> {

last_char_i = i;

match part_i {
0 => {
result.version.major =
Self::parse_version_number(&input[part_start_i..last_char_i]);
part_i = 1;
}
1 => {
result.version.minor =
Self::parse_version_number(&input[part_start_i..last_char_i]);
part_i = 2;
if part_i < 3 {
let number = Self::parse_version_number(&input[part_start_i..last_char_i]);
if number.is_none() {
result.valid = false;
// A range ignores a number after a wildcard, so keep reading the token.
if result.wildcard == Wildcard::None {
result.overflow = true;
is_done = true;
break;
}
}
2 => {
result.version.patch =
Self::parse_version_number(&input[part_start_i..last_char_i]);
part_i = 3;
match part_i {
0 => result.version.major = number,
1 => result.version.minor = number,
_ => result.version.patch = number,
}
_ => {}
part_i += 1;
}

if i < input.len()
Expand Down Expand Up @@ -652,11 +652,12 @@ impl<T: VersionInt> VersionType<T> {
result
}

/// `None` when the number is above `T::MAX`.
fn parse_version_number(input: &[u8]) -> Option<T> {
// Callers slice `input` from the first digit to the first non-digit,
// so every byte is already `b'0'..=b'9'` and the slice is non-empty.
debug_assert!(!input.is_empty() && input.iter().all(u8::is_ascii_digit));
Some(T::parse_ascii(input).unwrap_or(T::ZERO))
T::parse_ascii(input)
}
}

Expand Down Expand Up @@ -1191,6 +1192,8 @@ pub struct TagResult {
pub struct ParseResult<T: VersionInt> {
pub wildcard: Wildcard,
pub valid: bool,
/// A number before any wildcard is above `T::MAX`. The range parser reads this, not `valid`.
pub(crate) overflow: bool,
pub version: Partial<T>,
pub(crate) len: u32,
}
Expand All @@ -1200,6 +1203,7 @@ impl<T: VersionInt> Default for ParseResult<T> {
Self {
wildcard: Wildcard::None,
valid: true,
overflow: false,
version: Partial::default(),
len: 0,
}
Expand Down
1 change: 1 addition & 0 deletions test/bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

60 changes: 60 additions & 0 deletions test/cli/install/bun-pm-version.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,66 @@ describe.concurrent("bun pm version", () => {
expect(code5).toBe(0);
});

it("rejects a version number above u64::MAX like npm", async () => {
// The parser used to read such a number as 0, so `patch` on "1.0.18446744073709551616" printed v1.0.1.
const u64Max = "18446744073709551615";
const aboveU64Max = "18446744073709551616";

const bump = async (version: string, arg: string) => {
await using testDir = tempDir(`version-${i++}`, {
"package.json": JSON.stringify({ name: "test", version }, null, 2),
});
const { output, error, code } = await runCommand(
[bunExe(), "pm", "version", arg, "--no-git-tag-version"],
testDir,
false,
);
const after = (await Bun.file(join(String(testDir), "package.json")).json()).version;
return { output, error, code, after };
};

const results = await Promise.all([
bump(`1.0.${aboveU64Max}`, "patch"),
bump(`1.0.${aboveU64Max}`, "minor"),
bump("1.0.99999999999999999999", "patch"),
bump("1.0.0", `1.0.${aboveU64Max}`),
// u64::MAX itself still fits.
bump(`1.0.${u64Max}`, "minor"),
bump("1.0.0", `1.0.${u64Max}`),
]);

expect(results).toEqual([
{
output: "",
error: `error: Current version "1.0.${aboveU64Max}" is not a valid semver\n`,
code: 1,
after: `1.0.${aboveU64Max}`,
},
{
output: "",
error: `error: Current version "1.0.${aboveU64Max}" is not a valid semver\n`,
code: 1,
after: `1.0.${aboveU64Max}`,
},
{
output: "",
error: `error: Current version "1.0.99999999999999999999" is not a valid semver\n`,
code: 1,
after: "1.0.99999999999999999999",
},
{
output: "",
error:
`error: Invalid version argument: "1.0.${aboveU64Max}"\n` +
"note: Valid options: patch, minor, major, prepatch, preminor, premajor, prerelease, from-git, or a specific semver version\n",
code: 1,
after: "1.0.0",
},
{ output: "v1.1.0\n", error: "", code: 0, after: "1.1.0" },
{ output: `v1.0.${u64Max}\n`, error: "", code: 0, after: `1.0.${u64Max}` },
]);
});

it("handles missing package.json like npm", async () => {
await using testDir = tempDir(`version-${i++}`, {
"README.md": "# Test project",
Expand Down
Loading
Loading