Skip to content

Conform Semver and Range to fmt::Display #10

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Jan 5, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
84 changes: 83 additions & 1 deletion lib/src/range/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
use crate::semver::Semver;
use std::hash::{Hash, Hasher};
use std::{
fmt,
hash::{Hash, Hasher},
};

pub mod intersect;
pub mod max;
Expand Down Expand Up @@ -43,3 +46,82 @@ impl Hash for Semver {
self.components.hash(state);
}
}

impl fmt::Display for Range {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let str = self
.set
.iter()
.map(|v| match v {
Constraint::Any => "*".to_string(),
Constraint::Single(v) => format!("={}", v),
Constraint::Contiguous(v1, v2) => {
if v2.major == v1.major + 1 && v2.minor == 0 && v2.patch == 0 {
let v = chomp(v1);
if v1.major == 0 {
if v1.components.len() == 1 {
"^0".to_string()
} else {
format!(">={}<1", v)
}
} else {
format!("^{}", v)
}
} else if v2.major == v1.major && v2.minor == v1.minor + 1 && v2.patch == 0 {
let v = chomp(v1);
format!("~{}", v)
} else if v2.major == usize::MAX {
let v = chomp(v1);
format!(">={}", v)
} else if at(v1, v2) {
format!("@{}", v1)
} else {
format!(">={}<{}", chomp(v1), chomp(v2))
}
}
})
.collect::<Vec<_>>()
.join(",");
write!(f, "{}", str)
}
}

/// checks @ syntax, eg. [email protected]
fn at(v1: &Semver, v2: &Semver) -> bool {
let mut cc1 = v1.components.clone();
let cc2 = &v2.components;

if cc1.len() > cc2.len() {
return false;
}

// Ensure cc1 and cc2 have the same length by appending 0s to cc1
while cc1.len() < cc2.len() {
cc1.push(0);
}

if last(&cc1) != last(cc2) - 1 {
return false;
}

for i in 0..cc1.len() - 1 {
if cc1[i] != cc2[i] {
return false;
}
}

true
}

fn last(arr: &[usize]) -> usize {
*arr.last().unwrap()
}

fn chomp(v: &Semver) -> String {
let result = v.raw.trim_end_matches(".0");
if result.is_empty() {
"0".to_string()
} else {
result.to_string()
}
}
16 changes: 16 additions & 0 deletions lib/src/semver/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::fmt;

pub mod bump;
pub mod compare;
pub mod parse;
Expand Down Expand Up @@ -28,3 +30,17 @@ impl Semver {
}
}
}

impl fmt::Display for Semver {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{}",
self.components
.iter()
.map(|c| c.to_string())
.collect::<Vec<_>>()
.join(".")
)
}
}
Loading