1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
use std::fmt::Display;

#[cfg(feature = "schema")]
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

/// Pattern matching for the version of Minecraft, a package, etc.
#[derive(Debug, Hash, Clone, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
pub enum VersionPattern {
	/// Matches a single version
	Single(String),
	/// Matches the latest version in the list
	Latest(Option<String>),
	/// Matches any version that is <= a version
	Before(String),
	/// Matches any version that is >= a version
	After(String),
	/// Matches any versions between an inclusive range
	Range(String, String),
	/// Matches any version
	Any,
}

impl VersionPattern {
	/// Finds all match in a list of versions
	pub fn get_matches(&self, versions: &[String]) -> Vec<String> {
		match self {
			Self::Single(version) => match versions.contains(version) {
				true => vec![version.to_string()],
				false => vec![],
			},
			Self::Latest(found) => match found {
				Some(found) => vec![found.clone()],
				None => match versions.get(versions.len()).cloned() {
					Some(version) => vec![version],
					None => vec![],
				},
			},
			Self::Before(version) => match versions.iter().position(|e| e == version) {
				Some(pos) => versions[..=pos].to_vec(),
				None => vec![],
			},
			Self::After(version) => match versions.iter().position(|e| e == version) {
				Some(pos) => versions[pos..].to_vec(),
				None => vec![],
			},
			Self::Range(start, end) => match versions.iter().position(|e| e == start) {
				Some(start_pos) => match versions.iter().position(|e| e == end) {
					Some(end_pos) => versions[start_pos..=end_pos].to_vec(),
					None => vec![],
				},
				None => vec![],
			},
			Self::Any => versions.to_vec(),
		}
	}

	/// Finds the newest match in a list of versions
	pub fn get_match(&self, versions: &[String]) -> Option<String> {
		self.get_matches(versions).last().cloned()
	}

	/// Compares this pattern to a single string.
	/// For some pattern types, this may return false if it is unable to deduce an
	/// answer from the list of versions provided.
	pub fn matches_single(&self, version: &str, versions: &[String]) -> bool {
		match self {
			Self::Single(vers) => version == vers,
			Self::Latest(cached) => match cached {
				Some(vers) => version == vers,
				None => {
					if let Some(latest) = versions.last() {
						version == latest
					} else {
						false
					}
				}
			},
			Self::Before(vers) => {
				if let Some(vers_pos) = versions.iter().position(|x| x == vers) {
					if let Some(version_pos) = versions.iter().position(|x| x == version) {
						version_pos <= vers_pos
					} else {
						false
					}
				} else {
					false
				}
			}
			Self::After(vers) => {
				if let Some(vers_pos) = versions.iter().position(|x| x == vers) {
					if let Some(version_pos) = versions.iter().position(|x| x == version) {
						version_pos >= vers_pos
					} else {
						false
					}
				} else {
					false
				}
			}
			Self::Range(start, end) => {
				if let Some(start_pos) = versions.iter().position(|x| x == start) {
					if let Some(end_pos) = versions.iter().position(|x| x == end) {
						if let Some(version_pos) = versions.iter().position(|x| x == version) {
							(version_pos >= start_pos) && (version_pos <= end_pos)
						} else {
							false
						}
					} else {
						false
					}
				} else {
					false
				}
			}
			Self::Any => versions.contains(&version.to_string()),
		}
	}

	/// Compares this pattern to a version supplied in a VersionInfo
	pub fn matches_info(&self, version_info: &VersionInfo) -> bool {
		self.matches_single(&version_info.version, &version_info.versions)
	}

	/// Returns the union of matches for multiple patterns
	pub fn match_union(&self, other: &Self, versions: &[String]) -> Vec<String> {
		self.get_matches(versions)
			.iter()
			.zip(other.get_matches(versions))
			.filter_map(
				|(left, right)| {
					if *left == right {
						Some(right)
					} else {
						None
					}
				},
			)
			.collect()
	}

	/// Creates a version pattern by parsing a string
	pub fn from(text: &str) -> Self {
		match text {
			"latest" => Self::Latest(None),
			"*" => Self::Any,
			text => {
				if let Some(last) = text.chars().last() {
					match last {
						'-' => return Self::Before(text[..text.len() - 1].to_string()),
						'+' => return Self::After(text[..text.len() - 1].to_string()),
						_ => {}
					}
				}

				let range_split: Vec<_> = text.split("..").collect();
				if range_split.len() == 2 {
					let start = range_split
						.first()
						.expect("First element in range split should exist");
					let end = range_split
						.get(1)
						.expect("Second element in range split should exist");
					return Self::Range(start.to_string(), end.to_string());
				}

				Self::Single(text.to_string())
			}
		}
	}

	/// Checks that a string contains no pattern-special characters
	#[cfg(test)]
	pub fn validate(text: &str) -> bool {
		if text.contains('*') || text.contains("..") || text == "latest" {
			return false;
		}
		if let Some(last) = text.chars().last() {
			if last == '-' || last == '+' {
				return false;
			}
		}
		true
	}
}

impl Display for VersionPattern {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		write!(
			f,
			"{}",
			match self {
				Self::Single(version) => version.to_string(),
				Self::Latest(..) => "latest".into(),
				Self::Before(version) => version.to_string() + "-",
				Self::After(version) => version.to_string() + "+",
				Self::Range(start, end) => start.to_string() + ".." + end,
				Self::Any => "*".into(),
			}
		)
	}
}

impl<'de> Deserialize<'de> for VersionPattern {
	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
	where
		D: serde::Deserializer<'de>,
	{
		let string = String::deserialize(deserializer)?;
		Ok(Self::from(&string))
	}
}

impl Serialize for VersionPattern {
	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
	where
		S: serde::Serializer,
	{
		let ser = self.to_string().serialize(serializer)?;
		Ok(ser)
	}
}

/// Utility struct that contains the version and version list
#[derive(Debug)]
pub struct VersionInfo {
	/// The version
	pub version: String,
	/// The list of available versions to use for comparisons
	pub versions: Vec<String>,
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn test_version_pattern() {
		let versions = vec![
			"1.16.5".to_string(),
			"1.17".to_string(),
			"1.18".to_string(),
			"1.19.3".to_string(),
		];

		assert_eq!(
			VersionPattern::Single("1.19.3".into()).get_match(&versions),
			Some("1.19.3".into())
		);
		assert_eq!(
			VersionPattern::Single("1.18".into()).get_match(&versions),
			Some("1.18".into())
		);
		assert_eq!(
			VersionPattern::Single(String::new()).get_match(&versions),
			None
		);
		assert_eq!(
			VersionPattern::Before("1.18".into()).get_match(&versions),
			Some("1.18".into())
		);
		assert_eq!(
			VersionPattern::After("1.16.5".into()).get_match(&versions),
			Some("1.19.3".into())
		);

		assert_eq!(
			VersionPattern::Before("1.17".into()).get_matches(&versions),
			vec!["1.16.5".to_string(), "1.17".to_string()]
		);
		assert_eq!(
			VersionPattern::After("1.17".into()).get_matches(&versions),
			vec!["1.17".to_string(), "1.18".to_string(), "1.19.3".to_string()]
		);
		assert_eq!(
			VersionPattern::Range("1.16.5".into(), "1.18".into()).get_matches(&versions),
			vec!["1.16.5".to_string(), "1.17".to_string(), "1.18".to_string()]
		);

		assert!(VersionPattern::Before("1.18".into()).matches_single("1.16.5", &versions));
		assert!(VersionPattern::After("1.18".into()).matches_single("1.19.3", &versions));
		assert!(VersionPattern::Latest(None).matches_single("1.19.3", &versions));
	}

	#[test]
	fn test_version_pattern_parse() {
		assert_eq!(
			VersionPattern::from("+1.19.5"),
			VersionPattern::Single("+1.19.5".into())
		);
		assert_eq!(VersionPattern::from("latest"), VersionPattern::Latest(None));
		assert_eq!(
			VersionPattern::from("1.19.5-"),
			VersionPattern::Before("1.19.5".into())
		);
		assert_eq!(
			VersionPattern::from("1.19.5+"),
			VersionPattern::After("1.19.5".into())
		);
		assert_eq!(
			VersionPattern::from("1.17.1..1.19.3"),
			VersionPattern::Range("1.17.1".into(), "1.19.3".into())
		);
	}

	#[test]
	fn test_version_pattern_validation() {
		assert!(VersionPattern::validate("hello"));
		assert!(!VersionPattern::validate("latest"));
		assert!(!VersionPattern::validate("foo-"));
		assert!(!VersionPattern::validate("foo+"));
		assert!(!VersionPattern::validate("f*o"));
		assert!(!VersionPattern::validate("f..o"));
	}
}