added: launch_profile foundation primitives (rules, templates, model)
introduce the launch_profile module with the core types and pure functions
needed to parse, evaluate, and substitute against mojang-format version
JSON: Rule/OsCondition/FeatureSet with a single rule evaluator,
TemplateContext + substitute() for ${var} expansion, and the
LaunchProfile schema mirroring mojang's on-disk shape. no consumers yet.
This commit is contained in:
1 parent
50e31f38bb
commit
22e4481a2b
5 files changed
+853
No files matched your search
@@ -0,0 +1,10 @@
|
||||
// foundation primitives for parsing, merging, and rendering mojang-format
|
||||
// launch profiles. consumed by the vanilla launcher, forge/neoforge,
|
||||
// fabric/quilt - anything that reads a mojang-style version JSON.
|
||||
//
|
||||
// phase 1 is pure additions: no consumers yet. later phases will wire
|
||||
// these primitives into the launch pipeline and the installer paths.
|
||||
|
||||
pub mod model;
|
||||
pub mod rules;
|
||||
pub mod templates;
|
||||
@@ -0,0 +1,278 @@
|
||||
// mojang-format launch profile types. mirrors the on-disk JSON schema
|
||||
// used by vanilla versions, forge installer output, neoforge installer
|
||||
// output, fabric profiles, and quilt profiles. parsing is lossless for
|
||||
// the fields we care about; unknown fields are silently dropped (serde
|
||||
// default behavior) - which is fine because we write upstream JSON
|
||||
// byte-for-byte on the install side.
|
||||
//
|
||||
// no consumers yet. phase 2 wires this into the vanilla launch path;
|
||||
// phase 3 adds inheritsFrom resolution; phase 4 swaps the forge/neoforge
|
||||
// installer profile writer over to use this shape.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::rules::Rule;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct LaunchProfile {
|
||||
pub id: String,
|
||||
pub inherits_from: Option<String>,
|
||||
pub main_class: Option<String>,
|
||||
#[serde(default)]
|
||||
pub libraries: Vec<Library>,
|
||||
pub arguments: Option<Arguments>,
|
||||
pub minecraft_arguments: Option<String>,
|
||||
pub asset_index: Option<AssetIndex>,
|
||||
pub assets: Option<String>,
|
||||
pub java_version: Option<JavaVersion>,
|
||||
pub downloads: Option<VersionDownloads>,
|
||||
pub release_time: Option<String>,
|
||||
pub time: Option<String>,
|
||||
#[serde(rename = "type")]
|
||||
pub type_: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Default, Deserialize, Serialize)]
|
||||
pub struct Arguments {
|
||||
#[serde(default)]
|
||||
pub game: Vec<Argument>,
|
||||
#[serde(default)]
|
||||
pub jvm: Vec<Argument>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
|
||||
#[serde(untagged)]
|
||||
pub enum Argument {
|
||||
Literal(String),
|
||||
Conditional {
|
||||
rules: Vec<Rule>,
|
||||
value: ArgumentValue,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
|
||||
#[serde(untagged)]
|
||||
pub enum ArgumentValue {
|
||||
Single(String),
|
||||
Multiple(Vec<String>),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
|
||||
pub struct Library {
|
||||
pub name: String,
|
||||
pub downloads: Option<LibraryDownloads>,
|
||||
pub rules: Option<Vec<Rule>>,
|
||||
pub url: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
|
||||
pub struct LibraryDownloads {
|
||||
pub artifact: Option<Artifact>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
|
||||
pub struct Artifact {
|
||||
pub url: String,
|
||||
pub path: String,
|
||||
pub sha1: String,
|
||||
pub size: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
|
||||
pub struct AssetIndex {
|
||||
pub id: String,
|
||||
pub url: String,
|
||||
pub sha1: String,
|
||||
pub size: Option<u64>,
|
||||
pub total_size: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct JavaVersion {
|
||||
pub component: Option<String>,
|
||||
pub major_version: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
|
||||
pub struct VersionDownloads {
|
||||
pub client: Download,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
|
||||
pub struct Download {
|
||||
pub url: String,
|
||||
pub sha1: String,
|
||||
pub size: u64,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::launch_profile::rules::RuleAction;
|
||||
|
||||
const MODERN_FIXTURE: &str = r#"{
|
||||
"id": "1.20.1",
|
||||
"type": "release",
|
||||
"mainClass": "net.minecraft.client.main.Main",
|
||||
"assetIndex": {
|
||||
"id": "5",
|
||||
"url": "https://example.invalid/5.json",
|
||||
"sha1": "0000000000000000000000000000000000000000"
|
||||
},
|
||||
"javaVersion": {
|
||||
"component": "java-runtime-gamma",
|
||||
"majorVersion": 17
|
||||
},
|
||||
"libraries": [
|
||||
{
|
||||
"name": "org.lwjgl:lwjgl:3.3.1",
|
||||
"downloads": {
|
||||
"artifact": {
|
||||
"url": "https://example.invalid/lwjgl.jar",
|
||||
"path": "org/lwjgl/lwjgl/3.3.1/lwjgl-3.3.1.jar",
|
||||
"sha1": "1111111111111111111111111111111111111111",
|
||||
"size": 100
|
||||
}
|
||||
},
|
||||
"rules": [
|
||||
{ "action": "allow", "os": { "name": "linux" } }
|
||||
]
|
||||
}
|
||||
],
|
||||
"arguments": {
|
||||
"game": [
|
||||
"--username", "${auth_player_name}",
|
||||
{
|
||||
"rules": [{ "action": "allow", "features": { "is_demo_user": true } }],
|
||||
"value": "--demo"
|
||||
}
|
||||
],
|
||||
"jvm": [
|
||||
"-Djava.library.path=${natives_directory}",
|
||||
{
|
||||
"rules": [{ "action": "allow", "os": { "name": "osx" } }],
|
||||
"value": ["-XstartOnFirstThread"]
|
||||
}
|
||||
]
|
||||
}
|
||||
}"#;
|
||||
|
||||
const LEGACY_FIXTURE: &str = r#"{
|
||||
"id": "1.7.10",
|
||||
"type": "release",
|
||||
"mainClass": "net.minecraft.client.main.Main",
|
||||
"minecraftArguments": "--username ${auth_player_name} --version ${version_name} --gameDir ${game_directory}",
|
||||
"assetIndex": {
|
||||
"id": "1.7.10",
|
||||
"url": "https://example.invalid/1.7.10.json",
|
||||
"sha1": "0000000000000000000000000000000000000000"
|
||||
},
|
||||
"libraries": []
|
||||
}"#;
|
||||
|
||||
const LOADER_FIXTURE: &str = r#"{
|
||||
"id": "1.20.1-forge-47.2.0",
|
||||
"inheritsFrom": "1.20.1",
|
||||
"mainClass": "cpw.mods.bootstraplauncher.BootstrapLauncher",
|
||||
"libraries": [
|
||||
{ "name": "net.minecraftforge:forge:47.2.0" }
|
||||
],
|
||||
"arguments": {
|
||||
"game": ["--launchTarget", "forge_client"],
|
||||
"jvm": [
|
||||
"--add-opens", "java.base/sun.security.util=cpw.mods.securejarhandler",
|
||||
"-DlibraryDirectory=${library_directory}"
|
||||
]
|
||||
}
|
||||
}"#;
|
||||
|
||||
#[test]
|
||||
fn parses_modern_arguments_object() {
|
||||
let profile: LaunchProfile = serde_json::from_str(MODERN_FIXTURE).unwrap();
|
||||
assert_eq!(profile.id, "1.20.1");
|
||||
assert_eq!(
|
||||
profile.main_class.as_deref(),
|
||||
Some("net.minecraft.client.main.Main")
|
||||
);
|
||||
assert!(profile.inherits_from.is_none());
|
||||
assert!(profile.minecraft_arguments.is_none());
|
||||
|
||||
let args = profile.arguments.as_ref().expect("arguments present");
|
||||
assert_eq!(args.game.len(), 3);
|
||||
assert_eq!(args.jvm.len(), 2);
|
||||
|
||||
// first game arg should be a literal "--username"
|
||||
match &args.game[0] {
|
||||
Argument::Literal(s) => assert_eq!(s, "--username"),
|
||||
_ => panic!("expected literal"),
|
||||
}
|
||||
// third game arg should be a conditional with a single-string value
|
||||
match &args.game[2] {
|
||||
Argument::Conditional { rules, value } => {
|
||||
assert_eq!(rules.len(), 1);
|
||||
assert_eq!(rules[0].action, RuleAction::Allow);
|
||||
assert!(matches!(value, ArgumentValue::Single(_)));
|
||||
}
|
||||
_ => panic!("expected conditional"),
|
||||
}
|
||||
// second jvm arg should be a conditional with a multi-string value
|
||||
match &args.jvm[1] {
|
||||
Argument::Conditional { value, .. } => {
|
||||
assert!(matches!(value, ArgumentValue::Multiple(_)));
|
||||
}
|
||||
_ => panic!("expected conditional"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_legacy_minecraft_arguments_string() {
|
||||
let profile: LaunchProfile = serde_json::from_str(LEGACY_FIXTURE).unwrap();
|
||||
assert_eq!(profile.id, "1.7.10");
|
||||
assert!(profile.arguments.is_none());
|
||||
assert!(
|
||||
profile
|
||||
.minecraft_arguments
|
||||
.as_deref()
|
||||
.unwrap()
|
||||
.contains("${version_name}")
|
||||
);
|
||||
assert!(profile.libraries.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_loader_profile_with_inherits_from() {
|
||||
let profile: LaunchProfile = serde_json::from_str(LOADER_FIXTURE).unwrap();
|
||||
assert_eq!(profile.id, "1.20.1-forge-47.2.0");
|
||||
assert_eq!(profile.inherits_from.as_deref(), Some("1.20.1"));
|
||||
assert!(profile.asset_index.is_none()); // inherited from parent
|
||||
let args = profile.arguments.as_ref().unwrap();
|
||||
assert_eq!(args.game.len(), 2);
|
||||
assert_eq!(args.jvm.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modern_profile_round_trips() {
|
||||
let original: LaunchProfile = serde_json::from_str(MODERN_FIXTURE).unwrap();
|
||||
let serialized = serde_json::to_string(&original).unwrap();
|
||||
let reparsed: LaunchProfile = serde_json::from_str(&serialized).unwrap();
|
||||
assert_eq!(original, reparsed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loader_profile_round_trips() {
|
||||
let original: LaunchProfile = serde_json::from_str(LOADER_FIXTURE).unwrap();
|
||||
let serialized = serde_json::to_string(&original).unwrap();
|
||||
let reparsed: LaunchProfile = serde_json::from_str(&serialized).unwrap();
|
||||
assert_eq!(original, reparsed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_profile_round_trips() {
|
||||
let original: LaunchProfile = serde_json::from_str(LEGACY_FIXTURE).unwrap();
|
||||
let serialized = serde_json::to_string(&original).unwrap();
|
||||
let reparsed: LaunchProfile = serde_json::from_str(&serialized).unwrap();
|
||||
assert_eq!(original, reparsed);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
// mojang rule evaluation. profiles, libraries, and argument entries can
|
||||
// carry conditional rules that filter them by OS, architecture, or feature
|
||||
// flags. this module is the single source of truth for that semantics -
|
||||
// see `evaluate` below for the exact rules.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum RuleAction {
|
||||
Allow,
|
||||
Disallow,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Default, Deserialize, Serialize)]
|
||||
pub struct OsCondition {
|
||||
pub name: Option<String>,
|
||||
pub arch: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Default, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub struct FeatureSet {
|
||||
pub is_demo_user: Option<bool>,
|
||||
pub has_custom_resolution: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
|
||||
pub struct Rule {
|
||||
pub action: RuleAction,
|
||||
pub os: Option<OsCondition>,
|
||||
pub features: Option<FeatureSet>,
|
||||
}
|
||||
|
||||
pub struct RuleContext<'a> {
|
||||
pub os_name: &'a str,
|
||||
pub arch: &'a str,
|
||||
pub features: &'a FeatureSet,
|
||||
}
|
||||
|
||||
pub fn evaluate(rules: &[Rule], ctx: &RuleContext) -> bool {
|
||||
if rules.is_empty() {
|
||||
return true;
|
||||
}
|
||||
let mut allowed = false;
|
||||
for rule in rules {
|
||||
if rule_matches(rule, ctx) {
|
||||
allowed = matches!(rule.action, RuleAction::Allow);
|
||||
}
|
||||
}
|
||||
allowed
|
||||
}
|
||||
|
||||
fn rule_matches(rule: &Rule, ctx: &RuleContext) -> bool {
|
||||
if let Some(os) = &rule.os {
|
||||
if let Some(name) = &os.name
|
||||
&& name != ctx.os_name
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if let Some(arch) = &os.arch
|
||||
&& arch != ctx.arch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if let Some(required) = &rule.features
|
||||
&& !features_match(required, ctx.features)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn features_match(required: &FeatureSet, current: &FeatureSet) -> bool {
|
||||
if let Some(want) = required.is_demo_user
|
||||
&& current.is_demo_user.unwrap_or(false) != want
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if let Some(want) = required.has_custom_resolution
|
||||
&& current.has_custom_resolution.unwrap_or(false) != want
|
||||
{
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn linux_ctx<'a>(features: &'a FeatureSet) -> RuleContext<'a> {
|
||||
RuleContext {
|
||||
os_name: "linux",
|
||||
arch: "x86_64",
|
||||
features,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_rules_allow() {
|
||||
let features = FeatureSet::default();
|
||||
let ctx = linux_ctx(&features);
|
||||
assert!(evaluate(&[], &ctx));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_allow_matching_os_allows() {
|
||||
let rules = vec![Rule {
|
||||
action: RuleAction::Allow,
|
||||
os: Some(OsCondition {
|
||||
name: Some("linux".into()),
|
||||
arch: None,
|
||||
}),
|
||||
features: None,
|
||||
}];
|
||||
let features = FeatureSet::default();
|
||||
let ctx = linux_ctx(&features);
|
||||
assert!(evaluate(&rules, &ctx));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_disallow_matching_os_disallows() {
|
||||
let rules = vec![Rule {
|
||||
action: RuleAction::Disallow,
|
||||
os: Some(OsCondition {
|
||||
name: Some("linux".into()),
|
||||
arch: None,
|
||||
}),
|
||||
features: None,
|
||||
}];
|
||||
let features = FeatureSet::default();
|
||||
let ctx = linux_ctx(&features);
|
||||
assert!(!evaluate(&rules, &ctx));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn allow_without_os_match_disallows_by_default() {
|
||||
// explicit allow for windows; we are on linux; nothing matches;
|
||||
// default state remains disallow.
|
||||
let rules = vec![Rule {
|
||||
action: RuleAction::Allow,
|
||||
os: Some(OsCondition {
|
||||
name: Some("windows".into()),
|
||||
arch: None,
|
||||
}),
|
||||
features: None,
|
||||
}];
|
||||
let features = FeatureSet::default();
|
||||
let ctx = linux_ctx(&features);
|
||||
assert!(!evaluate(&rules, &ctx));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn last_matching_rule_wins_when_allow_then_disallow() {
|
||||
let rules = vec![
|
||||
Rule {
|
||||
action: RuleAction::Allow,
|
||||
os: None,
|
||||
features: None,
|
||||
},
|
||||
Rule {
|
||||
action: RuleAction::Disallow,
|
||||
os: Some(OsCondition {
|
||||
name: Some("osx".into()),
|
||||
arch: None,
|
||||
}),
|
||||
features: None,
|
||||
},
|
||||
];
|
||||
let features = FeatureSet::default();
|
||||
let osx_ctx = RuleContext {
|
||||
os_name: "osx",
|
||||
arch: "x86_64",
|
||||
features: &features,
|
||||
};
|
||||
assert!(!evaluate(&rules, &osx_ctx));
|
||||
// and on linux: only the first rule matches → still allow.
|
||||
let lin = linux_ctx(&features);
|
||||
assert!(evaluate(&rules, &lin));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn last_matching_rule_wins_when_disallow_then_allow() {
|
||||
let rules = vec![
|
||||
Rule {
|
||||
action: RuleAction::Disallow,
|
||||
os: None,
|
||||
features: None,
|
||||
},
|
||||
Rule {
|
||||
action: RuleAction::Allow,
|
||||
os: Some(OsCondition {
|
||||
name: Some("linux".into()),
|
||||
arch: None,
|
||||
}),
|
||||
features: None,
|
||||
},
|
||||
];
|
||||
let features = FeatureSet::default();
|
||||
let ctx = linux_ctx(&features);
|
||||
assert!(evaluate(&rules, &ctx));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arch_mismatch_blocks_rule() {
|
||||
let rules = vec![Rule {
|
||||
action: RuleAction::Allow,
|
||||
os: Some(OsCondition {
|
||||
name: Some("linux".into()),
|
||||
arch: Some("arm64".into()),
|
||||
}),
|
||||
features: None,
|
||||
}];
|
||||
let features = FeatureSet::default();
|
||||
let ctx = linux_ctx(&features);
|
||||
// we are on linux but x86_64, not arm64 → rule does not match.
|
||||
assert!(!evaluate(&rules, &ctx));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feature_required_true_matches_when_ctx_true() {
|
||||
let rules = vec![Rule {
|
||||
action: RuleAction::Allow,
|
||||
os: None,
|
||||
features: Some(FeatureSet {
|
||||
is_demo_user: Some(true),
|
||||
has_custom_resolution: None,
|
||||
}),
|
||||
}];
|
||||
let demo_features = FeatureSet {
|
||||
is_demo_user: Some(true),
|
||||
has_custom_resolution: None,
|
||||
};
|
||||
let ctx = RuleContext {
|
||||
os_name: "linux",
|
||||
arch: "x86_64",
|
||||
features: &demo_features,
|
||||
};
|
||||
assert!(evaluate(&rules, &ctx));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feature_required_true_blocks_when_ctx_false() {
|
||||
let rules = vec![Rule {
|
||||
action: RuleAction::Allow,
|
||||
os: None,
|
||||
features: Some(FeatureSet {
|
||||
is_demo_user: Some(true),
|
||||
has_custom_resolution: None,
|
||||
}),
|
||||
}];
|
||||
let features = FeatureSet::default();
|
||||
let ctx = linux_ctx(&features);
|
||||
assert!(!evaluate(&rules, &ctx));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_os_no_features_rule_always_matches() {
|
||||
let rules = vec![Rule {
|
||||
action: RuleAction::Allow,
|
||||
os: None,
|
||||
features: None,
|
||||
}];
|
||||
let features = FeatureSet::default();
|
||||
let ctx = linux_ctx(&features);
|
||||
assert!(evaluate(&rules, &ctx));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rule_deserializes_from_mojang_json() {
|
||||
// shape lifted from real mojang library rules.
|
||||
let json = r#"{
|
||||
"action": "allow",
|
||||
"os": { "name": "osx" }
|
||||
}"#;
|
||||
let rule: Rule = serde_json::from_str(json).unwrap();
|
||||
assert_eq!(rule.action, RuleAction::Allow);
|
||||
assert_eq!(
|
||||
rule.os.as_ref().and_then(|o| o.name.as_deref()),
|
||||
Some("osx")
|
||||
);
|
||||
assert!(rule.os.as_ref().and_then(|o| o.arch.as_ref()).is_none());
|
||||
assert!(rule.features.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rule_deserializes_with_features() {
|
||||
let json = r#"{
|
||||
"action": "allow",
|
||||
"features": { "is_demo_user": true }
|
||||
}"#;
|
||||
let rule: Rule = serde_json::from_str(json).unwrap();
|
||||
assert_eq!(rule.action, RuleAction::Allow);
|
||||
assert!(rule.os.is_none());
|
||||
assert_eq!(
|
||||
rule.features.as_ref().and_then(|f| f.is_demo_user),
|
||||
Some(true)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
// template substitution for mojang-style launch arguments. profiles use
|
||||
// `${variable_name}` placeholders that the launcher fills in at launch
|
||||
// time from the active session: paths, the user's account info, the
|
||||
// classpath, the resolved natives directory, and so on.
|
||||
//
|
||||
// the full set of variables is documented in `TemplateContext`. unknown
|
||||
// placeholders are left as-is and logged at `warn` level - that way if
|
||||
// mojang adds a new variable in the future, the launcher fails open
|
||||
// rather than silently swallowing it.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
pub struct TemplateContext<'a> {
|
||||
pub library_directory: &'a Path,
|
||||
pub classpath_separator: &'a str,
|
||||
pub version_name: &'a str,
|
||||
pub natives_directory: &'a Path,
|
||||
pub classpath: &'a str,
|
||||
pub game_directory: &'a Path,
|
||||
pub assets_root: &'a Path,
|
||||
pub assets_index_name: &'a str,
|
||||
pub auth_player_name: &'a str,
|
||||
pub auth_uuid: &'a str,
|
||||
pub auth_access_token: &'a str,
|
||||
pub auth_xuid: &'a str,
|
||||
pub user_type: &'a str,
|
||||
pub user_properties: &'a str,
|
||||
pub launcher_name: &'a str,
|
||||
pub launcher_version: &'a str,
|
||||
pub clientid: &'a str,
|
||||
}
|
||||
|
||||
pub fn substitute(input: &str, ctx: &TemplateContext) -> String {
|
||||
let mut out = String::with_capacity(input.len());
|
||||
let mut rest = input;
|
||||
while let Some(open) = rest.find("${") {
|
||||
out.push_str(&rest[..open]);
|
||||
let after_open = &rest[open + 2..];
|
||||
match after_open.find('}') {
|
||||
Some(close_rel) => {
|
||||
let name = &after_open[..close_rel];
|
||||
match lookup(name, ctx) {
|
||||
Some(value) => out.push_str(&value),
|
||||
None => {
|
||||
tracing::warn!("unknown launch template variable: ${{{}}}", name);
|
||||
out.push_str("${");
|
||||
out.push_str(name);
|
||||
out.push('}');
|
||||
}
|
||||
}
|
||||
rest = &after_open[close_rel + 1..];
|
||||
}
|
||||
None => {
|
||||
// unclosed `${...` - emit the rest literally and stop.
|
||||
out.push_str("${");
|
||||
out.push_str(after_open);
|
||||
return out;
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push_str(rest);
|
||||
out
|
||||
}
|
||||
|
||||
fn lookup(name: &str, ctx: &TemplateContext) -> Option<String> {
|
||||
Some(match name {
|
||||
"library_directory" => ctx.library_directory.display().to_string(),
|
||||
"classpath_separator" => ctx.classpath_separator.to_string(),
|
||||
"version_name" => ctx.version_name.to_string(),
|
||||
"natives_directory" => ctx.natives_directory.display().to_string(),
|
||||
"classpath" => ctx.classpath.to_string(),
|
||||
"game_directory" => ctx.game_directory.display().to_string(),
|
||||
"assets_root" => ctx.assets_root.display().to_string(),
|
||||
"assets_index_name" => ctx.assets_index_name.to_string(),
|
||||
"auth_player_name" => ctx.auth_player_name.to_string(),
|
||||
"auth_uuid" => ctx.auth_uuid.to_string(),
|
||||
"auth_access_token" => ctx.auth_access_token.to_string(),
|
||||
"auth_xuid" => ctx.auth_xuid.to_string(),
|
||||
"user_type" => ctx.user_type.to_string(),
|
||||
"user_properties" => ctx.user_properties.to_string(),
|
||||
"launcher_name" => ctx.launcher_name.to_string(),
|
||||
"launcher_version" => ctx.launcher_version.to_string(),
|
||||
"clientid" => ctx.clientid.to_string(),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn ctx_fixture<'a>(
|
||||
library_directory: &'a Path,
|
||||
natives_directory: &'a Path,
|
||||
game_directory: &'a Path,
|
||||
assets_root: &'a Path,
|
||||
) -> TemplateContext<'a> {
|
||||
TemplateContext {
|
||||
library_directory,
|
||||
classpath_separator: ":",
|
||||
version_name: "1.20.1",
|
||||
natives_directory,
|
||||
classpath: "a.jar:b.jar",
|
||||
game_directory,
|
||||
assets_root,
|
||||
assets_index_name: "5",
|
||||
auth_player_name: "Player",
|
||||
auth_uuid: "00000000-0000-0000-0000-000000000000",
|
||||
auth_access_token: "token",
|
||||
auth_xuid: "0",
|
||||
user_type: "msa",
|
||||
user_properties: "{}",
|
||||
launcher_name: "rmcl",
|
||||
launcher_version: "0.3.0",
|
||||
clientid: "0",
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_placeholders_unchanged() {
|
||||
let lib = PathBuf::from("/m/libraries");
|
||||
let nat = PathBuf::from("/m/natives");
|
||||
let game = PathBuf::from("/i/.minecraft");
|
||||
let assets = PathBuf::from("/m/assets");
|
||||
let ctx = ctx_fixture(&lib, &nat, &game, &assets);
|
||||
assert_eq!(
|
||||
substitute("--add-modules ALL-MODULE-PATH", &ctx),
|
||||
"--add-modules ALL-MODULE-PATH"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_known_substitution() {
|
||||
let lib = PathBuf::from("/m/libraries");
|
||||
let nat = PathBuf::from("/m/natives");
|
||||
let game = PathBuf::from("/i/.minecraft");
|
||||
let assets = PathBuf::from("/m/assets");
|
||||
let ctx = ctx_fixture(&lib, &nat, &game, &assets);
|
||||
assert_eq!(substitute("v=${version_name}", &ctx), "v=1.20.1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_placeholder_left_as_is() {
|
||||
let lib = PathBuf::from("/m/libraries");
|
||||
let nat = PathBuf::from("/m/natives");
|
||||
let game = PathBuf::from("/i/.minecraft");
|
||||
let assets = PathBuf::from("/m/assets");
|
||||
let ctx = ctx_fixture(&lib, &nat, &game, &assets);
|
||||
assert_eq!(
|
||||
substitute("x=${not_a_real_var}y", &ctx),
|
||||
"x=${not_a_real_var}y"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unclosed_placeholder_left_as_is() {
|
||||
let lib = PathBuf::from("/m/libraries");
|
||||
let nat = PathBuf::from("/m/natives");
|
||||
let game = PathBuf::from("/i/.minecraft");
|
||||
let assets = PathBuf::from("/m/assets");
|
||||
let ctx = ctx_fixture(&lib, &nat, &game, &assets);
|
||||
assert_eq!(
|
||||
substitute("--prefix ${unclosed", &ctx),
|
||||
"--prefix ${unclosed"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dollar_without_brace_is_literal() {
|
||||
let lib = PathBuf::from("/m/libraries");
|
||||
let nat = PathBuf::from("/m/natives");
|
||||
let game = PathBuf::from("/i/.minecraft");
|
||||
let assets = PathBuf::from("/m/assets");
|
||||
let ctx = ctx_fixture(&lib, &nat, &game, &assets);
|
||||
assert_eq!(substitute("$$ literal $5 $", &ctx), "$$ literal $5 $");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multiple_substitutions() {
|
||||
let lib = PathBuf::from("/m/libraries");
|
||||
let nat = PathBuf::from("/m/natives");
|
||||
let game = PathBuf::from("/i/.minecraft");
|
||||
let assets = PathBuf::from("/m/assets");
|
||||
let ctx = ctx_fixture(&lib, &nat, &game, &assets);
|
||||
assert_eq!(
|
||||
substitute("${version_name}-${auth_player_name}", &ctx),
|
||||
"1.20.1-Player"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_substitution() {
|
||||
let lib = PathBuf::from("/m/libraries");
|
||||
let nat = PathBuf::from("/m/natives");
|
||||
let game = PathBuf::from("/i/.minecraft");
|
||||
let assets = PathBuf::from("/m/assets");
|
||||
let ctx = ctx_fixture(&lib, &nat, &game, &assets);
|
||||
assert_eq!(
|
||||
substitute("-DlibraryDirectory=${library_directory}", &ctx),
|
||||
"-DlibraryDirectory=/m/libraries"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn substituted_value_is_not_recursively_substituted() {
|
||||
// simulate a `user_properties` value that happens to contain a `${...}`
|
||||
// pattern. it should NOT trigger another substitution pass.
|
||||
let lib = PathBuf::from("/m/libraries");
|
||||
let nat = PathBuf::from("/m/natives");
|
||||
let game = PathBuf::from("/i/.minecraft");
|
||||
let assets = PathBuf::from("/m/assets");
|
||||
let ctx = TemplateContext {
|
||||
library_directory: &lib,
|
||||
classpath_separator: ":",
|
||||
version_name: "1.20.1",
|
||||
natives_directory: &nat,
|
||||
classpath: "a.jar:b.jar",
|
||||
game_directory: &game,
|
||||
assets_root: &assets,
|
||||
assets_index_name: "5",
|
||||
auth_player_name: "Player",
|
||||
auth_uuid: "00000000-0000-0000-0000-000000000000",
|
||||
auth_access_token: "token",
|
||||
auth_xuid: "0",
|
||||
user_type: "msa",
|
||||
user_properties: "${version_name}",
|
||||
launcher_name: "rmcl",
|
||||
launcher_version: "0.3.0",
|
||||
clientid: "0",
|
||||
};
|
||||
assert_eq!(substitute("${user_properties}", &ctx), "${version_name}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_input_is_empty() {
|
||||
let lib = PathBuf::from("/m/libraries");
|
||||
let nat = PathBuf::from("/m/natives");
|
||||
let game = PathBuf::from("/i/.minecraft");
|
||||
let assets = PathBuf::from("/m/assets");
|
||||
let ctx = ctx_fixture(&lib, &nat, &game, &assets);
|
||||
assert_eq!(substitute("", &ctx), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_style_backslashes_in_value_pass_through() {
|
||||
// simulate a Windows install where library_directory is a path with
|
||||
// backslashes. the substitution must not interpret backslashes as
|
||||
// escape sequences or do anything else clever - it just copies the
|
||||
// value into the output.
|
||||
let lib = PathBuf::from(r"C:\Users\test\.minecraft\libraries");
|
||||
let nat = PathBuf::from(r"C:\Users\test\.minecraft\natives");
|
||||
let game = PathBuf::from(r"C:\Users\test\.minecraft");
|
||||
let assets = PathBuf::from(r"C:\Users\test\.minecraft\assets");
|
||||
let ctx = ctx_fixture(&lib, &nat, &game, &assets);
|
||||
let result = substitute("-Dpath=${library_directory}", &ctx);
|
||||
assert!(
|
||||
result.contains(r"C:\Users\test\.minecraft\libraries"),
|
||||
"expected backslashes preserved, got: {result}"
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user