nitro_shared 0.28.0

Shared libraries and utilities for Nitrolaunch crates
Documentation
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
use anyhow::bail;
use itertools::Itertools;
#[cfg(feature = "schema")]
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::fmt::Display;
use std::hash::Hash;
use std::str::FromStr;
use std::sync::Arc;

use crate::addon::AddonKind;
use crate::loaders::Loader;
use crate::util::is_valid_identifier;
use crate::versions::{parse_versioned_string, VersionPattern};

/// Type for the ID of a package
pub type PackageID = Arc<str>;

/// Used to store a request for a package that will be fulfilled later
#[derive(Debug, Clone, PartialOrd, Ord, Deserialize, Serialize)]
pub struct PkgRequest {
	/// The source of this request.
	/// Could be a dependent, a recommender, or anything else.
	#[serde(default)]
	pub source: PkgRequestSource,
	/// The ID of the package to request
	pub id: PackageID,
	/// The requested repository of the package
	#[serde(default)]
	pub repository: Option<String>,
	/// The requested content version of the package
	#[serde(default)]
	pub content_version: VersionPattern,
}

/// Where a package was requested from
#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize, Serialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum PkgRequestSource {
	/// This package was required by the user
	#[default]
	UserRequire,
	/// This package was bundled by another package
	Bundled(ArcPkgReq),
	/// This package was depended on by another package
	Dependency(ArcPkgReq),
	/// This package was refused by another package
	Refused(ArcPkgReq),
	/// This package was requested by some automatic system
	Repository,
}

impl Ord for PkgRequestSource {
	fn cmp(&self, other: &Self) -> std::cmp::Ordering {
		self.to_num().cmp(&other.to_num())
	}
}

impl PartialOrd for PkgRequestSource {
	fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
		Some(self.cmp(other))
	}
}

impl PkgRequestSource {
	/// Gets the source package of this package, if any
	pub fn get_source(&self) -> Option<ArcPkgReq> {
		match self {
			Self::Dependency(source) | Self::Bundled(source) => Some(source.clone()),
			_ => None,
		}
	}

	/// Gets the original source package all the way up the chain
	pub fn get_original_source(&self) -> Option<&ArcPkgReq> {
		match self {
			Self::Dependency(source) | Self::Bundled(source) => match &source.source {
				Self::Dependency(..) | Self::Bundled(..) => source.source.get_original_source(),
				_ => Some(source),
			},
			_ => None,
		}
	}

	/// Gets whether this source list is only bundles that lead up to a UserRequire
	pub fn is_user_bundled(&self) -> bool {
		matches!(self, Self::Bundled(source) if source.source.is_user_bundled())
			|| matches!(self, Self::UserRequire)
	}

	/// Converts to a number, used for ordering
	fn to_num(&self) -> u8 {
		match self {
			Self::UserRequire => 0,
			Self::Bundled(..) => 1,
			Self::Dependency(..) => 2,
			Self::Refused(..) => 3,
			Self::Repository => 4,
		}
	}
}

impl PkgRequest {
	/// Create a new PkgRequest
	#[inline(always)]
	pub fn new(
		id: impl Into<PackageID>,
		source: PkgRequestSource,
		content_version: VersionPattern,
		repository: Option<String>,
	) -> Self {
		Self {
			id: id.into(),
			source,
			content_version,
			repository,
		}
	}

	/// Create a new PkgRequest that matches all content versions and repositories
	#[inline(always)]
	pub fn any(id: impl Into<PackageID>, source: PkgRequestSource) -> Self {
		Self::new(id, source, VersionPattern::Any, None)
	}

	/// Parse the package name and content version from a string
	pub fn parse(string: impl AsRef<str>, source: PkgRequestSource) -> Self {
		let string = string.as_ref();
		let (id_and_repo, version) = parse_versioned_string(string);

		let (id, repository) = if let Some(pos) = id_and_repo.find(":") {
			let id = &id_and_repo[pos + 1..];
			let repository = &id_and_repo[0..pos];
			// Empty repository should just be none
			(id, Some(repository).filter(|x| !x.is_empty()))
		} else {
			(id_and_repo, None)
		};
		Self {
			source,
			id: id.into(),
			content_version: version,
			repository: repository.map(|x| x.to_string()),
		}
	}

	/// Create a new request with the content version changed
	pub fn with_content_version(&self, content_version: VersionPattern) -> Self {
		Self {
			source: self.source.clone(),
			id: self.id.clone(),
			repository: self.repository.clone(),
			content_version,
		}
	}

	/// Create a dependency list for debugging
	pub fn debug_sources(&self) -> String {
		self.debug_sources_inner(String::new())
	}

	/// Converts to repository:id or id
	pub fn to_string_no_version(&self) -> String {
		if let Some(repo) = &self.repository {
			format!("{repo}:{}", self.id)
		} else {
			self.id.to_string()
		}
	}

	/// Recursive inner function for debugging sources
	fn debug_sources_inner(&self, list: String) -> String {
		match &self.source {
			PkgRequestSource::UserRequire => format!("{}{list}", self.id),
			PkgRequestSource::Dependency(source) => {
				format!("{} -> {}", source.debug_sources_inner(list), self.id)
			}
			PkgRequestSource::Refused(source) => {
				format!("{} =X=> {}", source.debug_sources_inner(list), self.id)
			}
			PkgRequestSource::Bundled(bundler) => {
				format!("{} => {}", bundler.debug_sources_inner(list), self.id)
			}
			PkgRequestSource::Repository => format!("Repository -> {}{list}", self.id),
		}
	}
}

impl PartialEq for PkgRequest {
	fn eq(&self, other: &Self) -> bool {
		self.id == other.id && self.repository == other.repository
	}
}

impl Eq for PkgRequest {}

impl Hash for PkgRequest {
	fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
		self.id.hash(state);
		self.repository.hash(state);
	}
}

impl Display for PkgRequest {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		if let Some(repo) = &self.repository {
			write!(f, "{repo}:")?;
		}
		write!(f, "{}", self.id)
	}
}

/// A PkgRequest wrapped in an Arc
pub type ArcPkgReq = Arc<PkgRequest>;

/// Stability setting for a package
#[derive(Deserialize, Serialize, Default, Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum PackageStability {
	/// Whatever the latest stable version is
	Stable,
	/// Whatever the latest version is
	#[default]
	Latest,
}

impl PackageStability {
	/// Parse a PackageStability from a string
	pub fn parse_from_str(string: &str) -> Option<Self> {
		match string {
			"stable" => Some(Self::Stable),
			"latest" => Some(Self::Latest),
			_ => None,
		}
	}
}

/// The maximum length for a package identifier
pub const MAX_PACKAGE_ID_LENGTH: usize = 32;

/// Checks if a package identifier is valid
pub fn is_valid_package_id(id: &str) -> bool {
	if !is_valid_identifier(id) {
		return false;
	}

	for c in id.chars() {
		if c.is_ascii_uppercase() {
			return false;
		}
		if c == '_' || c == '.' {
			return false;
		}
	}

	if id.len() > MAX_PACKAGE_ID_LENGTH {
		return false;
	}

	true
}

/// Hashes used for package addons
#[derive(Deserialize, Serialize, PartialEq, Debug, Clone, Default)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(default)]
pub struct PackageAddonHashes<T: Default> {
	/// The SHA-256 hash of this addon file
	pub sha256: T,
	/// The SHA-512 hash of this addon file
	pub sha512: T,
}

impl PackageAddonOptionalHashes {
	/// Checks if this set of optional hashes is empty
	pub fn is_empty(&self) -> bool {
		self.sha256.is_none() && self.sha512.is_none()
	}
}

/// Optional PackageAddonHashes
pub type PackageAddonOptionalHashes = PackageAddonHashes<Option<String>>;

/// Different types of packages, mostly AddonKinds
#[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Hash, Debug)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum PackageKind {
	/// A mod package
	Mod,
	/// A resource pack package
	ResourcePack,
	/// A datapack package
	Datapack,
	/// A plugin package
	Plugin,
	/// A shader package
	Shader,
	/// A package that bundles other packages
	Bundle,
}

impl PackageKind {
	/// Converts to an addon kind, if possible
	pub fn to_addon_kind(&self) -> Option<AddonKind> {
		match self {
			Self::Mod => Some(AddonKind::Mod),
			Self::ResourcePack => Some(AddonKind::ResourcePack),
			Self::Datapack => Some(AddonKind::Datapack),
			Self::Plugin => Some(AddonKind::Plugin),
			Self::Shader => Some(AddonKind::Shader),
			Self::Bundle => None,
		}
	}
}

impl FromStr for PackageKind {
	type Err = anyhow::Error;

	fn from_str(s: &str) -> Result<Self, Self::Err> {
		match s {
			"mod" => Ok(Self::Mod),
			"resource_pack" => Ok(Self::ResourcePack),
			"datapack" => Ok(Self::Datapack),
			"plugin" => Ok(Self::Plugin),
			"shader" => Ok(Self::Shader),
			"bundle" => Ok(Self::Bundle),
			other => bail!("Unknown package type '{other}'"),
		}
	}
}

/// Parameters for a package search
#[derive(Serialize, Deserialize, Default, Clone)]
pub struct PackageSearchParameters {
	/// The number of packages to return
	pub count: u8,
	/// How many results to skip
	pub skip: usize,
	/// The fuzzy search term for ids, names, or descriptions
	pub search: Option<String>,
	/// The addon kinds / package types to include
	pub types: Vec<PackageKind>,
	/// The Minecraft versions to include
	pub minecraft_versions: Vec<String>,
	/// The loaders to include
	pub loaders: Vec<Loader>,
	/// The package categories to include
	pub categories: Vec<PackageCategory>,
}

/// A category for a package
#[allow(missing_docs)]
#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum PackageCategory {
	Adventure,
	Atmosphere,
	Audio,
	Blocks,
	Building,
	Cartoon,
	Challenge,
	Combat,
	Compatability,
	Decoration,
	Economy,
	Entities,
	Equipment,
	Exploration,
	Extensive,
	Fantasy,
	Fonts,
	Food,
	GameMechanics,
	Gui,
	Items,
	Language,
	Library,
	Lightweight,
	Magic,
	Minigame,
	Mobs,
	Multiplayer,
	Optimization,
	Realistic,
	Simplistic,
	Space,
	Social,
	Storage,
	Structures,
	Technology,
	Transportation,
	Tweaks,
	Utility,
	VanillaPlus,
	Worldgen,
}

/// Error from package resolution
#[allow(missing_docs)]
#[derive(thiserror::Error, Debug)]
pub enum ResolutionError {
	/// Error that happens when resolving a single package
	#[error("When resolving the package {0}: {1:?}")]
	PackageContext(ArcPkgReq, Box<ResolutionError>),
	#[error("Failed to preload packages")]
	FailedToPreload(anyhow::Error),
	#[error("Failed to get properties of package {0}: {1:?}")]
	FailedToGetProperties(ArcPkgReq, anyhow::Error),
	#[error("No valid versions found for package {0}")]
	NoValidVersionsFound(ArcPkgReq),
	#[error("{pkg} extends the functionality of the package {1}, which is not installed", pkg = .0.as_ref().map(|x| format!("The package {}", x.debug_sources())).unwrap_or("A package".into()))]
	ExtensionNotFulfilled(Option<ArcPkgReq>, ArcPkgReq),
	#[error("Package {0} has been explicitly required by package {1}. This means it must be required by the user in their config.")]
	ExplicitRequireNotFulfilled(ArcPkgReq, ArcPkgReq),
	#[error("Package {0} is incompatible with the packages {refusers}", refusers = .1.iter().join(", "))]
	IncompatiblePackage(ArcPkgReq, Vec<Arc<str>>),
	#[error("Failed to evaluate package {0}: {1:?}")]
	FailedToEvaluate(ArcPkgReq, anyhow::Error),
	#[error("Miscellaneous error: {0:?}")]
	Misc(anyhow::Error),
}

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

	#[test]
	fn test_package_id_validation() {
		assert!(is_valid_package_id("hello"));
		assert!(is_valid_package_id("32"));
		assert!(is_valid_package_id("hello-world"));
		assert!(!is_valid_package_id("hello_world"));
		assert!(!is_valid_package_id("hello.world"));
		assert!(!is_valid_package_id("\\"));
		assert!(!is_valid_package_id(
			"very-very-long-long-long-package-name-thats-too-long"
		));
	}

	#[test]
	fn test_request_source_debug() {
		let req = PkgRequest::parse(
			"foo",
			PkgRequestSource::Dependency(Arc::new(PkgRequest::parse(
				"bar",
				PkgRequestSource::Dependency(Arc::new(PkgRequest::parse(
					"baz",
					PkgRequestSource::Repository,
				))),
			))),
		);
		let debug = req.debug_sources();
		assert_eq!(debug, "Repository -> baz -> bar -> foo");
	}

	#[test]
	fn test_pkg_req_parsing() {
		let req = PkgRequest::parse("foo", PkgRequestSource::UserRequire);
		assert_eq!(req.id, "foo".into());
		assert_eq!(req.repository, None);
		let req = PkgRequest::parse("foo@1.19.2", PkgRequestSource::UserRequire);
		assert_eq!(req.id, "foo".into());
		assert_eq!(req.content_version, VersionPattern::Single("1.19.2".into()));
		let req = PkgRequest::parse("modrinth:foo@1.19.2", PkgRequestSource::UserRequire);
		assert_eq!(req.id, "foo".into());
		assert_eq!(req.repository, Some("modrinth".into()));
		assert_eq!(req.content_version, VersionPattern::Single("1.19.2".into()));
		let req = PkgRequest::parse(":foo", PkgRequestSource::UserRequire);
		assert_eq!(req.id, "foo".into());
		assert_eq!(req.repository, None);

		let _ = PkgRequest::parse(":@", PkgRequestSource::UserRequire);
	}
}