port-pack: check one mod jar (Works, Partly, Doesn't run) from its content and classes
`horizon-port-pack check <jar> <out>` carries a single jar into a folder content mod and reads its class files (constant pool, superclass, declared methods) for what the carry can't take: block entities, menus, entities, blocks and items with behaviour of their own, recipe types, worldgen code, Mixins, game events. The verdict and the lists of what ports and what is skipped go to check.json, for the launcher's mod browser to show before install. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,366 @@
|
||||
//! One mod jar on its own, as the launcher's mod browser installs it: what
|
||||
//! of it Horizon runs, said before install (Works, Partly, Doesn't run),
|
||||
//! from the jar itself. The jar is carried over ([`crate::carry`]) into a
|
||||
//! folder content mod, and its classes are read ([`crate::classes`]) for
|
||||
//! what the carry can't take: block entities, entities, Mixins, behaviour.
|
||||
//!
|
||||
//! - **Works**: content only. Its blocks, items, recipes, loot, tags and
|
||||
//! worldgen port, and its code only registers them.
|
||||
//! - **Partly**: the content ports; the code features listed don't.
|
||||
//! - **Doesn't run**: nothing to port (everything it does is Java code), or
|
||||
//! the jar can't be carried at all.
|
||||
use crate::{carry, classes, jar};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{collections::BTreeMap, fs, io::Read, path::Path};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum Verdict {
|
||||
Works,
|
||||
Partly,
|
||||
No,
|
||||
}
|
||||
|
||||
impl Verdict {
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Verdict::Works => "Works",
|
||||
Verdict::Partly => "Partly",
|
||||
Verdict::No => "Doesn't run",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What checking a jar found. Written as `check.json` beside the carry.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Check {
|
||||
pub mod_id: String,
|
||||
pub name: String,
|
||||
pub version: String,
|
||||
/// `neoforge`, `forge`, `fabric`, `quilt`, or `` for a plain zip.
|
||||
pub loader: String,
|
||||
pub license: String,
|
||||
pub verdict: Verdict,
|
||||
/// One line: why this verdict.
|
||||
pub summary: String,
|
||||
/// What ports: "12 blocks", "40 recipes"...
|
||||
pub ports: Vec<String>,
|
||||
/// What doesn't, with why.
|
||||
pub skipped: Vec<String>,
|
||||
/// Required mods, by id.
|
||||
pub depends: Vec<String>,
|
||||
/// The folder mod's namespaces (its id first): two mods on at once may
|
||||
/// not share one.
|
||||
pub namespaces: Vec<String>,
|
||||
pub code: classes::Code,
|
||||
}
|
||||
|
||||
/// The loader a jar is made for, from its metadata file.
|
||||
fn loader(names: &[String]) -> &'static str {
|
||||
let has = |n: &str| names.iter().any(|x| x == n);
|
||||
if has("META-INF/neoforge.mods.toml") {
|
||||
"neoforge"
|
||||
} else if has("META-INF/mods.toml") {
|
||||
"forge"
|
||||
} else if has("fabric.mod.json") {
|
||||
"fabric"
|
||||
} else if has("quilt.mod.json") {
|
||||
"quilt"
|
||||
} else {
|
||||
""
|
||||
}
|
||||
}
|
||||
|
||||
/// Data folders named as before 1.21 (`recipes/`, `loot_tables/`) and none
|
||||
/// as 1.21 names them: the game doesn't read them, and the carry upgrades
|
||||
/// from 1.21.1 on. (Some jars keep a stale plural folder beside the new one.)
|
||||
fn old_layout(names: &[String]) -> bool {
|
||||
let has = |kinds: [&str; 2]| {
|
||||
names.iter().any(|n| {
|
||||
let p: Vec<&str> = n.split('/').collect();
|
||||
p.len() > 3 && p[0] == "data" && kinds.contains(&p[2]) && n.ends_with(".json")
|
||||
})
|
||||
};
|
||||
has(["recipes", "loot_tables"]) && !has(["recipe", "loot_table"])
|
||||
}
|
||||
|
||||
fn plural(n: usize, one: &str, many: &str) -> String {
|
||||
format!("{n} {}", if n == 1 { one } else { many })
|
||||
}
|
||||
|
||||
/// Checks `jar` and carries it over into `out/carry/` (`out/check.json`,
|
||||
/// `out/carry-report.json` beside it). The carry is the folder mod an
|
||||
/// install copies.
|
||||
pub fn check(jar_path: &Path, out: &Path) -> Result<Check, String> {
|
||||
let info = jar::read(jar_path)?;
|
||||
let file = fs::File::open(jar_path).map_err(|e| format!("{}: {e}", jar_path.display()))?;
|
||||
let mut zip = zip::ZipArchive::new(file).map_err(|e| format!("{}: {e}", jar_path.display()))?;
|
||||
let names: Vec<String> = zip.file_names().map(str::to_owned).collect();
|
||||
let mut bytes = Vec::new();
|
||||
for n in names.iter().filter(|n| n.ends_with(".class")) {
|
||||
let mut b = Vec::new();
|
||||
if let Ok(mut e) = zip.by_name(n)
|
||||
&& e.size() < 1 << 24
|
||||
&& e.read_to_end(&mut b).is_ok()
|
||||
{
|
||||
bytes.push(b);
|
||||
}
|
||||
}
|
||||
let code = classes::census(bytes.iter().map(Vec::as_slice));
|
||||
let mut check = Check {
|
||||
mod_id: info.mod_id.clone(),
|
||||
name: info.name.clone(),
|
||||
version: info.version.clone(),
|
||||
loader: loader(&names).to_owned(),
|
||||
license: info.license.clone(),
|
||||
verdict: Verdict::No,
|
||||
summary: String::new(),
|
||||
ports: Vec::new(),
|
||||
skipped: Vec::new(),
|
||||
depends: info.depends.clone(),
|
||||
namespaces: Vec::new(),
|
||||
code,
|
||||
};
|
||||
fs::create_dir_all(out).map_err(|e| format!("{}: {e}", out.display()))?;
|
||||
let done = |check: Check| -> Result<Check, String> {
|
||||
crate::pipeline::write_json(&out.join("check.json"), &check)?;
|
||||
Ok(check)
|
||||
};
|
||||
if old_layout(&names) {
|
||||
check.summary = "Made for Minecraft 1.20 or older: Horizon ports mods made for 1.21 \
|
||||
and later."
|
||||
.into();
|
||||
return done(check);
|
||||
}
|
||||
let alone = |m: &str| m == info.mod_id || m == "minecraft";
|
||||
let pack = carry::Pack {
|
||||
loaded: &alone,
|
||||
mods: &alone,
|
||||
};
|
||||
let report = match carry::carry(
|
||||
jar_path,
|
||||
&info,
|
||||
out,
|
||||
None,
|
||||
&|_| true,
|
||||
&pack,
|
||||
&BTreeMap::new(),
|
||||
) {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
check.summary = format!("Can't be carried over: {e}");
|
||||
return done(check);
|
||||
}
|
||||
};
|
||||
check.namespaces = std::iter::once(info.mod_id.clone())
|
||||
.chain(report.namespaces.iter().cloned())
|
||||
.collect();
|
||||
let c = &info.census;
|
||||
let recipes = report.recipes_upgraded;
|
||||
let loot = c.loot_tables + report.loot_tables_added;
|
||||
let content =
|
||||
report.blocks.len() + report.items + recipes + loot + report.worldgen + c.structures;
|
||||
for (n, one, many) in [
|
||||
(report.blocks.len(), "block", "blocks"),
|
||||
(report.items, "item", "items"),
|
||||
(recipes, "recipe", "recipes"),
|
||||
(loot, "loot table", "loot tables"),
|
||||
(report.worldgen, "worldgen file", "worldgen files"),
|
||||
(c.textures, "texture", "textures"),
|
||||
] {
|
||||
if n > 0 {
|
||||
check.ports.push(plural(n, one, many));
|
||||
}
|
||||
}
|
||||
if !report.blocks.is_empty() {
|
||||
check
|
||||
.ports
|
||||
.push("blocks take the closest vanilla block's shape, hardness and sounds".into());
|
||||
}
|
||||
let mut skipped = Vec::new();
|
||||
if !report.blocks_unknown.is_empty() {
|
||||
skipped.push(plural(
|
||||
report.blocks_unknown.len(),
|
||||
"block with no vanilla block to copy (left out)",
|
||||
"blocks with no vanilla block to copy (left out)",
|
||||
));
|
||||
}
|
||||
if !report.recipes_kept.is_empty() {
|
||||
skipped.push(plural(
|
||||
report.recipes_kept.len(),
|
||||
"recipe of a type Horizon doesn't have",
|
||||
"recipes of types Horizon doesn't have",
|
||||
));
|
||||
}
|
||||
if !report.unreadable.is_empty() {
|
||||
skipped.push(plural(
|
||||
report.unreadable.len(),
|
||||
"file the game can't read",
|
||||
"files the game can't read",
|
||||
));
|
||||
}
|
||||
let wg = &report.worldgen_types;
|
||||
let dropped = wg.processors_dropped.values().sum::<usize>();
|
||||
if dropped > 0 {
|
||||
skipped.push(plural(
|
||||
dropped,
|
||||
"structure processor written in Java",
|
||||
"structure processors written in Java",
|
||||
));
|
||||
}
|
||||
let unsupported = wg.unsupported.values().sum::<usize>();
|
||||
if unsupported > 0 {
|
||||
skipped.push(plural(
|
||||
unsupported,
|
||||
"worldgen file of a type written in Java",
|
||||
"worldgen files of types written in Java",
|
||||
));
|
||||
}
|
||||
for (f, n) in &check.code.features {
|
||||
let mut line = f.describe(*n);
|
||||
if *f == classes::Feature::Events {
|
||||
let names: Vec<&str> = check
|
||||
.code
|
||||
.events
|
||||
.iter()
|
||||
.take(3)
|
||||
.map(String::as_str)
|
||||
.collect();
|
||||
line.push_str(&format!(" ({}", names.join(", ")));
|
||||
if check.code.events.len() > 3 {
|
||||
line.push_str(", ...");
|
||||
}
|
||||
line.push(')');
|
||||
}
|
||||
skipped.push(line);
|
||||
}
|
||||
check.skipped = skipped;
|
||||
let behaviour = check.code.behaviour();
|
||||
(check.verdict, check.summary) = if content == 0 {
|
||||
let what = if behaviour || check.code.classes > 0 {
|
||||
"everything it does is Java code, which Horizon doesn't run"
|
||||
} else {
|
||||
"it has no blocks, items, recipes or worldgen"
|
||||
};
|
||||
(Verdict::No, format!("Nothing to port: {what}."))
|
||||
} else if check.skipped.is_empty() {
|
||||
(
|
||||
Verdict::Works,
|
||||
format!(
|
||||
"Content only: {} port.",
|
||||
check.ports[..check.ports.len().min(3)].join(", ")
|
||||
),
|
||||
)
|
||||
} else {
|
||||
(
|
||||
Verdict::Partly,
|
||||
format!(
|
||||
"{} port; not {}.",
|
||||
check.ports[..check.ports.len().min(2)].join(", "),
|
||||
check.skipped[..check.skipped.len().min(2)].join(", ")
|
||||
),
|
||||
)
|
||||
};
|
||||
done(check)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::Write;
|
||||
|
||||
fn jar(dir: &Path, files: &[(&str, &[u8])]) -> std::path::PathBuf {
|
||||
let path = dir.join("m.jar");
|
||||
let mut zip = zip::ZipWriter::new(fs::File::create(&path).unwrap());
|
||||
for (name, bytes) in files {
|
||||
zip.start_file(*name, zip::write::SimpleFileOptions::default())
|
||||
.unwrap();
|
||||
zip.write_all(bytes).unwrap();
|
||||
}
|
||||
zip.finish().unwrap();
|
||||
path
|
||||
}
|
||||
|
||||
const TOML: &[u8] = br#"modLoader = "javafml"
|
||||
license = "MIT"
|
||||
[[mods]]
|
||||
modId = "ruby"
|
||||
version = "1.0"
|
||||
displayName = "Ruby"
|
||||
"#;
|
||||
|
||||
fn temp(name: &str) -> std::path::PathBuf {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("port-pack-check-{name}-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn content_only_works_and_code_makes_it_partly() {
|
||||
let dir = temp("content");
|
||||
let blockstate = br#"{"variants": {"": {"model": "ruby:block/ruby_block"}}}"#;
|
||||
let recipe = br#"{"type": "minecraft:crafting_shapeless", "ingredients": ["minecraft:red_dye"], "result": {"id": "ruby:ruby"}}"#;
|
||||
let plain = [
|
||||
("META-INF/neoforge.mods.toml", TOML),
|
||||
("assets/ruby/blockstates/ruby_block.json", blockstate),
|
||||
("assets/ruby/models/item/ruby.json", b"{}"),
|
||||
("data/ruby/recipe/ruby.json", recipe),
|
||||
];
|
||||
let c = check(&jar(&dir, &plain), &dir.join("out")).unwrap();
|
||||
assert_eq!(c.verdict, Verdict::Works, "{c:?}");
|
||||
assert_eq!(c.loader, "neoforge");
|
||||
assert_eq!(&c.ports[..3], ["1 block", "1 item", "1 recipe"]);
|
||||
assert!(dir.join("out/carry/horizon-mod.toml").is_file());
|
||||
assert!(dir.join("out/check.json").is_file());
|
||||
|
||||
let tile = crate::classes::tests_support::class_file(
|
||||
"ruby/Tile",
|
||||
"net/minecraft/world/level/block/entity/BlockEntity",
|
||||
);
|
||||
let mut coded = plain.to_vec();
|
||||
coded.push(("ruby/Tile.class", &tile));
|
||||
let c = check(&jar(&dir, &coded), &dir.join("out")).unwrap();
|
||||
assert_eq!(c.verdict, Verdict::Partly);
|
||||
assert!(
|
||||
c.skipped[0].starts_with("1 block entity"),
|
||||
"{:?}",
|
||||
c.skipped
|
||||
);
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_only_and_old_layouts_dont_run() {
|
||||
let dir = temp("code");
|
||||
let tile = crate::classes::tests_support::class_file("ruby/Mixin", "java/lang/Object");
|
||||
let c = check(
|
||||
&jar(
|
||||
&dir,
|
||||
&[
|
||||
("META-INF/neoforge.mods.toml", TOML),
|
||||
("ruby/A.class", &tile),
|
||||
],
|
||||
),
|
||||
&dir.join("out"),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(c.verdict, Verdict::No);
|
||||
assert!(c.summary.starts_with("Nothing to port"), "{}", c.summary);
|
||||
let c = check(
|
||||
&jar(
|
||||
&dir,
|
||||
&[
|
||||
("META-INF/mods.toml", TOML),
|
||||
("data/ruby/recipes/ruby.json", b"{}"),
|
||||
],
|
||||
),
|
||||
&dir.join("out"),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(c.verdict, Verdict::No);
|
||||
assert!(c.summary.contains("1.20 or older"));
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,642 @@
|
||||
//! What a mod's Java code does, read from its class files without running
|
||||
//! or decompiling them: each class's superclass, interfaces, declared
|
||||
//! methods and the classes and annotations its constant pool names. The
|
||||
//! mod's own classes are followed up to the first game class they extend,
|
||||
//! and that class says what the code is: a block entity, a menu, an entity,
|
||||
//! a block or item with behaviour of its own, a worldgen feature...
|
||||
//!
|
||||
//! Since 26.1 the game ships unobfuscated, and NeoForge has run on Mojang's
|
||||
//! names since 1.20.5, so game classes and methods are read by name. Fabric
|
||||
//! jars before 26.1 name them in intermediary (`net/minecraft/class_2248`)
|
||||
//! and Forge's methods are SRG (`m_60503_`): a class extending such a game
|
||||
//! class is counted as code of its own, whatever it overrides.
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||
|
||||
/// One class file, as much as this module reads.
|
||||
#[derive(Debug, Default, Clone, PartialEq)]
|
||||
pub struct Class {
|
||||
pub name: String,
|
||||
pub superclass: String,
|
||||
pub interfaces: Vec<String>,
|
||||
/// Declared methods, by name (constructors and lambdas left out).
|
||||
pub methods: Vec<String>,
|
||||
/// Every class the constant pool names (`net/minecraft/...`).
|
||||
pub refs: BTreeSet<String>,
|
||||
/// Annotation and descriptor strings (`Lorg/spongepowered/asm/mixin/Mixin;`).
|
||||
pub mixin: bool,
|
||||
}
|
||||
|
||||
/// Reads a class file's header, constant pool and declared methods.
|
||||
pub fn parse(bytes: &[u8]) -> Option<Class> {
|
||||
let mut r = Reader { bytes, at: 0 };
|
||||
if r.u4()? != 0xCAFE_BABE {
|
||||
return None;
|
||||
}
|
||||
r.skip(4)?; // minor, major
|
||||
let count = r.u2()? as usize;
|
||||
let mut utf8: HashMap<usize, String> = HashMap::new();
|
||||
let mut class_of: HashMap<usize, usize> = HashMap::new();
|
||||
let mut i = 1;
|
||||
while i < count {
|
||||
let tag = r.u1()?;
|
||||
match tag {
|
||||
1 => {
|
||||
let len = r.u2()? as usize;
|
||||
let s = r.take(len)?;
|
||||
utf8.insert(i, String::from_utf8_lossy(s).into_owned());
|
||||
}
|
||||
7 => {
|
||||
class_of.insert(i, r.u2()? as usize);
|
||||
}
|
||||
8 | 16 | 19 | 20 => r.skip(2)?,
|
||||
3 | 4 | 9..=12 | 17 | 18 => r.skip(4)?,
|
||||
15 => r.skip(3)?,
|
||||
5 | 6 => {
|
||||
r.skip(8)?;
|
||||
i += 1;
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
let class_name = |idx: usize| -> String {
|
||||
class_of
|
||||
.get(&idx)
|
||||
.and_then(|u| utf8.get(u))
|
||||
.cloned()
|
||||
.unwrap_or_default()
|
||||
};
|
||||
r.skip(2)?; // access flags
|
||||
let name = class_name(r.u2()? as usize);
|
||||
let superclass = class_name(r.u2()? as usize);
|
||||
let n = r.u2()? as usize;
|
||||
let mut interfaces = Vec::with_capacity(n);
|
||||
for _ in 0..n {
|
||||
interfaces.push(class_name(r.u2()? as usize));
|
||||
}
|
||||
// Fields, then methods: flags, name, descriptor, attributes.
|
||||
let mut methods = Vec::new();
|
||||
for member in 0..2 {
|
||||
let n = r.u2()?;
|
||||
for _ in 0..n {
|
||||
r.skip(2)?;
|
||||
let name = r.u2()? as usize;
|
||||
r.skip(2)?;
|
||||
let attributes = r.u2()?;
|
||||
for _ in 0..attributes {
|
||||
r.skip(2)?;
|
||||
let len = r.u4()? as usize;
|
||||
r.skip(len)?;
|
||||
}
|
||||
if member == 1
|
||||
&& let Some(m) = utf8.get(&name)
|
||||
&& !m.starts_with('<')
|
||||
&& !m.starts_with("lambda$")
|
||||
{
|
||||
methods.push(m.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
let refs = class_of
|
||||
.values()
|
||||
.filter_map(|u| utf8.get(u))
|
||||
.filter(|s| !s.starts_with('['))
|
||||
.cloned()
|
||||
.collect();
|
||||
let mixin = utf8
|
||||
.values()
|
||||
.any(|s| s == "Lorg/spongepowered/asm/mixin/Mixin;");
|
||||
Some(Class {
|
||||
name,
|
||||
superclass,
|
||||
interfaces,
|
||||
methods,
|
||||
refs,
|
||||
mixin,
|
||||
})
|
||||
}
|
||||
|
||||
struct Reader<'a> {
|
||||
bytes: &'a [u8],
|
||||
at: usize,
|
||||
}
|
||||
|
||||
impl<'a> Reader<'a> {
|
||||
fn take(&mut self, n: usize) -> Option<&'a [u8]> {
|
||||
let s = self.bytes.get(self.at..self.at.checked_add(n)?)?;
|
||||
self.at += n;
|
||||
Some(s)
|
||||
}
|
||||
fn skip(&mut self, n: usize) -> Option<()> {
|
||||
self.take(n).map(drop)
|
||||
}
|
||||
fn u1(&mut self) -> Option<u8> {
|
||||
Some(self.take(1)?[0])
|
||||
}
|
||||
fn u2(&mut self) -> Option<u16> {
|
||||
let b = self.take(2)?;
|
||||
Some(u16::from_be_bytes([b[0], b[1]]))
|
||||
}
|
||||
fn u4(&mut self) -> Option<u32> {
|
||||
let b = self.take(4)?;
|
||||
Some(u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
|
||||
}
|
||||
}
|
||||
|
||||
/// What a class does, as the port sees it.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum Feature {
|
||||
/// A block with behaviour of its own (use, ticks, collisions...).
|
||||
BlockBehaviour,
|
||||
/// A block with a shape of its own: it ports with its template's.
|
||||
BlockShape,
|
||||
/// An item with behaviour of its own (use, on hit...).
|
||||
ItemBehaviour,
|
||||
BlockEntity,
|
||||
Menu,
|
||||
Entity,
|
||||
Screen,
|
||||
Renderer,
|
||||
/// A worldgen feature, placement or structure type written in Java.
|
||||
Worldgen,
|
||||
/// A recipe type (its recipes don't craft) or ingredient type.
|
||||
Recipe,
|
||||
Effect,
|
||||
Enchantment,
|
||||
Particle,
|
||||
Command,
|
||||
Network,
|
||||
/// Reacts to game events (NeoForge's bus, Fabric's callbacks).
|
||||
Events,
|
||||
/// A Mixin: a patch to the game's own code.
|
||||
Mixin,
|
||||
/// Extends a game class under obfuscated names (Fabric before 26.1,
|
||||
/// Forge's methods): what it does can't be read.
|
||||
Unread,
|
||||
}
|
||||
|
||||
impl Feature {
|
||||
/// How the coverage line names `n` of them.
|
||||
pub fn describe(self, n: usize) -> String {
|
||||
let (one, many) = match self {
|
||||
Feature::BlockBehaviour => (
|
||||
"block with behaviour of its own (use, ticks, collisions)",
|
||||
"blocks with behaviour of their own (use, ticks, collisions)",
|
||||
),
|
||||
Feature::BlockShape => (
|
||||
"block with a shape of its own: it ports with its template's",
|
||||
"blocks with shapes of their own: they port with their templates'",
|
||||
),
|
||||
Feature::ItemBehaviour => (
|
||||
"item with behaviour of its own (use, on hit)",
|
||||
"items with behaviour of their own (use, on hit)",
|
||||
),
|
||||
Feature::BlockEntity => (
|
||||
"block entity (machine, container or animated block)",
|
||||
"block entities (machines, containers, animated blocks)",
|
||||
),
|
||||
Feature::Menu => ("menu (a container screen)", "menus (container screens)"),
|
||||
Feature::Entity => ("mob or entity", "mobs or entities"),
|
||||
Feature::Screen => ("screen of its own", "screens of its own"),
|
||||
Feature::Renderer => ("renderer or model in code", "renderers or models in code"),
|
||||
Feature::Worldgen => (
|
||||
"worldgen feature or structure type in code",
|
||||
"worldgen features or structure types in code",
|
||||
),
|
||||
Feature::Recipe => (
|
||||
"recipe type of its own (its recipes don't craft)",
|
||||
"recipe types of its own (their recipes don't craft)",
|
||||
),
|
||||
Feature::Effect => ("status effect", "status effects"),
|
||||
Feature::Enchantment => ("enchantment effect in code", "enchantment effects in code"),
|
||||
Feature::Particle => ("particle type", "particle types"),
|
||||
Feature::Command => ("command", "commands"),
|
||||
Feature::Network => ("network message", "network messages"),
|
||||
Feature::Events => ("game event it reacts to", "game events it reacts to"),
|
||||
Feature::Mixin => (
|
||||
"Mixin (a patch to the game's code)",
|
||||
"Mixins (patches to the game's code)",
|
||||
),
|
||||
Feature::Unread => (
|
||||
"class extending the game under obfuscated names",
|
||||
"classes extending the game under obfuscated names",
|
||||
),
|
||||
};
|
||||
format!("{n} {}", if n == 1 { one } else { many })
|
||||
}
|
||||
}
|
||||
|
||||
/// Block methods that only say how it looks or is placed: the template's
|
||||
/// do the same for the states a blockstate file lists.
|
||||
const BLOCK_LOOKS: [&str; 18] = [
|
||||
"codec",
|
||||
"createBlockStateDefinition",
|
||||
"getStateForPlacement",
|
||||
"rotate",
|
||||
"mirror",
|
||||
"getRenderShape",
|
||||
"skipRendering",
|
||||
"getShadeBrightness",
|
||||
"propagatesSkylightDown",
|
||||
"getCloneItemStack",
|
||||
"isPathfindable",
|
||||
"getFluidState",
|
||||
"updateShape",
|
||||
"canBeReplaced",
|
||||
"getLightBlock",
|
||||
"useShapeForLightOcclusion",
|
||||
"getDescriptionId",
|
||||
"animateTick",
|
||||
];
|
||||
/// Block methods that only change its outline or collision.
|
||||
const BLOCK_SHAPES: [&str; 6] = [
|
||||
"getShape",
|
||||
"getCollisionShape",
|
||||
"getVisualShape",
|
||||
"getOcclusionShape",
|
||||
"getInteractionShape",
|
||||
"getBlockSupportShape",
|
||||
];
|
||||
/// Item methods that only say how it looks or is named.
|
||||
const ITEM_LOOKS: [&str; 6] = [
|
||||
"appendHoverText",
|
||||
"getName",
|
||||
"isFoil",
|
||||
"getDescriptionId",
|
||||
"getBarColor",
|
||||
"getBarWidth",
|
||||
];
|
||||
|
||||
/// The game's own, loader and library classes: the first of these a mod's
|
||||
/// class chain reaches is what it extends.
|
||||
fn external(name: &str, own: &BTreeMap<String, Class>) -> bool {
|
||||
!own.contains_key(name)
|
||||
}
|
||||
|
||||
fn obfuscated_method(m: &str) -> bool {
|
||||
let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
|
||||
m.strip_prefix("method_").is_some_and(digits)
|
||||
|| m.strip_prefix("m_")
|
||||
.and_then(|s| s.strip_suffix('_'))
|
||||
.is_some_and(digits)
|
||||
}
|
||||
|
||||
/// What a game class (Mojang's names) is, by its package and name.
|
||||
fn kind_of_game_class(name: &str) -> Option<Feature> {
|
||||
let rest = name.strip_prefix("net/minecraft/")?;
|
||||
if rest.starts_with("class_") {
|
||||
return Some(Feature::Unread);
|
||||
}
|
||||
let (package, simple) = rest.rsplit_once('/').unwrap_or(("", rest));
|
||||
Some(match package {
|
||||
"world/level/block/entity" => Feature::BlockEntity,
|
||||
p if p.starts_with("world/level/block") => Feature::BlockBehaviour,
|
||||
"world/inventory" if simple.ends_with("Menu") => Feature::Menu,
|
||||
p if p.starts_with("world/entity") => Feature::Entity,
|
||||
p if p.starts_with("world/item/crafting") => Feature::Recipe,
|
||||
p if p.starts_with("world/item/enchantment") => Feature::Enchantment,
|
||||
p if p.starts_with("world/item") => Feature::ItemBehaviour,
|
||||
p if p.starts_with("world/level/levelgen") => Feature::Worldgen,
|
||||
"world/effect" => Feature::Effect,
|
||||
p if p.starts_with("client/gui/screens") || p.starts_with("client/gui/components") => {
|
||||
Feature::Screen
|
||||
}
|
||||
p if p.starts_with("client/renderer") || p.starts_with("client/model") => Feature::Renderer,
|
||||
p if p.starts_with("client/particle") || p.starts_with("core/particles") => {
|
||||
Feature::Particle
|
||||
}
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Events a content mod uses to register what it has: not behaviour.
|
||||
fn registration_event(name: &str) -> bool {
|
||||
[
|
||||
"BuildCreativeModeTabContentsEvent",
|
||||
"RegisterEvent",
|
||||
"Register",
|
||||
"Lifecycle",
|
||||
"ModConfigEvent",
|
||||
"AddPackFindersEvent",
|
||||
"ItemGroupEvents",
|
||||
"ClientLifecycleEvents",
|
||||
"ServerLifecycleEvents",
|
||||
]
|
||||
.iter()
|
||||
.any(|k| name.rsplit('/').next().unwrap_or(name).contains(k))
|
||||
|| name.contains("/lifecycle/")
|
||||
|| name.contains("/registries/")
|
||||
|| name.contains("/registry/")
|
||||
}
|
||||
|
||||
/// The code census: how many of each feature, and examples.
|
||||
#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Code {
|
||||
pub classes: usize,
|
||||
pub features: BTreeMap<Feature, usize>,
|
||||
/// The game events it subscribes to, by simple name.
|
||||
pub events: BTreeSet<String>,
|
||||
/// Blocks and items with behaviour, and the methods they override.
|
||||
pub examples: BTreeMap<String, Vec<String>>,
|
||||
}
|
||||
|
||||
impl Code {
|
||||
/// Whether it does anything beyond registering blocks and items.
|
||||
pub fn behaviour(&self) -> bool {
|
||||
self.features
|
||||
.keys()
|
||||
.any(|f| *f != Feature::BlockShape && *f != Feature::Particle)
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads every class of a jar. `classes` are the class files' bytes.
|
||||
pub fn census<'a>(classes: impl IntoIterator<Item = &'a [u8]>) -> Code {
|
||||
let own: BTreeMap<String, Class> = classes
|
||||
.into_iter()
|
||||
.filter_map(parse)
|
||||
.map(|c| (c.name.clone(), c))
|
||||
.collect();
|
||||
let mut code = Code {
|
||||
classes: own.len(),
|
||||
..Code::default()
|
||||
};
|
||||
let mut count = |f: Feature| *code.features.entry(f).or_default() += 1;
|
||||
for c in own.values() {
|
||||
if c.mixin {
|
||||
count(Feature::Mixin);
|
||||
continue;
|
||||
}
|
||||
// The first class outside the jar the chain reaches, and the
|
||||
// methods declared along the way.
|
||||
let mut methods: BTreeSet<&str> = c.methods.iter().map(String::as_str).collect();
|
||||
let mut at = c;
|
||||
let mut seen = 0;
|
||||
while !external(&at.superclass, &own) && seen < 64 {
|
||||
at = &own[&at.superclass];
|
||||
methods.extend(at.methods.iter().map(String::as_str));
|
||||
seen += 1;
|
||||
}
|
||||
let base = at.superclass.as_str();
|
||||
let kind = kind_of_game_class(base).or_else(|| {
|
||||
c.interfaces.iter().find_map(|i| match i.as_str() {
|
||||
"net/minecraft/network/protocol/common/custom/CustomPacketPayload" => {
|
||||
Some(Feature::Network)
|
||||
}
|
||||
"net/minecraft/world/MenuProvider" => Some(Feature::Menu),
|
||||
_ => None,
|
||||
})
|
||||
});
|
||||
let Some(kind) = kind else {
|
||||
continue;
|
||||
};
|
||||
let feature = match kind {
|
||||
Feature::BlockBehaviour => {
|
||||
let behaviour: Vec<&str> = methods
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|m| !BLOCK_LOOKS.contains(m) && !BLOCK_SHAPES.contains(m))
|
||||
.collect();
|
||||
if !behaviour.is_empty() {
|
||||
code.examples.insert(
|
||||
c.name.rsplit('/').next().unwrap_or("").to_owned(),
|
||||
behaviour.iter().map(|m| m.to_string()).collect(),
|
||||
);
|
||||
if behaviour.iter().any(|m| obfuscated_method(m)) {
|
||||
Some(Feature::Unread)
|
||||
} else {
|
||||
Some(Feature::BlockBehaviour)
|
||||
}
|
||||
} else if methods.iter().any(|m| BLOCK_SHAPES.contains(m)) {
|
||||
Some(Feature::BlockShape)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
Feature::ItemBehaviour => {
|
||||
let behaviour: Vec<&str> = methods
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|m| !ITEM_LOOKS.contains(m))
|
||||
.collect();
|
||||
if behaviour.is_empty() {
|
||||
None
|
||||
} else {
|
||||
code.examples.insert(
|
||||
c.name.rsplit('/').next().unwrap_or("").to_owned(),
|
||||
behaviour.iter().map(|m| m.to_string()).collect(),
|
||||
);
|
||||
Some(Feature::ItemBehaviour)
|
||||
}
|
||||
}
|
||||
// A class extending an obfuscated game class without declaring
|
||||
// anything adds nothing to read.
|
||||
Feature::Unread if methods.is_empty() => None,
|
||||
k => Some(k),
|
||||
};
|
||||
if let Some(f) = feature {
|
||||
count(f);
|
||||
}
|
||||
}
|
||||
for c in own.values() {
|
||||
for r in &c.refs {
|
||||
let event = (r.starts_with("net/neoforged/neoforge/event/")
|
||||
|| r.starts_with("net/minecraftforge/event/")
|
||||
|| r.starts_with("net/fabricmc/fabric/api/event/")
|
||||
|| r.starts_with("net/fabricmc/fabric/api/entity/event/"))
|
||||
&& !registration_event(r);
|
||||
if event {
|
||||
let simple = r.rsplit('/').next().unwrap_or(r);
|
||||
code.events
|
||||
.insert(simple.split('$').next().unwrap_or(simple).to_owned());
|
||||
}
|
||||
if r.starts_with("com/mojang/brigadier/")
|
||||
&& !code.features.contains_key(&Feature::Command)
|
||||
{
|
||||
code.features.insert(Feature::Command, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
if !code.events.is_empty() {
|
||||
code.features.insert(Feature::Events, code.events.len());
|
||||
}
|
||||
code
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests_support {
|
||||
/// A class file with `name` extending `superclass`, declaring `methods`
|
||||
/// and naming `refs` in its constant pool.
|
||||
pub fn class_with(
|
||||
name: &str,
|
||||
superclass: &str,
|
||||
methods: &[&str],
|
||||
refs: &[&str],
|
||||
mixin: bool,
|
||||
) -> Vec<u8> {
|
||||
let mut pool: Vec<Vec<u8>> = Vec::new();
|
||||
let utf = |pool: &mut Vec<Vec<u8>>, s: &str| -> u16 {
|
||||
let mut e = vec![1];
|
||||
e.extend((s.len() as u16).to_be_bytes());
|
||||
e.extend(s.as_bytes());
|
||||
pool.push(e);
|
||||
pool.len() as u16
|
||||
};
|
||||
let class = |pool: &mut Vec<Vec<u8>>, s: &str| -> u16 {
|
||||
let u = utf(pool, s);
|
||||
let mut e = vec![7];
|
||||
e.extend(u.to_be_bytes());
|
||||
pool.push(e);
|
||||
pool.len() as u16
|
||||
};
|
||||
let this = class(&mut pool, name);
|
||||
let sup = class(&mut pool, superclass);
|
||||
for r in refs {
|
||||
class(&mut pool, r);
|
||||
}
|
||||
// A long takes two slots.
|
||||
pool.push(vec![5, 0, 0, 0, 0, 0, 0, 0, 1]);
|
||||
pool.push(Vec::new());
|
||||
if mixin {
|
||||
utf(&mut pool, "Lorg/spongepowered/asm/mixin/Mixin;");
|
||||
}
|
||||
let desc = utf(&mut pool, "()V");
|
||||
let names: Vec<u16> = methods.iter().map(|m| utf(&mut pool, m)).collect();
|
||||
let mut out = vec![0xCA, 0xFE, 0xBA, 0xBE, 0, 0, 0, 65];
|
||||
out.extend(((pool.len() + 1) as u16).to_be_bytes());
|
||||
for e in &pool {
|
||||
out.extend(e);
|
||||
}
|
||||
out.extend([0, 0x21]);
|
||||
out.extend(this.to_be_bytes());
|
||||
out.extend(sup.to_be_bytes());
|
||||
out.extend([0, 0]); // interfaces
|
||||
out.extend([0, 0]); // fields
|
||||
out.extend((names.len() as u16).to_be_bytes());
|
||||
for n in names {
|
||||
out.extend([0, 1]);
|
||||
out.extend(n.to_be_bytes());
|
||||
out.extend(desc.to_be_bytes());
|
||||
// One attribute, to be skipped.
|
||||
out.extend([0, 1, 0, 1, 0, 0, 0, 2, 0, 0]);
|
||||
}
|
||||
out.extend([0, 0]); // class attributes
|
||||
out
|
||||
}
|
||||
|
||||
/// A class extending `superclass` and declaring nothing.
|
||||
pub fn class_file(name: &str, superclass: &str) -> Vec<u8> {
|
||||
class_with(name, superclass, &[], &[], false)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::tests_support::class_with as class_file;
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn reads_the_header_methods_and_pool() {
|
||||
let bytes = class_file(
|
||||
"a/Lamp",
|
||||
"net/minecraft/world/level/block/Block",
|
||||
&["<init>", "useWithoutItem", "lambda$x$0"],
|
||||
&["net/minecraft/world/item/Item"],
|
||||
false,
|
||||
);
|
||||
let c = parse(&bytes).unwrap();
|
||||
assert_eq!(c.name, "a/Lamp");
|
||||
assert_eq!(c.superclass, "net/minecraft/world/level/block/Block");
|
||||
assert_eq!(c.methods, ["useWithoutItem"]);
|
||||
assert!(c.refs.contains("net/minecraft/world/item/Item"));
|
||||
assert!(!c.mixin);
|
||||
assert!(parse(&bytes[..bytes.len() - 3]).is_none());
|
||||
assert!(parse(b"not a class").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn follows_own_classes_to_the_game() {
|
||||
let block = "net/minecraft/world/level/block/Block";
|
||||
let files = [
|
||||
// Looks only: a template covers it.
|
||||
class_file("m/Plain", block, &["getStateForPlacement"], &[], false),
|
||||
class_file("m/Round", block, &["getShape"], &[], false),
|
||||
// Behaviour two levels down.
|
||||
class_file("m/Base", block, &["randomTick"], &[], false),
|
||||
class_file("m/Lamp", "m/Base", &[], &[], false),
|
||||
class_file(
|
||||
"m/Tile",
|
||||
"net/minecraft/world/level/block/entity/BlockEntity",
|
||||
&[],
|
||||
&[],
|
||||
false,
|
||||
),
|
||||
class_file("m/Mix", "java/lang/Object", &[], &[], true),
|
||||
class_file(
|
||||
"m/Old",
|
||||
"net/minecraft/class_2248",
|
||||
&["method_9534"],
|
||||
&[],
|
||||
false,
|
||||
),
|
||||
class_file(
|
||||
"m/Events",
|
||||
"java/lang/Object",
|
||||
&[],
|
||||
&[
|
||||
"net/neoforged/neoforge/event/entity/player/PlayerInteractEvent$RightClickBlock",
|
||||
"net/neoforged/neoforge/event/BuildCreativeModeTabContentsEvent",
|
||||
"net/neoforged/neoforge/registries/DeferredRegister",
|
||||
],
|
||||
false,
|
||||
),
|
||||
class_file(
|
||||
"m/Gem",
|
||||
"net/minecraft/world/item/Item",
|
||||
&["appendHoverText"],
|
||||
&[],
|
||||
false,
|
||||
),
|
||||
];
|
||||
let code = census(files.iter().map(Vec::as_slice));
|
||||
assert_eq!(code.classes, 9);
|
||||
let n = |f| code.features.get(&f).copied().unwrap_or(0);
|
||||
assert_eq!(n(Feature::BlockBehaviour), 2, "{code:?}");
|
||||
assert_eq!(n(Feature::BlockShape), 1);
|
||||
assert_eq!(n(Feature::BlockEntity), 1);
|
||||
assert_eq!(n(Feature::Mixin), 1);
|
||||
assert_eq!(n(Feature::Unread), 1);
|
||||
assert_eq!(n(Feature::ItemBehaviour), 0);
|
||||
assert_eq!(
|
||||
code.events.iter().collect::<Vec<_>>(),
|
||||
["PlayerInteractEvent"]
|
||||
);
|
||||
assert!(code.behaviour());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registration_only_is_not_behaviour() {
|
||||
let files = [
|
||||
class_file(
|
||||
"m/Mod",
|
||||
"java/lang/Object",
|
||||
&["register"],
|
||||
&[
|
||||
"net/neoforged/neoforge/registries/DeferredRegister",
|
||||
"net/minecraft/world/level/block/Block",
|
||||
],
|
||||
false,
|
||||
),
|
||||
class_file(
|
||||
"m/Pillar",
|
||||
"net/minecraft/world/level/block/RotatedPillarBlock",
|
||||
&[],
|
||||
&[],
|
||||
false,
|
||||
),
|
||||
];
|
||||
let code = census(files.iter().map(Vec::as_slice));
|
||||
assert!(!code.behaviour(), "{code:?}");
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,8 @@
|
||||
//! jars they downloaded and what is carried over from them stay there and
|
||||
//! are never uploaded or committed.
|
||||
pub mod carry;
|
||||
pub mod check;
|
||||
pub mod classes;
|
||||
pub mod classify;
|
||||
pub mod fetch;
|
||||
pub mod import;
|
||||
|
||||
@@ -19,6 +19,10 @@
|
||||
//! - `report <work>`: the coverage report, per mod ported, partial, not yet
|
||||
//! or not needed with the reason, in `<work>/coverage.json` and
|
||||
//! `coverage.md`.
|
||||
//! - `check <jar> <out>`: one mod jar on its own, as the launcher's mod
|
||||
//! browser installs it: carried over into `<out>/carry/`, its classes
|
||||
//! read, and the verdict (Works, Partly, Doesn't run) in
|
||||
//! `<out>/check.json`.
|
||||
//! - `port <pack> <work> [--from <folder>] [--resources <prepared>]`: every
|
||||
//! step for the portable mods, as the launcher's "Import modpack" runs it.
|
||||
//!
|
||||
@@ -30,7 +34,7 @@ use std::{
|
||||
process::ExitCode,
|
||||
};
|
||||
|
||||
const USAGE: &str = "usage: horizon-port-pack import <pack> <work> | inventory <work> [--offline] | fetch <work> [--from <folder>] [<mod id>...] | carry <work> [--resources <prepared>] [<mod id>...] | report <work> | port <pack> <work> [--from <folder>] [--resources <prepared>]";
|
||||
const USAGE: &str = "usage: horizon-port-pack import <pack> <work> | inventory <work> [--offline] | fetch <work> [--from <folder>] [<mod id>...] | carry <work> [--resources <prepared>] [<mod id>...] | report <work> | check <jar> <out> | port <pack> <work> [--from <folder>] [--resources <prepared>]";
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let mut args: Vec<String> = std::env::args().skip(1).collect();
|
||||
@@ -66,6 +70,17 @@ fn main() -> ExitCode {
|
||||
println!("{}", work.join("coverage.md").display());
|
||||
Ok(())
|
||||
}
|
||||
Some("check") => {
|
||||
let c = horizon_port_pack::check::check(path(1)?, path(2)?)?;
|
||||
println!("{}: {}. {}", c.mod_id, c.verdict.label(), c.summary);
|
||||
for p in &c.ports {
|
||||
println!(" ports: {p}");
|
||||
}
|
||||
for s in &c.skipped {
|
||||
println!(" skipped: {s}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Some("port") => {
|
||||
let work = path(2)?;
|
||||
pipeline::import(path(1)?, work, log)?;
|
||||
|
||||
@@ -302,6 +302,22 @@ cargo run -p horizon-port-pack -- report ~/.horizon/ports/pack # coverage
|
||||
cargo run -p horizon-port-pack -- port ~/Downloads/pack.zip ~/.horizon/ports/pack [--from <folder>] [--resources <root>]
|
||||
```
|
||||
|
||||
`check <jar> <out>` takes one mod jar on its own, as the launcher's mod browser installs it
|
||||
([mod-browser.md](mod-browser.md)): it carries the jar into `<out>/carry/` and reads its class
|
||||
files (constant pool, superclass, declared methods; no decompiling) for what the carry can't
|
||||
take, then writes the verdict to `<out>/check.json`. **Works**: content only, and the code just
|
||||
registers it. **Partly**: the content ports, and the code features listed don't (block entities,
|
||||
menus, entities, blocks and items with behaviour of their own, recipe types, Mixins, game events).
|
||||
**Doesn't run**: nothing to port, or a jar made for 1.20 or older. Each mod class is followed up to
|
||||
the first game class it extends; a block subclass that only overrides how it looks or is placed
|
||||
(`getStateForPlacement`, `rotate`...) is registration. Game classes are read by Mojang's names
|
||||
(26.1 and later, and NeoForge since 1.20.5); older Fabric jars name them in intermediary, so a
|
||||
class extending one counts as code that can't be read. On ten 26.3 jars (2026-10-22): Macaw's
|
||||
Fences, Windows and Furniture, Ecologics, Compressed Blocks, More Decorative Blocks and Moog's
|
||||
Nether Structures are Partly; Sodium and GeckoLib don't run (Mixins, renderers, nothing to port);
|
||||
Fabric API doesn't run (its id has a dash, which content mods can't use). A check takes 0.2 s to
|
||||
3 s, and 24 s for Compressed Blocks (18 MB, 9,360 recipes, writing the carry dominates).
|
||||
|
||||
`fetch` gets each jar the player's way, never from us: copied from a folder they have (matched
|
||||
by SHA-1, or through a CurseForge app instance's `minecraftinstance.json`), else downloaded from
|
||||
the link the pack itself gives (a `.mrpack`'s, on the format's hosts only) or, for a CurseForge
|
||||
|
||||
Reference in New Issue
Block a user