portablemc 5.0.3

Developer-oriented crate for launching Minecraft quickly and reliably with included support for Mojang versions and popular mod loaders. See portablemc-cli for the reference implementation.
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
//! JSON schemas structures for serde deserialization.
//! 
//! This module is internal to the crate and should not be exposed because the format
//! might change with increasing version and bug fixes.

use std::collections::HashMap;
use std::fmt;
use std::path::PathBuf;

use chrono::{DateTime, FixedOffset};

use crate::serde::{HexString, RegexString};
use crate::maven::Gav;


// ================== //
//  VERSION METADATA  //
// ================== //

/// A version metadata JSON schema.
#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct VersionMetadata {
    /// The version id, should be the same as the directory the metadata is in.
    pub id: String,
    /// The version type, such as 'release' or 'snapshot'.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub r#type: Option<VersionType>,
    /// The last time this version has been updated.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub time: Option<DateTimeChill>,
    /// The first release time of this version.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub release_time: Option<DateTimeChill>,
    /// If present, this is the name of another version to resolve after this one and
    /// where fallback values will be taken.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub inherits_from: Option<String>,
    /// Used by official launcher, optional.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub minimum_launcher_version: Option<u32>,
    /// Describe the Java version to use, optional.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub java_version: Option<VersionJavaVersion>,
    /// The asset index to use when launching the game, it also has download information.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub asset_index: Option<VersionAssetIndex>,
    /// Legacy asset index id without download information.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub assets: Option<String>,
    /// Unknown, used by official launcher.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub compliance_level: Option<u32>,
    /// A mapping of downloads for entry point JAR files, such as for client or for 
    /// server. This sometime also defines a server executable for old versions.
    #[serde(default)]
    #[serde(skip_serializing_if = "HashMap::is_empty")]
    pub downloads: HashMap<String, Download>,
    /// The sequence of JAR libraries to include in the class path when running the
    /// version, the order of libraries should be respected in the class path (for
    /// some corner cases with mod loaders). When a library is defined, it can't be
    /// overridden by inherited versions.
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub libraries: Vec<VersionLibrary>,
    /// The full class name to run as the main JVM class.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub main_class: Option<String>,
    /// Legacy arguments command line.
    #[serde(rename = "minecraftArguments")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub legacy_arguments: Option<String>,
    /// Modern arguments for game and/or jvm.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub arguments: Option<VersionArguments>,
    /// Logging configuration.
    #[serde(default)]
    #[serde(skip_serializing_if = "HashMap::is_empty")]
    pub logging: HashMap<String, VersionLogging>,
}

#[derive(serde::Deserialize, serde::Serialize, Debug, Copy, Clone, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum VersionType {
    Release,
    Snapshot,
    OldBeta,
    OldAlpha,
}

impl VersionType {

    pub fn as_str(&self) -> &'static str {
        match self {
            VersionType::Release => "release",
            VersionType::Snapshot => "snapshot",
            VersionType::OldBeta => "old_beta",
            VersionType::OldAlpha => "old_alpha",
        }
    }

}

/// Object describing the Mojang-provided Java version to use to launch the game.
#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct VersionJavaVersion {
    pub component: Option<String>,
    pub major_version: u32,
}

/// Describe the asset index to use and how to download it when missing.
#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct VersionAssetIndex {
    pub id: String,
    pub total_size: u32,
    #[serde(flatten)]
    pub download: Download,
}

#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct VersionLibrary {
    pub name: Gav,
    #[serde(default)]
    #[serde(skip_serializing_if = "VersionLibraryDownloads::is_empty")]
    pub downloads: VersionLibraryDownloads,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub natives: Option<HashMap<String, String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rules: Option<Vec<Rule>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
}

#[derive(serde::Deserialize, serde::Serialize, Debug, Default, Clone)]
#[serde(rename_all = "camelCase")]
pub struct VersionLibraryDownloads {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub artifact: Option<VersionLibraryDownload>,
    #[serde(default)]
    #[serde(skip_serializing_if = "HashMap::is_empty")]
    pub classifiers: HashMap<String, VersionLibraryDownload>,
}

impl VersionLibraryDownloads {
    fn is_empty(&self) -> bool {
        self.artifact.is_none() && self.classifiers.is_empty()
    }
}

#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct VersionLibraryDownload {
    pub path: Option<PathBuf>,
    #[serde(flatten)]
    pub download: Download,
}

#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct VersionArguments {
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub game: Vec<VersionArgument>,
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub jvm: Vec<VersionArgument>,
}

#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
#[serde(untagged)]
pub enum VersionArgument {
    Raw(String),
    Conditional(VersionConditionalArgument),
}

#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct VersionConditionalArgument {
    pub value: SingleOrVec<String>,
    pub rules: Option<Vec<Rule>>,
}

#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct VersionLogging {
    #[serde(default)]
    pub r#type: VersionLoggingType,
    pub argument: String,
    pub file: VersionLoggingFile,
}

#[derive(serde::Deserialize, serde::Serialize, Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum VersionLoggingType {
    #[default]
    #[serde(rename = "log4j2-xml")]
    Log4j2Xml,
}

#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct VersionLoggingFile {
    pub id: String,
    #[serde(flatten)]
    pub download: Download,
}


// ================== //
//    ASSET INDEX     //
// ================== //

#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
pub struct AssetIndex {
    /// For version <= 13w23b (1.6.1).
    #[serde(default)]
    pub map_to_resources: bool,
    /// For 13w23b (1.6.1) < version <= 13w48b (1.7.2).
    #[serde(default)]
    pub r#virtual: bool,
    /// Mapping of assets from their real path to their download information.
    pub objects: HashMap<String, AssetObject>,
}

#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
pub struct AssetObject {
    pub size: u32,
    pub hash: HexString<20>,
}

// ================== //
//   JVM MANIFESTS    //
// ================== //

#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
#[serde(transparent)]
pub struct JvmMetaManifest {
    pub platforms: HashMap<String, JvmMetaManifestPlatform>,
}

#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
#[serde(transparent)]
pub struct JvmMetaManifestPlatform {
    pub distributions: HashMap<String, JvmMetaManifestDistribution>,
}

#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
#[serde(transparent)]
pub struct JvmMetaManifestDistribution {
    pub variants: Vec<JvmMetaManifestVariant>,
}

#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
pub struct JvmMetaManifestVariant {
    pub availability: JvmMetaManifestAvailability,
    pub manifest: Download,
    pub version: JvmMetaManifestVersion,
}

#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
pub struct JvmMetaManifestAvailability {
    pub group: u32,
    pub progress: u8,
}

#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
pub struct JvmMetaManifestVersion {
    pub name: String,
    pub released: DateTime<FixedOffset>,
}

#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
pub struct JvmManifest {
    pub files: HashMap<String, JvmManifestFile>,
}

#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
#[serde(rename_all = "lowercase", tag = "type")] // Internally tagged.
pub enum JvmManifestFile {
    Directory,
    File {
        #[serde(default)]
        executable: bool,
        downloads: JvmManifestFileDownloads,
    },
    Link {
        target: String,
    },
}

#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
pub struct JvmManifestFileDownloads {
    pub raw: Download,
    pub lzma: Option<Download>,
}

// ================== //
//       COMMON       //
// ================== //

#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Rule {
    pub action: RuleAction,
    #[serde(default)]
    pub os: RuleOs,
    #[serde(default)]
    pub features: HashMap<String, bool>,
}

#[derive(serde::Deserialize, serde::Serialize, Debug, Default, Clone)]
#[serde(rename_all = "camelCase")]
pub struct RuleOs {
    pub name: Option<String>,
    pub arch: Option<String>,
    /// Only known value to use regex.
    pub version: Option<RegexString>,
}

#[derive(serde::Deserialize, serde::Serialize, Debug, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum RuleAction {
    Allow,
    Disallow,
}

#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
pub struct Download {
    pub url: String,
    pub size: Option<u32>,
    pub sha1: Option<HexString<20>>,
}

#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
#[serde(untagged)]
pub enum SingleOrVec<T> {
    Single(T),
    Vec(Vec<T>)
}

/// Internal serde structure for RFC3339 date time parsing, specifically for 
/// [`VersionMetadata`] because it appears that some metadata might contain malformed
/// date time that we don't want to error. 
/// 
/// This as been observed with NeoForge installer embedded version, an example of 
/// malformed time is "2024-12-09T23:22:49.408008176", where the timezone is missing.
/// 
/// On old Forge versions there is also a missing ':' in the timezone offset between
/// hours and minutes.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct DateTimeChill(pub DateTime<FixedOffset>);

impl<'de> serde::Deserialize<'de> for DateTimeChill {

    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        
        use chrono::format::ParseErrorKind;

        struct Visitor;
        impl serde::de::Visitor<'_> for Visitor {

            type Value = DateTimeChill;
            
            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("an RFC 3339 formatted date and time string")
            }

            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {

                let err;
                let mut buf;

                match DateTime::parse_from_rfc3339(v) {
                    Ok(date) => return Ok(DateTimeChill(date)),
                    Err(e) if e.kind() == ParseErrorKind::TooShort => {
                        // Try adding a 'Z' at the end, we don't know if this was the issue 
                        // so we retry.
                        err = e;
                        buf = v.to_string();
                        buf.push('Z');
                    }
                    Err(e) if e.kind() == ParseErrorKind::Invalid => {
                        if let Some(index) = v.rfind(&['+', '-']) {
                            // This order avoids overflows.
                            if v.len() - index == 5 && v[v.len() - 4..].is_ascii() {
                                err = e;
                                buf = v.to_string();
                                buf.insert(v.len() - 2, ':');
                            } else {
                                return Err(E::custom(e));
                            }
                        } else {
                            return Err(E::custom(e));
                        }
                    }
                    Err(e) => return Err(E::custom(e)),
                };

                match DateTime::parse_from_rfc3339(&buf) {
                    Ok(date) => Ok(DateTimeChill(date)),
                    Err(_) => Err(E::custom(err)), // Return the original error!!
                }

            }
            
        }

        deserializer.deserialize_str(Visitor)
        
    }

}

impl serde::Serialize for DateTimeChill {

    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        self.0.serialize(serializer)
    }

}