use std::borrow::Borrow;
use std::fmt;
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct PackageName(String);
impl PackageName {
pub fn new(value: impl Into<String>) -> Self {
Self(value.into())
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[must_use]
pub fn into_string(self) -> String {
self.0
}
#[must_use]
pub fn for_tracing(&self) -> String {
crate::redact::redact_declaration_key(&self.0).into_owned()
}
}
impl fmt::Debug for PackageName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&crate::redact::redact_declaration_key(&self.0), f)
}
}
impl From<String> for PackageName {
fn from(value: String) -> Self {
Self(value)
}
}
impl From<&str> for PackageName {
fn from(value: &str) -> Self {
Self(value.to_string())
}
}
impl AsRef<str> for PackageName {
fn as_ref(&self) -> &str {
&self.0
}
}
impl Borrow<str> for PackageName {
fn borrow(&self) -> &str {
&self.0
}
}
impl PartialEq<str> for PackageName {
fn eq(&self, other: &str) -> bool {
self.0 == other
}
}
impl PartialEq<&str> for PackageName {
fn eq(&self, other: &&str) -> bool {
self.0 == *other
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("{0}")]
pub struct InvalidPackageName(std::borrow::Cow<'static, str>);
impl InvalidPackageName {
pub fn new(reason: impl Into<std::borrow::Cow<'static, str>>) -> Self {
Self(reason.into())
}
#[must_use]
pub fn reason(&self) -> &str {
&self.0
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct VersionReq(String);
impl VersionReq {
pub fn new(value: impl Into<String>) -> Self {
Self(value.into())
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[must_use]
pub fn into_string(self) -> String {
self.0
}
}
impl fmt::Display for VersionReq {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl From<String> for VersionReq {
fn from(value: String) -> Self {
Self(value)
}
}
impl From<&str> for VersionReq {
fn from(value: &str) -> Self {
Self(value.to_string())
}
}
impl AsRef<str> for VersionReq {
fn as_ref(&self) -> &str {
&self.0
}
}
impl PartialEq<str> for VersionReq {
fn eq(&self, other: &str) -> bool {
self.0 == other
}
}
impl PartialEq<&str> for VersionReq {
fn eq(&self, other: &&str) -> bool {
self.0 == *other
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ConcreteVersion(String);
impl ConcreteVersion {
pub fn new(value: impl Into<String>) -> Self {
Self(value.into())
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[must_use]
pub fn into_string(self) -> String {
self.0
}
#[must_use]
pub fn eq_ignoring_build_metadata(&self, other: &Self) -> bool {
strip_build_metadata(&self.0) == strip_build_metadata(&other.0)
}
}
impl fmt::Display for ConcreteVersion {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl From<String> for ConcreteVersion {
fn from(value: String) -> Self {
Self(value)
}
}
impl From<&str> for ConcreteVersion {
fn from(value: &str) -> Self {
Self(value.to_string())
}
}
impl AsRef<str> for ConcreteVersion {
fn as_ref(&self) -> &str {
&self.0
}
}
impl PartialEq<str> for ConcreteVersion {
fn eq(&self, other: &str) -> bool {
self.0 == other
}
}
impl PartialEq<&str> for ConcreteVersion {
fn eq(&self, other: &&str) -> bool {
self.0 == *other
}
}
pub(crate) fn strip_build_metadata(version: &str) -> &str {
version
.split_once('+')
.map_or(version, |(precedence, _)| precedence)
}
#[expect(
clippy::string_slice,
reason = "slash_rel comes from str::find('/'), an ASCII byte, so slash_rel + 1 is always \
a char boundary"
)]
#[must_use]
pub fn npm_style_name_boundary(rest: &str) -> Option<usize> {
if let Some(after_at) = rest.strip_prefix('@') {
let slash_rel = after_at.find('/')?;
if slash_rel == 0 {
return None; }
let after_slash = &after_at[slash_rel + 1..];
let pkg_end_rel = after_slash.find(['@', '/']).unwrap_or(after_slash.len());
if pkg_end_rel == 0 {
return None; }
Some(1 + slash_rel + 1 + pkg_end_rel)
} else {
let end = rest.find(['@', '/']).unwrap_or(rest.len());
(end > 0).then_some(end)
}
}
#[cfg(test)]
mod tests {
use super::{ConcreteVersion, PackageName, VersionReq};
#[test]
fn eq_ignoring_build_metadata_cases() {
for (a, b, expected) in [
("1.2.3", "1.2.3", true),
("1.2.3+a", "1.2.3+b", true),
("1.2.3", "1.2.3+b", true),
("1.2.3+a", "1.2.3", true),
("1.2.3", "1.2.4+b", false),
("1.2.3-beta.1", "1.2.3+b", false),
("1.2.3-beta.1+a", "1.2.3-beta.1+b", true),
("1.2.3+", "1.2.3", true),
("1.2.3+a+b", "1.2.3+c", true),
("1.2.3+a+b", "1.2.4+a+b", false),
] {
assert_eq!(
ConcreteVersion::new(a).eq_ignoring_build_metadata(&ConcreteVersion::new(b)),
expected,
"{a} vs {b}"
);
}
}
#[test]
fn package_name_round_trips_empty_string() {
let name = PackageName::new("");
assert_eq!(name.as_str(), "");
assert_eq!(name, "");
}
#[test]
fn package_name_round_trips_surrounding_whitespace() {
let name = PackageName::new(" serde ");
assert_eq!(name.as_str(), " serde ");
assert_eq!(name, " serde ");
}
#[test]
fn package_name_round_trips_non_ascii() {
let name = PackageName::new("パッケージ");
assert_eq!(name.as_str(), "パッケージ");
assert_eq!(name, "パッケージ");
}
#[test]
fn package_name_compares_byte_wise_like_string() {
assert_ne!(PackageName::new("Foo"), PackageName::new("foo"));
assert_eq!(
PackageName::new("Foo") == PackageName::new("foo"),
"Foo" == "foo"
);
}
#[test]
fn package_name_into_string_roundtrip() {
let original = String::from("tokio");
let name = PackageName::new(original.clone());
assert_eq!(name.into_string(), original);
}
#[test]
fn package_name_debug_redacts_credential_shape() {
let name = PackageName::new("com.google.guava:deploy:TOKEN@git.internal.corp");
assert_eq!(format!("{name:?}"), "\"***@git.internal.corp\"");
}
#[test]
fn package_name_debug_leaves_ordinary_name_untouched() {
let name = PackageName::new("com.google.guava:guava");
assert_eq!(format!("{name:?}"), "\"com.google.guava:guava\"");
}
#[test]
fn for_tracing_neutralizes_control_characters() {
for forged in [
"lodash\nERROR deps_lsp: FORGED\x1b[31mRED",
"ok\r\nWARN forged2",
] {
let rendered = PackageName::new(forged).for_tracing();
assert!(
!rendered.contains('\n'),
"{rendered:?} must not contain \\n"
);
assert!(
!rendered.contains('\r'),
"{rendered:?} must not contain \\r"
);
assert!(
!rendered.contains('\x1b'),
"{rendered:?} must not contain ESC"
);
}
}
#[test]
fn for_tracing_neutralizes_control_characters_alongside_credential_redaction() {
let rendered =
PackageName::new("com.google.guava:deploy:TOKEN@git.internal\ncorp").for_tracing();
assert!(!rendered.contains('\n'));
assert!(!rendered.contains("TOKEN"));
}
#[test]
fn package_name_hashmap_reachable_by_str_and_by_package_name() {
use std::collections::HashMap;
let mut map: HashMap<PackageName, u32> = HashMap::new();
map.insert(PackageName::new("serde"), 1);
assert_eq!(map.get("serde"), Some(&1));
assert_eq!(map.get(&PackageName::new("serde")), Some(&1));
}
#[test]
fn version_req_round_trips_empty_string() {
let req = VersionReq::new("");
assert_eq!(req.as_str(), "");
assert_eq!(req, "");
}
#[test]
fn version_req_round_trips_surrounding_whitespace() {
let req = VersionReq::new(" ^1.0 ");
assert_eq!(req.as_str(), " ^1.0 ");
assert_eq!(req, " ^1.0 ");
}
#[test]
fn version_req_round_trips_non_ascii() {
let req = VersionReq::new("非対応");
assert_eq!(req.as_str(), "非対応");
assert_eq!(req, "非対応");
}
#[test]
fn version_req_compares_byte_wise_like_string() {
assert_ne!(VersionReq::new("^1.0"), VersionReq::new("^1.0 "));
}
#[test]
fn version_req_into_string_roundtrip() {
let original = String::from("~2.3.4");
let req = VersionReq::new(original.clone());
assert_eq!(req.into_string(), original);
}
#[test]
fn concrete_version_round_trips_empty_string() {
let version = ConcreteVersion::new("");
assert_eq!(version.as_str(), "");
assert_eq!(version, "");
}
#[test]
fn concrete_version_round_trips_surrounding_whitespace() {
let version = ConcreteVersion::new(" 1.0.0 ");
assert_eq!(version.as_str(), " 1.0.0 ");
assert_eq!(version, " 1.0.0 ");
}
#[test]
fn concrete_version_round_trips_non_ascii() {
let version = ConcreteVersion::new("バージョン");
assert_eq!(version.as_str(), "バージョン");
assert_eq!(version, "バージョン");
}
#[test]
fn concrete_version_compares_byte_wise_like_string() {
assert_ne!(
ConcreteVersion::new("1.0.0"),
ConcreteVersion::new("1.0.0 ")
);
}
#[test]
fn concrete_version_into_string_roundtrip() {
let original = String::from("2.3.4");
let version = ConcreteVersion::new(original.clone());
assert_eq!(version.into_string(), original);
}
}