#![forbid(unsafe_code)]
#![doc = include_str!("../README.md")]
use core::{fmt, str::FromStr};
use std::error::Error;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum GoModuleError {
EmptyPath,
InvalidPath,
EmptyVersion,
InvalidVersion,
EmptyPseudoVersion,
InvalidPseudoVersion,
}
impl fmt::Display for GoModuleError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::EmptyPath => formatter.write_str("Go module path cannot be empty"),
Self::InvalidPath => formatter.write_str("invalid Go module path"),
Self::EmptyVersion => formatter.write_str("Go module version cannot be empty"),
Self::InvalidVersion => formatter.write_str("invalid Go module version"),
Self::EmptyPseudoVersion => formatter.write_str("Go pseudo-version cannot be empty"),
Self::InvalidPseudoVersion => formatter.write_str("invalid Go pseudo-version"),
}
}
}
impl Error for GoModuleError {}
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct GoModulePath(String);
impl GoModulePath {
pub fn new(value: impl AsRef<str>) -> Result<Self, GoModuleError> {
let trimmed = value.as_ref().trim();
if trimmed.is_empty() {
return Err(GoModuleError::EmptyPath);
}
if !is_valid_path_text(trimmed) {
return Err(GoModuleError::InvalidPath);
}
Ok(Self(trimmed.to_string()))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[must_use]
pub fn into_string(self) -> String {
self.0
}
}
impl AsRef<str> for GoModulePath {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl fmt::Display for GoModulePath {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
impl FromStr for GoModulePath {
type Err = GoModuleError;
fn from_str(value: &str) -> Result<Self, Self::Err> {
Self::new(value)
}
}
impl TryFrom<&str> for GoModulePath {
type Error = GoModuleError;
fn try_from(value: &str) -> Result<Self, Self::Error> {
Self::new(value)
}
}
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct GoModuleVersion(String);
impl GoModuleVersion {
pub fn new(value: impl AsRef<str>) -> Result<Self, GoModuleError> {
let trimmed = value.as_ref().trim();
if trimmed.is_empty() {
return Err(GoModuleError::EmptyVersion);
}
if !is_lightweight_module_version(trimmed) {
return Err(GoModuleError::InvalidVersion);
}
Ok(Self(trimmed.to_string()))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[must_use]
pub fn is_pseudo_version(&self) -> bool {
is_pseudo_version_like(self.as_str())
}
}
impl AsRef<str> for GoModuleVersion {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl fmt::Display for GoModuleVersion {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
impl FromStr for GoModuleVersion {
type Err = GoModuleError;
fn from_str(value: &str) -> Result<Self, Self::Err> {
Self::new(value)
}
}
impl TryFrom<&str> for GoModuleVersion {
type Error = GoModuleError;
fn try_from(value: &str) -> Result<Self, Self::Error> {
Self::new(value)
}
}
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct GoPseudoVersion(String);
impl GoPseudoVersion {
pub fn new(value: impl AsRef<str>) -> Result<Self, GoModuleError> {
let trimmed = value.as_ref().trim();
if trimmed.is_empty() {
return Err(GoModuleError::EmptyPseudoVersion);
}
if !is_pseudo_version_like(trimmed) {
return Err(GoModuleError::InvalidPseudoVersion);
}
Ok(Self(trimmed.to_string()))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl AsRef<str> for GoPseudoVersion {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl fmt::Display for GoPseudoVersion {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
impl FromStr for GoPseudoVersion {
type Err = GoModuleError;
fn from_str(value: &str) -> Result<Self, Self::Err> {
Self::new(value)
}
}
impl TryFrom<&str> for GoPseudoVersion {
type Error = GoModuleError;
fn try_from(value: &str) -> Result<Self, Self::Error> {
Self::new(value)
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GoModuleDependency {
path: GoModulePath,
version: GoModuleVersion,
}
impl GoModuleDependency {
#[must_use]
pub const fn new(path: GoModulePath, version: GoModuleVersion) -> Self {
Self { path, version }
}
#[must_use]
pub const fn path(&self) -> &GoModulePath {
&self.path
}
#[must_use]
pub const fn version(&self) -> &GoModuleVersion {
&self.version
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GoModuleReplacement {
old_path: GoModulePath,
old_version: Option<GoModuleVersion>,
new_path: GoModulePath,
new_version: Option<GoModuleVersion>,
}
impl GoModuleReplacement {
#[must_use]
pub const fn new(old_path: GoModulePath, new_path: GoModulePath) -> Self {
Self {
old_path,
old_version: None,
new_path,
new_version: None,
}
}
#[must_use]
pub fn with_old_version(mut self, version: GoModuleVersion) -> Self {
self.old_version = Some(version);
self
}
#[must_use]
pub fn with_new_version(mut self, version: GoModuleVersion) -> Self {
self.new_version = Some(version);
self
}
#[must_use]
pub const fn old_path(&self) -> &GoModulePath {
&self.old_path
}
#[must_use]
pub const fn old_version(&self) -> Option<&GoModuleVersion> {
self.old_version.as_ref()
}
#[must_use]
pub const fn new_path(&self) -> &GoModulePath {
&self.new_path
}
#[must_use]
pub const fn new_version(&self) -> Option<&GoModuleVersion> {
self.new_version.as_ref()
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GoModuleRequirement {
dependency: GoModuleDependency,
indirect: bool,
}
impl GoModuleRequirement {
#[must_use]
pub const fn new(dependency: GoModuleDependency) -> Self {
Self {
dependency,
indirect: false,
}
}
#[must_use]
pub const fn indirect(mut self) -> Self {
self.indirect = true;
self
}
#[must_use]
pub const fn dependency(&self) -> &GoModuleDependency {
&self.dependency
}
#[must_use]
pub const fn is_indirect(&self) -> bool {
self.indirect
}
}
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum GoModuleDirectiveKind {
Module,
Go,
Toolchain,
Require,
Replace,
Exclude,
Retract,
}
impl GoModuleDirectiveKind {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Module => "module",
Self::Go => "go",
Self::Toolchain => "toolchain",
Self::Require => "require",
Self::Replace => "replace",
Self::Exclude => "exclude",
Self::Retract => "retract",
}
}
}
impl fmt::Display for GoModuleDirectiveKind {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
impl FromStr for GoModuleDirectiveKind {
type Err = GoModuleError;
fn from_str(value: &str) -> Result<Self, Self::Err> {
match normalized_label(value)?.as_str() {
"module" => Ok(Self::Module),
"go" => Ok(Self::Go),
"toolchain" => Ok(Self::Toolchain),
"require" => Ok(Self::Require),
"replace" => Ok(Self::Replace),
"exclude" => Ok(Self::Exclude),
"retract" => Ok(Self::Retract),
_ => Err(GoModuleError::InvalidPath),
}
}
}
fn is_valid_path_text(value: &str) -> bool {
!value.chars().any(char::is_whitespace)
&& !value.split('/').any(str::is_empty)
&& !value.contains('\\')
}
fn is_lightweight_module_version(value: &str) -> bool {
let Some(rest) = value.strip_prefix('v') else {
return false;
};
let base = rest.split('-').next().unwrap_or(rest);
is_semver_core(base) && !value.split('-').any(str::is_empty)
}
fn is_semver_core(value: &str) -> bool {
let mut components = value.split('.');
let Some(major) = components.next() else {
return false;
};
let Some(minor) = components.next() else {
return false;
};
let Some(patch) = components.next() else {
return false;
};
components.next().is_none()
&& is_ascii_digits(major)
&& is_ascii_digits(minor)
&& is_ascii_digits(patch)
}
fn is_pseudo_version_like(value: &str) -> bool {
let parts = value.split('-').collect::<Vec<_>>();
parts.len() >= 3
&& is_lightweight_module_version(value)
&& parts.iter().all(|part| !part.is_empty())
}
fn is_ascii_digits(value: &str) -> bool {
!value.is_empty() && value.chars().all(|character| character.is_ascii_digit())
}
fn normalized_label(value: &str) -> Result<String, GoModuleError> {
let trimmed = value.trim();
if trimmed.is_empty() {
Err(GoModuleError::EmptyPath)
} else {
Ok(trimmed.to_ascii_lowercase())
}
}
#[cfg(test)]
mod tests {
use super::{
GoModuleDependency, GoModuleDirectiveKind, GoModuleError, GoModulePath,
GoModuleReplacement, GoModuleRequirement, GoModuleVersion, GoPseudoVersion,
};
#[test]
fn validates_module_paths() -> Result<(), GoModuleError> {
let path = GoModulePath::new("example.com/project/sub")?;
assert_eq!(path.as_str(), "example.com/project/sub");
assert_eq!(GoModulePath::new(""), Err(GoModuleError::EmptyPath));
assert_eq!(
GoModulePath::new("example.com//project"),
Err(GoModuleError::InvalidPath)
);
assert_eq!(
GoModulePath::new("example.com/project name"),
Err(GoModuleError::InvalidPath)
);
Ok(())
}
#[test]
fn validates_module_versions() -> Result<(), GoModuleError> {
let version = GoModuleVersion::new("v1.2.3")?;
let pseudo = GoModuleVersion::new("v0.0.0-20240101000000-abcdefabcdef")?;
assert_eq!(version.as_str(), "v1.2.3");
assert!(pseudo.is_pseudo_version());
assert_eq!(
GoModuleVersion::new("1.2.3"),
Err(GoModuleError::InvalidVersion)
);
assert_eq!(
GoModuleVersion::new("v1.2"),
Err(GoModuleError::InvalidVersion)
);
Ok(())
}
#[test]
fn validates_pseudo_versions() -> Result<(), GoModuleError> {
let pseudo = GoPseudoVersion::new("v0.0.0-20240101000000-abcdefabcdef")?;
assert_eq!(pseudo.as_str(), "v0.0.0-20240101000000-abcdefabcdef");
assert_eq!(
GoPseudoVersion::new("v1.2.3"),
Err(GoModuleError::InvalidPseudoVersion)
);
Ok(())
}
#[test]
fn models_dependency_requirement_and_replacement() -> Result<(), GoModuleError> {
let path = GoModulePath::new("example.com/library")?;
let version = GoModuleVersion::new("v1.2.3")?;
let dependency = GoModuleDependency::new(path.clone(), version.clone());
let requirement = GoModuleRequirement::new(dependency).indirect();
let replacement = GoModuleReplacement::new(path, GoModulePath::new("../library")?)
.with_old_version(version.clone())
.with_new_version(version);
assert!(requirement.is_indirect());
assert_eq!(
replacement.old_version().map(GoModuleVersion::as_str),
Some("v1.2.3")
);
assert_eq!(replacement.new_path().as_str(), "../library");
Ok(())
}
#[test]
fn parses_directive_kinds() -> Result<(), GoModuleError> {
assert_eq!(
"require".parse::<GoModuleDirectiveKind>()?,
GoModuleDirectiveKind::Require
);
assert_eq!(GoModuleDirectiveKind::Toolchain.to_string(), "toolchain");
Ok(())
}
}