lux_lib/lockfile/
constraint.rs1use miette::Diagnostic;
2use serde::Deserialize;
3use thiserror::Error;
4
5use crate::package;
6
7#[derive(Clone, Debug, PartialEq, Eq, Hash, Default)]
8pub enum Constraint {
9 #[default]
10 Unconstrained,
11 Constrained(package::VersionReq),
12}
13
14impl<'de> Deserialize<'de> for Constraint {
15 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
16 where
17 D: serde::Deserializer<'de>,
18 {
19 let str = String::deserialize(deserializer)?;
20 match str.as_str() {
21 "*" => Ok(Constraint::Unconstrained),
22 _ => Ok(Constraint::Constrained(
23 str.parse().map_err(serde::de::Error::custom)?,
24 )),
25 }
26 }
27}
28
29impl Constraint {
30 pub fn to_string_opt(&self) -> Option<String> {
31 match self {
32 Constraint::Unconstrained => None,
33 Constraint::Constrained(req) => Some(req.to_string()),
34 }
35 }
36
37 pub(crate) fn matches_version_req(&self, req: &package::VersionReq) -> bool {
38 match self {
39 Constraint::Unconstrained => req.is_any(),
40 Constraint::Constrained(package_version_req) => package_version_req == req,
41 }
42 }
43}
44
45impl From<package::VersionReq> for Constraint {
46 fn from(value: package::VersionReq) -> Self {
47 if value.is_any() {
48 Self::Unconstrained
49 } else {
50 Self::Constrained(value)
51 }
52 }
53}
54
55#[derive(Error, Debug, Diagnostic)]
56#[non_exhaustive]
57pub enum Error {
58 #[error("invalid constraint in LuaPackage")]
59 #[diagnostic(forward(0))]
60 VersionReq(#[from] package::version::ReqError),
61}
62
63impl TryFrom<&Option<String>> for Constraint {
64 type Error = Error;
65
66 fn try_from(constraint: &Option<String>) -> Result<Self, Self::Error> {
67 match constraint {
68 Some(constraint) => {
69 let package_version_req = constraint.parse()?;
70 Ok(Constraint::Constrained(package_version_req))
71 }
72 None => Ok(Constraint::Unconstrained),
73 }
74 }
75}