nitro_config 0.28.0

Serialization for Nitrolaunch configuration
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
use std::collections::HashMap;
use std::path::{Path, PathBuf};

use anyhow::Context;
use nitro_pkg::overrides::PackageOverrides;
use nitro_shared::addon::AddonKind;
use nitro_shared::java_args::MemoryNum;
use nitro_shared::loaders::Loader;
use nitro_shared::pkg::PackageStability;
use nitro_shared::util::{merge_options, DefaultExt, DeserListOrSingle};
use nitro_shared::versions::{MinecraftVersionDeser, VersionInfo, VersionPattern};
use nitro_shared::Side;
#[cfg(feature = "schema")]
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use super::package::PackageConfigDeser;

/// Configuration for an instance
#[derive(Deserialize, Serialize, Clone, Debug, Default)]
#[serde(default)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
pub struct InstanceConfig {
	/// One or more templates to use
	#[serde(skip_serializing_if = "DeserListOrSingle::is_empty")]
	pub from: DeserListOrSingle<String>,
	/// The type or side of this instance
	#[serde(rename = "type")]
	pub side: Option<Side>,
	/// The display name of this instance
	#[serde(skip_serializing_if = "Option::is_none")]
	pub name: Option<String>,
	/// A path to an icon file for this instance
	#[serde(skip_serializing_if = "Option::is_none")]
	pub icon: Option<String>,
	/// The Minecraft version
	#[serde(skip_serializing_if = "Option::is_none")]
	pub version: Option<MinecraftVersionDeser>,
	/// Configured loader
	#[serde(skip_serializing_if = "DefaultExt::is_default")]
	pub loader: Option<String>,
	/// Default stability setting of packages on this instance
	#[serde(skip_serializing_if = "DefaultExt::is_default")]
	pub package_stability: Option<PackageStability>,
	/// Launch configuration
	#[serde(skip_serializing_if = "DefaultExt::is_default")]
	pub launch: LaunchConfig,
	/// The folder for global datapacks to be installed to
	#[serde(skip_serializing_if = "Option::is_none")]
	pub datapack_folder: Option<String>,
	/// Packages for this instance
	#[serde(skip_serializing_if = "Vec::is_empty")]
	pub packages: Vec<PackageConfigDeser>,
	/// Overrides for packages on this instance
	#[serde(skip_serializing_if = "DefaultExt::is_default")]
	pub overrides: PackageOverrides,
	/// Override for the game file directory for this instance
	#[serde(skip_serializing_if = "Option::is_none")]
	pub game_dir: Option<String>,
	/// Window configuration
	#[serde(skip_serializing_if = "DefaultExt::is_default")]
	pub window: ClientWindowConfig,
	/// Whether this config was created by a plugin
	#[serde(skip_serializing_if = "DefaultExt::is_default")]
	pub from_plugin: bool,
	/// Whether to use a plugin to custom launch this instance. Should only be set by plugins.
	#[serde(skip_serializing_if = "DefaultExt::is_default")]
	pub custom_launch: bool,
	/// Whether this instance was imported
	#[serde(skip_serializing_if = "DefaultExt::is_default")]
	pub imported: bool,
	/// Config for plugins
	#[serde(skip_serializing_if = "serde_json::Map::is_empty")]
	pub plugin_config: serde_json::Map<String, serde_json::Value>,
}

impl InstanceConfig {
	/// Merge this config with another one, with right side taking precendence
	pub fn merge(&mut self, other: Self) {
		self.from.merge(other.from);
		if other.name.is_some() {
			self.name = other.name;
		}
		self.version = other.version.or(self.version.clone());
		self.loader = other.loader.or(self.loader.clone());
		self.package_stability = other.package_stability.or(self.package_stability);
		self.launch.merge(other.launch);
		self.datapack_folder = other.datapack_folder.or(self.datapack_folder.clone());
		self.packages.extend(other.packages);
		self.overrides.suppress.extend(other.overrides.suppress);
		nitro_shared::util::merge_json_objects(&mut self.plugin_config, other.plugin_config);
		self.icon = other.icon.or(self.icon.clone());
		self.side = other.side.or(self.side);
		self.window.merge(other.window);
		self.from_plugin = other.from_plugin;
	}
}

/// Different representations for JVM / game arguments
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(untagged)]
pub enum Args {
	/// A list of separate arguments
	List(Vec<String>),
	/// A single string of arguments
	String(String),
}

impl Args {
	/// Parse the arguments into a vector
	pub fn parse(&self) -> Vec<String> {
		match self {
			Self::List(vec) => vec.clone(),
			Self::String(string) => string.split(' ').map(|string| string.to_string()).collect(),
		}
	}

	/// Merge Args
	pub fn merge(&mut self, other: Self) {
		let mut out = self.parse();
		out.extend(other.parse());
		*self = Self::List(out);
	}
}

impl Default for Args {
	fn default() -> Self {
		Self::List(Vec::new())
	}
}

/// Arguments for the process when launching
#[derive(Deserialize, Serialize, Debug, Default, Clone, PartialEq)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
pub struct LaunchArgs {
	/// Arguments for the JVM
	#[serde(default)]
	#[serde(skip_serializing_if = "DefaultExt::is_default")]
	pub jvm: Args,
	/// Arguments for the game
	#[serde(default)]
	#[serde(skip_serializing_if = "DefaultExt::is_default")]
	pub game: Args,
}

/// Different representations of both memory arguments for the JVM
#[derive(Deserialize, Serialize, Debug, Default, Clone, PartialEq)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(untagged)]
pub enum LaunchMemory {
	/// No memory arguments
	#[default]
	None,
	/// A single memory argument shared for both
	Single(String),
	/// Different memory arguments for both
	Both {
		/// The minimum memory
		min: String,
		/// The maximum memory
		max: String,
	},
}

impl LaunchMemory {
	/// Parse this memory as a minimum and maximum memory
	pub fn to_min_max(self) -> (Option<MemoryNum>, Option<MemoryNum>) {
		let min_mem = match &self {
			LaunchMemory::None => None,
			LaunchMemory::Single(string) => MemoryNum::parse(string),
			LaunchMemory::Both { min, .. } => MemoryNum::parse(min),
		};
		let max_mem = match &self {
			LaunchMemory::None => None,
			LaunchMemory::Single(string) => MemoryNum::parse(string),
			LaunchMemory::Both { max, .. } => MemoryNum::parse(max),
		};

		(min_mem, max_mem)
	}
}

/// Options for the Minecraft QuickPlay feature
#[derive(Deserialize, Serialize, Debug, PartialEq, Default, Clone)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "type")]
#[serde(rename_all = "snake_case")]
pub enum QuickPlay {
	/// QuickPlay a world
	World {
		/// The world to play
		world: String,
	},
	/// QuickPlay a server
	Server {
		/// The server address to join
		server: String,
		/// The port for the server to connect to
		port: Option<u16>,
	},
	/// QuickPlay a realm
	Realm {
		/// The realm name to join
		realm: String,
	},
	/// Don't do any QuickPlay
	#[default]
	None,
}

/// Configuration for the launching of the game
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
pub struct LaunchConfig {
	/// The arguments for the process
	#[serde(default)]
	#[serde(skip_serializing_if = "DefaultExt::is_default")]
	pub args: LaunchArgs,
	/// JVM memory options
	#[serde(default)]
	#[serde(skip_serializing_if = "DefaultExt::is_default")]
	pub memory: LaunchMemory,
	/// The java installation to use
	#[serde(default)]
	pub java: Option<String>,
	/// Environment variables
	#[serde(default)]
	#[serde(skip_serializing_if = "HashMap::is_empty")]
	pub env: HashMap<String, String>,
	/// A wrapper command
	#[serde(default)]
	#[serde(skip_serializing_if = "Option::is_none")]
	pub wrapper: Option<WrapperCommand>,
	/// QuickPlay options
	#[serde(default)]
	#[serde(skip_serializing_if = "DefaultExt::is_default")]
	pub quick_play: QuickPlay,
	/// Whether or not to use the Log4J configuration
	#[serde(default)]
	#[serde(skip_serializing_if = "DefaultExt::is_default")]
	pub use_log4j_config: bool,
}

impl LaunchConfig {
	/// Merge multiple LaunchConfigs
	pub fn merge(&mut self, other: Self) -> &mut Self {
		self.args.jvm.merge(other.args.jvm);
		self.args.game.merge(other.args.game);
		if !matches!(other.memory, LaunchMemory::None) {
			self.memory = other.memory;
		}
		if other.java.is_some() {
			self.java = other.java;
		}
		self.env.extend(other.env);
		if other.wrapper.is_some() {
			self.wrapper = other.wrapper;
		}
		if !matches!(other.quick_play, QuickPlay::None) {
			self.quick_play = other.quick_play;
		}

		self
	}
}

impl Default for LaunchConfig {
	fn default() -> Self {
		Self {
			args: LaunchArgs {
				jvm: Args::default(),
				game: Args::default(),
			},
			memory: LaunchMemory::default(),
			java: None,
			env: HashMap::new(),
			wrapper: None,
			quick_play: QuickPlay::default(),
			use_log4j_config: false,
		}
	}
}

/// A wrapper command
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
pub struct WrapperCommand {
	/// The command to run
	pub cmd: String,
	/// The command's arguments
	#[serde(default)]
	pub args: Vec<String>,
}

/// Resolution for a client window
#[derive(Deserialize, Serialize, Clone, Debug, Copy, PartialEq)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
pub struct WindowResolution {
	/// The width of the window
	pub width: u32,
	/// The height of the window
	pub height: u32,
}

/// Configuration for the client window
#[derive(Deserialize, Serialize, Default, Clone, Debug, PartialEq)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(default)]
pub struct ClientWindowConfig {
	/// The resolution of the window
	#[serde(skip_serializing_if = "Option::is_none")]
	pub resolution: Option<WindowResolution>,
}

impl ClientWindowConfig {
	/// Merge two ClientWindowConfigs
	pub fn merge(&mut self, other: Self) -> &mut Self {
		self.resolution = merge_options(self.resolution, other.resolution);
		self
	}
}

/// Checks if an instance ID is valid
pub fn is_valid_instance_id(id: &str) -> bool {
	for c in id.chars() {
		if !c.is_ascii() {
			return false;
		}

		if c.is_ascii_punctuation() {
			match c {
				'_' | '-' | '.' | ':' => {}
				_ => return false,
			}
		}

		if c.is_ascii_whitespace() {
			return false;
		}
	}

	true
}

/// Converts a string into a valid instance ID
/// Special characters will be converted into hyphens
pub fn make_valid_instance_id(string: &str) -> String {
	let string = string.to_lowercase();
	string
		.chars()
		.map(|c| {
			if !c.is_ascii_alphanumeric() && c != '.' && c != ':' {
				'-'
			} else {
				c
			}
		})
		.collect()
}

/// Check if a loader can be installed by Nitrolaunch
pub fn can_install_loader(loader: &Loader) -> bool {
	matches!(loader, Loader::Vanilla)
}

/// Get the paths on an instance to put addons in
pub fn get_addon_paths(
	instance: &InstanceConfig,
	game_dir: &Path,
	addon: AddonKind,
	selected_worlds: &[String],
	version_info: &VersionInfo,
) -> anyhow::Result<Vec<PathBuf>> {
	let side = instance.side.context("Instance side missing")?;
	Ok(match addon {
		AddonKind::ResourcePack => {
			if side == Side::Client {
				// Resource packs are texture packs on older versions
				if VersionPattern::After("13w24a".into()).matches_info(version_info) {
					vec![game_dir.join("resourcepacks")]
				} else {
					vec![game_dir.join("texturepacks")]
				}
			} else {
				vec![game_dir.join("resourcepacks")]
			}
		}
		AddonKind::Mod => vec![game_dir.join("mods")],
		AddonKind::Plugin => {
			if side == Side::Server {
				vec![game_dir.join("plugins")]
			} else {
				vec![]
			}
		}
		AddonKind::Shader => {
			if side == Side::Client {
				vec![game_dir.join("shaderpacks")]
			} else {
				vec![]
			}
		}
		AddonKind::Datapack => {
			if let Some(datapack_folder) = &instance.datapack_folder {
				vec![game_dir.join(datapack_folder)]
			} else {
				match side {
					Side::Client => {
						if selected_worlds.is_empty() {
							vec![game_dir.join("world_files/datapacks")]
						} else {
							selected_worlds
								.iter()
								.map(|x| game_dir.join("saves").join(x).join("datapacks"))
								.collect()
						}
					}
					Side::Server => {
						// TODO: Support custom world names
						vec![game_dir.join("world").join("datapacks")]
					}
				}
			}
		}
	})
}