helixlauncher_meta/
util.rs

1/*
2 * Copyright 2022 kb1000
3 *
4 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.
5 */
6
7use std::{fmt::Display, str::FromStr};
8
9use serde_with::{DeserializeFromStr, SerializeDisplay};
10use thiserror::Error;
11
12#[derive(Debug, DeserializeFromStr, SerializeDisplay, Hash, Clone, PartialEq, Eq)]
13pub struct GradleSpecifier {
14	pub group: String,
15	pub artifact: String,
16	pub version: String,
17	pub classifier: Option<String>,
18	pub extension: String, // defaults to jar
19}
20
21impl GradleSpecifier {
22	pub fn with_classifier(&self, classifier: String) -> Self {
23		Self {
24			classifier: Some(classifier),
25			..self.clone()
26		}
27	}
28}
29
30#[derive(Error, Debug)]
31pub enum GradleParseError {
32	#[error("\"{0}\" does not contain an artifact id!")]
33	ArtifactIdMissing(String),
34	#[error("\"{0}\" does not contain a version!")]
35	VersionMissing(String),
36}
37
38impl FromStr for GradleSpecifier {
39	type Err = GradleParseError;
40
41	fn from_str(s: &str) -> Result<Self, Self::Err> {
42		let (group, s) = s
43			.split_once(':')
44			.ok_or_else(|| GradleParseError::ArtifactIdMissing(s.to_string()))?;
45		let (artifact, s) = s
46			.split_once(':')
47			.ok_or_else(|| GradleParseError::VersionMissing(s.to_string()))?;
48		let (s, extension) = s
49			.rsplit_once('@')
50			.map_or_else(|| (s, "jar"), |(s, extension)| (s, extension));
51		let (version, classifier) = s.split_once(':').map_or_else(
52			|| (s, None),
53			|(version, classifier)| (version, Some(classifier)),
54		);
55
56		Ok(GradleSpecifier {
57			group: group.to_owned(),
58			artifact: artifact.to_owned(),
59			version: version.to_owned(),
60			classifier: classifier.map(|v| v.to_owned()),
61			extension: extension.to_owned(),
62		})
63	}
64}
65
66impl Display for GradleSpecifier {
67	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
68		write!(f, "{}:{}:{}", self.group, self.artifact, self.version)?;
69		if let Some(classifier) = &self.classifier {
70			write!(f, ":{}", classifier)?;
71		}
72
73		if self.extension != "jar" {
74			write!(f, "@{}", self.extension)?;
75		}
76		Ok(())
77	}
78}