Archive incari-client (client, 26.3, clean)

This commit is contained in:
2026-11-28 00:54:38 -06:00
parent 7a6174687f
commit 12838e838c
2383 changed files with 280266 additions and 0 deletions
@@ -0,0 +1,6 @@
# tools/build
- Output must stay deterministic: the same inputs give byte-identical patch files on every
machine. Don't add timestamps, machine paths or locale-dependent formatting to anything written.
- Nothing Mojang may leave `work/`. Every such path is defined in `Workspace`.
- Test: `./gradlew :tools:build:test`. The end-to-end check is `./incari setup && ./incari rebuild --check`.
+53
View File
@@ -0,0 +1,53 @@
# tools/build: the `incari` CLI
Turns a fresh clone into a patched, editable Minecraft source tree, and edits to that tree back
into patch files. This is how the repo stays patch-only. Run it through `./incari` at the repo root.
| Command | Does |
| --- | --- |
| `./incari setup` | `fetch` + `decompile` + `apply`: a fresh clone to `work/client`; also clones the pinned Horizon into `work/horizon` (ADR 0068), warning instead of failing |
| `./incari fetch` | Download the pinned version's jar and libraries, checked against Mojang's SHA-1s |
| `./incari decompile` | Vineflower into `work/decompiled/<version>` (skipped if unchanged) |
| `./incari apply [--force]` | Rebuild `work/client` from the decompiled source, `classes.txt` and `patches/`. Refuses to drop unsaved work without `--force` |
| `./incari rebuild [--check]` | Regenerate `patches/` from `work/client`'s commits. `--check` fails if stale, or if a replaced class's stamp is |
| `./incari classes [--stamp]` | List the classes `classes.txt` replaces whose Mojang original changed since their stamp; `--stamp` records the current ones once reviewed ([`docs/updating.md`](../../docs/updating.md)) |
| `./incari assets` | Download the asset index and sounds for the desktop and dev server |
| `./incari build [--out <dir>] [--only fast\|compatible\|rust] [--no-sounds] [--html]` | Release builds as one folder (`dist/web/`, ADR 0028) or one HTML file (`--html`, ADR 0057). The folder has the experimental Rust build in `rust/` when this machine can build it (ADR 0068; skipped, saying why, otherwise). Never share either ([`docs/self-hosting.md`](../../docs/self-hosting.md)) |
| `./incari survey` | The TeaVM compile survey ([`tools/survey`](../survey/README.md)) |
| `./incari copycheck` | Fail on code copied from the game ([`tools/copycheck`](../copycheck/README.md)) |
Code: `Main`; `GameFiles` fetches, `Decompiler` decompiles, `ClientTree` applies and rebuilds,
`WebBuild` runs `build`, `Horizon` fetches and builds the Rust build ([`rust/`](../../rust/README.md)).
## `work/` (git-ignored)
```
work/
cache/ manifest, version JSON, client.jar, libraries, jar lists for Gradle
decompiled/<version>/ Vineflower's output and a stamp of its inputs
client/ git repo: tag vendor -> classes.txt applied (tag base) -> one commit per patch
survey/<version>/ survey output
horizon/ the pinned Horizon commit (Rust build); horizon-stage/ with rust/mods applied,
horizon-resources/<version>/, horizon-target/, horizon-out/; horizon-override/,
an INCARI_HORIZON_DIR checkout's files without its ignored builds
```
## Invariants
- **Nothing of Mojang's leaves `work/`.** Only patch files and `classes.txt` are tracked.
- **Deterministic:** pinned jar and Vineflower, fixed options, git run without user config, so the
same commits give byte-identical patches.
- **Patches carry as little Mojang text as possible:** one line of context, no function names in
hunk headers, no file deletions. `rebuild` rejects a commit that deletes a file or edits a class
`classes.txt` owns.
- **Unsaved work is never silently dropped.**
- **Commit subjects are `<subsystem>: <summary>`;** the subsystem is the folder under `patches/`.
- **Every replacement names its original:** a `classes.txt` stamp (`<version>@<vendor blob>`) per
`replace` line, so a Minecraft bump that changes the original is flagged, not silently drifted.
## How to test
```sh
./gradlew :tools:build:test # a synthetic vendor tree: no network, no Mojang jar
./incari setup && ./incari rebuild --check # what CI runs end to end
```
@@ -0,0 +1,21 @@
plugins {
application
}
dependencies {
implementation(libs.gson)
// Not called directly: the decompile step runs Vineflower in a child JVM (its own heap,
// and a crash can't take the CLI down). It sits on the runtime classpath so the CLI can
// find the jar.
runtimeOnly(libs.vineflower)
testImplementation(platform(libs.junit.bom))
testImplementation(libs.junit.jupiter)
testImplementation(libs.assertj)
testRuntimeOnly(libs.junit.launcher)
}
application {
applicationName = "incari-build"
mainClass = "incari.tools.build.Main"
}
@@ -0,0 +1,88 @@
package incari.tools.build;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* The game's assets (sounds, music, languages, the panorama...) for the desktop runtime, in the
* launcher's layout under {@code work/cache/assets}, so the game finds them with
* {@code --assetsDir} and {@code --assetIndex} exactly as with Mojang's launcher.
*
* <p>About 480 MB for 26.3. Only the desktop runtime needs them; setup and CI don't download them.
*/
public final class Assets {
static final URI OBJECT_HOST = URI.create("https://resources.download.minecraft.net/");
private Assets() {}
/** One asset: where the game looks for it, and its content hash (also its file name). */
record AssetObject(String name, String hash, long size) {
String objectPath() {
return hash.substring(0, 2) + "/" + hash;
}
}
/** Downloads the version's asset index and every object it lists that isn't cached yet. */
public static String fetch(Workspace ws, BuildConfig config, Downloader downloader)
throws IOException, InterruptedException {
GameFiles game = GameFiles.load(ws, config);
MojangMetadata.AssetIndex index = game.version().assetIndex();
if (index == null) {
throw new CliException("The version JSON for " + game.version().id() + " has no asset index");
}
Path indexFile = ws.assetsDir().resolve("indexes").resolve(index.id() + ".json");
downloader.fetch(index.download().url(), index.download().sha1(), indexFile);
List<AssetObject> objects = parseIndex(Files.readString(indexFile));
Path objectsDir = ws.assetsDir().resolve("objects");
long totalBytes = objects.stream().mapToLong(AssetObject::size).sum();
Log.step("Downloading " + objects.size() + " assets (" + totalBytes / (1024 * 1024)
+ " MB, cached ones are skipped)");
try (ExecutorService pool = Executors.newFixedThreadPool(16)) {
List<Future<?>> pending = new ArrayList<>();
for (AssetObject object : objects) {
pending.add(pool.submit(() -> {
downloader.fetch(
OBJECT_HOST.resolve(object.objectPath()),
object.hash(),
objectsDir.resolve(object.objectPath()));
return null;
}));
}
for (Future<?> future : pending) {
Concurrency.join(future);
}
}
return index.id();
}
/** The objects an index lists, one per distinct hash (many names share a file), sorted by hash. */
static List<AssetObject> parseIndex(String indexJson) {
JsonObject objects = JsonParser.parseString(indexJson).getAsJsonObject().getAsJsonObject("objects");
Map<String, AssetObject> byHash = new TreeMap<>();
for (Map.Entry<String, JsonElement> entry : objects.entrySet()) {
JsonObject object = entry.getValue().getAsJsonObject();
String hash = object.get("hash").getAsString();
if (!hash.matches("[0-9a-f]{40}")) {
throw new CliException("Asset " + entry.getKey() + " has an invalid hash: " + hash);
}
byHash.putIfAbsent(
hash,
new AssetObject(entry.getKey(), hash, object.get("size").getAsLong()));
}
return List.copyOf(byHash.values());
}
}
@@ -0,0 +1,39 @@
package incari.tools.build;
import java.io.IOException;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Properties;
/**
* The pinned game version from {@code incari.properties} at the repo root.
*
* <p>Pinning the hashes, not just the version id, matters because patches are text diffs
* against decompiled output: if Mojang ever re-uploaded a jar under the same id, unpinned
* builds would silently drift apart.
*/
public record BuildConfig(String minecraftVersion, String versionJsonSha1, String clientSha1) {
public static final String FILE_NAME = "incari.properties";
public static BuildConfig load(Path repoRoot) throws IOException {
Path file = repoRoot.resolve(FILE_NAME);
Properties props = new Properties();
try (Reader reader = Files.newBufferedReader(file)) {
props.load(reader);
}
return new BuildConfig(
require(props, file, "minecraft.version"),
require(props, file, "minecraft.versionJson.sha1"),
require(props, file, "minecraft.client.sha1"));
}
private static String require(Properties props, Path file, String key) {
String value = props.getProperty(key);
if (value == null || value.isBlank()) {
throw new CliException("Missing '" + key + "' in " + file);
}
return value.trim();
}
}
@@ -0,0 +1,186 @@
package incari.tools.build;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jspecify.annotations.Nullable;
/**
* Whole-file changes to the vendor tree: classes Incari deletes outright, and classes it
* replaces with its own source file.
*
* <p>These don't go through patches on purpose. A diff that deletes or rewrites a whole
* Mojang file has to contain every one of its lines, which would republish them. A manifest
* line names the class and contains no Mojang code at all.
*
* <p>Format of {@code patches/classes.txt}, one entry per line, {@code #} starts a comment:
* <pre>
* delete net.minecraft.client.telemetry.ClientTelemetryManager
* replace com.mojang.blaze3d.vertex.ByteBufferBuilder render-webgl2/src/vendor/java/com/mojang/blaze3d/vertex/ByteBufferBuilder.java 26.3@3f2a9c1b07de
* </pre>
* Replacement paths are relative to the repo root. A replace line's last column, its {@link Stamp},
* records which Mojang original the replacement was last checked against, so a new Minecraft
* version (or decompiler) that changes the original is flagged for review instead of drifting
* silently. {@code ./incari classes --stamp} writes it; nobody types it.
*/
public record ClassManifest(List<Entry> entries) {
public static final String FILE_NAME = "classes.txt";
private static final Pattern CLASS_NAME = Pattern.compile("[A-Za-z_$][\\w$]*(\\.[A-Za-z_$][\\w$]*)*");
private static final Pattern STAMP = Pattern.compile("([^@\\s]+)@([0-9a-f]{7,40})");
/** A replace line up to its source path, its stamp if any, and what follows (a comment). */
private static final Pattern REPLACE_LINE =
Pattern.compile("^(\\s*replace\\s+(\\S+)\\s+[^\\s#]+)(?:\\s+[^\\s#]+)?(\\s*(?:#.*)?)$");
/** Blob ids are abbreviated to this many hex digits in the manifest. */
public static final int STAMP_DIGITS = 12;
public sealed interface Entry {
String className();
/** Path of the class's source file, relative to the client tree root. */
default String treePath() {
return Workspace.CLIENT_SOURCE_DIR + "/" + className().replace('.', '/') + ".java";
}
}
public record Delete(String className) implements Entry {}
/**
* The vendor original a replacement was checked against: the Minecraft version and the git blob
* id of its decompiled, unpatched source (abbreviated). Names no Mojang code.
*/
public record Stamp(String version, String blob) {
@Override
public String toString() {
return version + "@" + blob;
}
/** Whether a full or abbreviated blob id is this stamp's file. */
public boolean matches(String otherBlob) {
return otherBlob.startsWith(blob) || blob.startsWith(otherBlob);
}
}
/** {@code stamp} is null until {@code ./incari classes --stamp} records one. */
public record Replace(
String className, String source, @Nullable Stamp stamp) implements Entry {
public Replace(String className, String source) {
this(className, source, null);
}
}
public static ClassManifest load(Path file) throws IOException {
if (!Files.isRegularFile(file)) {
return new ClassManifest(List.of());
}
return parse(Files.readAllLines(file), file.toString());
}
static ClassManifest parse(List<String> lines, String origin) {
List<Entry> entries = new ArrayList<>();
Set<String> seen = new HashSet<>();
for (int i = 0; i < lines.size(); i++) {
String line = lines.get(i);
int hash = line.indexOf('#');
String content = (hash >= 0 ? line.substring(0, hash) : line).strip();
if (content.isEmpty()) {
continue;
}
String where = origin + ":" + (i + 1);
String[] parts = content.split("\\s+", -1);
Entry entry =
switch (parts[0]) {
case "delete" -> {
expect(parts.length == 2, where, "expected: delete <class>");
yield new Delete(className(parts[1], where));
}
case "replace" -> {
expect(
parts.length == 3 || parts.length == 4,
where,
"expected: replace <class> <source path> [<version>@<vendor blob>]");
String source = parts[2];
expect(
!source.startsWith("/") && !source.contains("..") && !source.startsWith("work/"),
where,
"replacement source must be a repo-relative path outside work/");
@Nullable Stamp stamp = null;
if (parts.length == 4) {
Matcher m = STAMP.matcher(parts[3]);
expect(
m.matches(),
where,
"'" + parts[3] + "' is not a stamp (<version>@<vendor blob>);"
+ " write it with ./incari classes --stamp");
stamp = new Stamp(m.group(1), m.group(2));
}
yield new Replace(className(parts[1], where), source, stamp);
}
default -> throw new CliException(where + ": unknown action '" + parts[0] + "'");
};
expect(seen.add(entry.className()), where, entry.className() + " is listed twice");
entries.add(entry);
}
return new ClassManifest(List.copyOf(entries));
}
/**
* The manifest's lines with each replace line's stamp set from {@code stamps} (by class name),
* aligned in one column. Every other line, comments included, is kept as it is.
*/
static List<String> withStamps(List<String> lines, Map<String, Stamp> stamps) {
int width = 0;
for (String line : lines) {
Matcher m = REPLACE_LINE.matcher(line);
if (m.matches() && stamps.containsKey(m.group(2))) {
width = Math.max(width, m.group(1).length());
}
}
List<String> out = new ArrayList<>(lines.size());
for (String line : lines) {
Matcher m = REPLACE_LINE.matcher(line);
Stamp stamp = m.matches() ? stamps.get(m.group(2)) : null;
if (stamp == null) {
out.add(line);
continue;
}
String head = m.group(1);
out.add(head + " ".repeat(width - head.length() + 2) + stamp + m.group(3));
}
return out;
}
/** Tree paths this manifest owns. Patches must not touch them. */
public Set<String> treePaths() {
Set<String> paths = new HashSet<>();
for (Entry entry : entries) {
paths.add(entry.treePath());
}
return paths;
}
private static String className(String value, String where) {
expect(
CLASS_NAME.matcher(value).matches() && !value.contains("$"),
where,
"'" + value + "' is not a top-level class name (nested classes can't be replaced alone)");
return value;
}
private static void expect(boolean condition, String where, String message) {
if (!condition) {
throw new CliException(where + ": " + message);
}
}
}
@@ -0,0 +1,20 @@
package incari.tools.build;
import org.jspecify.annotations.Nullable;
/**
* An expected failure with a message meant for the person running the CLI. {@link Main}
* prints it without a stack trace; anything else is treated as a bug in the tool.
*/
public class CliException extends RuntimeException {
private static final long serialVersionUID = 1L;
public CliException(String message) {
super(message);
}
public CliException(String message, @Nullable Throwable cause) {
super(message, cause);
}
}
@@ -0,0 +1,450 @@
package incari.tools.build;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;
import org.jspecify.annotations.Nullable;
/**
* The editable client tree in {@code work/client}: a git repository whose history is
*
* <ol>
* <li>one vendor commit (Vineflower's output, untouched), tagged {@code vendor};
* <li>one commit applying {@code patches/classes.txt}, tagged {@code base};
* <li>one commit per patch file.
* </ol>
*
* <p>People edit the tree and commit there (one concern per commit, subject
* {@code "<subsystem>: <summary>"}), then {@link #rebuildPatches} turns the commits after
* {@code base} back into patch files. Patch files are never edited by hand.
*/
public final class ClientTree {
public static final String VENDOR_TAG = "vendor";
public static final String BASE_TAG = "base";
/** HEAD at the last apply or rebuild. Anything else means unsaved work. */
private static final String SYNCED_HEAD_FILE = "incari-synced-head";
/** Which decompiled output the vendor commit holds, so re-applying can skip the copy. */
private static final String VENDOR_STAMP_FILE = "incari-vendor-stamp";
/**
* Minimal context keeps Mojang lines out of patch files (a unified diff repeats its context
* lines). Full blob ids let {@code git am --3way} fall back to a merge when context drifts.
*/
private static final List<String> FORMAT_PATCH_OPTIONS = List.of(
"--stdout",
"--zero-commit",
"--no-signature",
"--no-stat",
"--no-numbered",
"--no-renames",
"--full-index",
"--no-color",
"--no-ext-diff",
"-U1");
private final Workspace ws;
private final Git git;
public ClientTree(Workspace ws) {
this.ws = ws;
this.git = new Git(ws.clientTree());
}
// ------------------------------------------------------------------------------------
// Apply: decompiled sources + manifest + patches -> work/client
// ------------------------------------------------------------------------------------
/**
* Rebuilds the tree from the decompiled sources and the tracked patches. Refuses to throw
* away commits or edits that {@code rebuild} hasn't saved, unless {@code force}.
*/
public void apply(Path decompiledDir, String version, boolean force) throws IOException, InterruptedException {
Path tree = ws.clientTree();
if (Files.isDirectory(tree.resolve(".git")) && !force) {
requireNoUnsavedWork();
}
String vendorStamp = Files.readString(decompiledDir.resolve(".incari-decompile-stamp"));
if (vendorIsCurrent(vendorStamp)) {
Log.step("Resetting work/client to the vendor commit");
abortInProgressAm();
git.run("reset", "--quiet", "--hard", VENDOR_TAG);
git.run("clean", "--quiet", "-fdx");
} else {
createVendorCommit(decompiledDir, version, vendorStamp);
}
writeAttributes();
applyManifest();
// Before the patches: a conflict there stops the apply, and this is the bump's other half.
reportDrift(replacementDrift(version), version);
applyPatches();
recordSyncedHead();
}
private boolean vendorIsCurrent(String vendorStamp) throws IOException, InterruptedException {
Path stampFile = ws.clientTree().resolve(".git").resolve(VENDOR_STAMP_FILE);
return Files.isRegularFile(stampFile)
&& Files.readString(stampFile).equals(vendorStamp)
&& git.tryRun("rev-parse", "--verify", "--quiet", VENDOR_TAG).exitCode() == 0;
}
private void createVendorCommit(Path decompiledDir, String version, String vendorStamp)
throws IOException, InterruptedException {
Path tree = ws.clientTree();
Log.step("Creating work/client from the decompiled " + version + " sources");
FileTrees.deleteRecursively(tree);
Files.createDirectories(tree);
git.run("init", "--quiet");
int files = FileTrees.copyTree(decompiledDir, tree.resolve(Workspace.CLIENT_SOURCE_DIR), ".java");
Log.info(files + " source files");
git.run("add", "--all");
git.run("commit", "--quiet", "--no-verify", "-m", "Vendor: Minecraft " + version + " (decompiled, unmodified)");
git.run("tag", VENDOR_TAG);
Files.writeString(tree.resolve(".git").resolve(VENDOR_STAMP_FILE), vendorStamp);
}
private void writeAttributes() throws IOException {
Path info = ws.clientTree().resolve(".git").resolve("info");
Files.createDirectories(info);
Files.writeString(info.resolve("attributes"), "* diff=incari\n");
}
private void applyManifest() throws IOException, InterruptedException {
ClassManifest manifest = ClassManifest.load(ws.classManifest());
Path tree = ws.clientTree();
int deleted = 0;
int replaced = 0;
for (ClassManifest.Entry entry : manifest.entries()) {
Path target = tree.resolve(entry.treePath());
switch (entry) {
case ClassManifest.Delete delete -> {
requireExists(target, delete.className(), "delete");
Files.delete(target);
deleted++;
}
case ClassManifest.Replace replace -> {
requireExists(target, replace.className(), "replace");
Path source = ws.repoRoot().resolve(replace.source());
if (!Files.isRegularFile(source)) {
throw new CliException(ClassManifest.FILE_NAME + ": replacement source " + replace.source()
+ " for " + replace.className() + " doesn't exist");
}
Files.copy(source, target, java.nio.file.StandardCopyOption.REPLACE_EXISTING);
replaced++;
}
}
}
git.run("add", "--all");
git.run(
"commit",
"--quiet",
"--no-verify",
"--allow-empty",
"-m",
"Incari: class manifest (" + deleted + " deleted, " + replaced + " replaced)");
git.run("tag", "--force", BASE_TAG);
if (!manifest.entries().isEmpty()) {
Log.info("Class manifest: " + deleted + " deleted, " + replaced + " replaced");
}
}
private static void requireExists(Path target, String className, String action) {
if (!Files.isRegularFile(target)) {
throw new CliException(ClassManifest.FILE_NAME + ": can't " + action + " " + className
+ ", it isn't in the vendor tree (renamed or removed in this Minecraft version?)");
}
}
private void applyPatches() throws IOException, InterruptedException {
List<PatchSet.PatchFile> patches = PatchSet.list(ws.patchesDir());
if (patches.isEmpty()) {
Log.step("No patches to apply");
return;
}
Log.step("Applying " + patches.size() + " patches");
List<String> args = new ArrayList<>(List.of("am", "--quiet", "--3way", "--keep-cr", "--no-gpg-sign"));
for (PatchSet.PatchFile patch : patches) {
args.add(patch.path().toString());
}
ProcessRunner.Result result = git.tryRun(args.toArray(String[]::new));
if (result.exitCode() != 0) {
String current =
git.tryRun("am", "--show-current-patch=diff").exitCode() == 0 ? currentAmPatchName() : "a patch";
throw new CliException(
"Patch failed to apply: " + current + "\n" + result.stderr().strip() + "\n"
+ result.stdout().strip() + "\n\n"
+ "work/client is stopped mid-apply. To fix it: resolve the conflicts in work/client, then\n"
+ " git -C work/client add <files> && git -C work/client am --continue\n"
+ "and once every patch is in, save the result with ./incari rebuild");
}
}
private String currentAmPatchName() throws IOException {
Path next = ws.clientTree().resolve(".git/rebase-apply/next");
Path last = ws.clientTree().resolve(".git/rebase-apply/last");
if (!Files.isRegularFile(next)) {
return "a patch";
}
String n = Files.readString(next).strip();
return "patch " + n + " of " + Files.readString(last).strip();
}
private void abortInProgressAm() throws IOException, InterruptedException {
if (Files.isDirectory(ws.clientTree().resolve(".git/rebase-apply"))) {
git.run("am", "--abort");
}
}
// ------------------------------------------------------------------------------------
// Rebuild: commits after `base` -> patches/
// ------------------------------------------------------------------------------------
/** What a rebuild wrote, or (with {@code check}) would write. */
public record RebuildResult(int written, int unchanged, int removed) {
public boolean changed() {
return written > 0 || removed > 0;
}
}
/**
* Turns every commit after {@code base} into a patch file. With {@code check}, writes
* nothing and only reports whether {@code patches/} is out of date (for CI).
*/
public RebuildResult rebuildPatches(boolean check) throws IOException, InterruptedException {
requireTree();
if (Files.isDirectory(ws.clientTree().resolve(".git/rebase-apply"))) {
throw new CliException("work/client is in the middle of applying patches. Finish with"
+ " `git -C work/client am --continue` (or start over with ./incari apply --force).");
}
if (!git.run("status", "--porcelain").isBlank()) {
throw new CliException("work/client has uncommitted changes. Commit them first (one concern per commit,"
+ " subject \"<subsystem>: <summary>\"), then run ./incari rebuild.");
}
if (git.tryRun("merge-base", "--is-ancestor", BASE_TAG, "HEAD").exitCode() != 0) {
throw new CliException(
"HEAD in work/client doesn't build on the '" + BASE_TAG + "' tag. Rebase your commits onto it.");
}
Set<String> manifestPaths = ClassManifest.load(ws.classManifest()).treePaths();
List<String> commits =
git.run("rev-list", "--reverse", BASE_TAG + "..HEAD").lines().toList();
Map<String, byte[]> generated = new LinkedHashMap<>();
for (int i = 0; i < commits.size(); i++) {
String commit = commits.get(i);
validateCommit(commit, manifestPaths);
String subject = git.run("log", "-1", "--format=%s", commit).strip();
String file = PatchSet.fileFor(i + 1, subject);
List<String> args = new ArrayList<>(List.of("format-patch", "-1"));
args.addAll(FORMAT_PATCH_OPTIONS);
args.add(commit);
generated.put(file, git.run(args.toArray(String[]::new)).getBytes(StandardCharsets.UTF_8));
}
return writePatches(generated, check);
}
private void validateCommit(String commit, Set<String> manifestPaths) throws IOException, InterruptedException {
String shortId = commit.substring(0, 10);
if (git.run("rev-list", "--parents", "-n", "1", commit).strip().split(" ").length > 2) {
throw new CliException(
"Commit " + shortId + " is a merge. Patches must be a linear history; rebase instead.");
}
String changes = git.run("diff-tree", "--no-commit-id", "--name-status", "-r", "--no-renames", commit);
for (String line : changes.lines().toList()) {
String[] parts = line.split("\t", 2);
String status = parts[0];
String path = parts[1];
if (status.startsWith("D")) {
throw new CliException("Commit " + shortId + " deletes " + path + ". A patch that deletes a file"
+ " republishes all of it; add a `delete` line to patches/classes.txt instead.");
}
if (manifestPaths.contains(path)) {
throw new CliException("Commit " + shortId + " edits " + path + ", which patches/classes.txt deletes or"
+ " replaces. Edit the replacement source in the repo instead.");
}
}
}
private RebuildResult writePatches(Map<String, byte[]> generated, boolean check)
throws IOException, InterruptedException {
Path patchesDir = ws.patchesDir();
List<Path> existing = new ArrayList<>();
if (Files.isDirectory(patchesDir)) {
try (Stream<Path> files = Files.walk(patchesDir)) {
files.filter(p -> p.toString().endsWith(".patch")).forEach(existing::add);
}
}
int written = 0;
int unchanged = 0;
for (Map.Entry<String, byte[]> entry : generated.entrySet()) {
Path target = patchesDir.resolve(entry.getKey());
existing.remove(target);
if (Files.isRegularFile(target) && java.util.Arrays.equals(Files.readAllBytes(target), entry.getValue())) {
unchanged++;
continue;
}
written++;
if (check) {
Log.info("out of date: patches/" + entry.getKey());
} else {
Files.createDirectories(target.getParent());
Files.write(target, entry.getValue());
}
}
for (Path stale : existing) {
if (check) {
Log.info("stale: " + ws.repoRoot().relativize(stale));
} else {
Files.delete(stale);
Path parent = stale.getParent();
if (parent != null) {
deleteIfEmpty(parent);
}
}
}
if (!check) {
recordSyncedHead();
}
return new RebuildResult(written, unchanged, existing.size());
}
private void deleteIfEmpty(Path dir) throws IOException {
if (dir.equals(ws.patchesDir())) {
return;
}
try (Stream<Path> entries = Files.list(dir)) {
if (entries.findAny().isEmpty()) {
Files.delete(dir);
}
}
}
// ------------------------------------------------------------------------------------
// Replacement stamps: has Mojang changed a class Incari replaces?
// ------------------------------------------------------------------------------------
/**
* A replaced class whose vendor original isn't the one its stamp in {@code classes.txt} names
* (or that has no stamp yet). {@code recorded} is null when there's no stamp.
*/
public record Drift(
String className, ClassManifest.@Nullable Stamp recorded, ClassManifest.Stamp current, String path) {}
/**
* Each replaced class whose decompiled original differs from the one it was last checked
* against, read from the {@code vendor} commit, so it works mid-apply too.
*/
public List<Drift> replacementDrift(String version) throws IOException, InterruptedException {
requireTree();
List<Drift> drift = new ArrayList<>();
for (ClassManifest.Entry entry : ClassManifest.load(ws.classManifest()).entries()) {
if (!(entry instanceof ClassManifest.Replace replace)) {
continue;
}
ClassManifest.Stamp current = vendorStamp(replace, version);
ClassManifest.@Nullable Stamp recorded = replace.stamp();
if (recorded == null || !recorded.matches(current.blob())) {
drift.add(new Drift(replace.className(), recorded, current, replace.treePath()));
}
}
return drift;
}
/** Records the current vendor original of every replaced class in {@code classes.txt}. */
public int stampReplacements(String version) throws IOException, InterruptedException {
requireTree();
Map<String, ClassManifest.Stamp> stamps = new LinkedHashMap<>();
for (ClassManifest.Entry entry : ClassManifest.load(ws.classManifest()).entries()) {
if (entry instanceof ClassManifest.Replace replace) {
stamps.put(replace.className(), vendorStamp(replace, version));
}
}
List<String> lines = Files.readAllLines(ws.classManifest());
List<String> stamped = ClassManifest.withStamps(lines, stamps);
if (!stamped.equals(lines)) {
Files.write(ws.classManifest(), stamped);
}
return stamps.size();
}
/** Logs each drifted replacement, with the command that shows what Mojang changed. */
public void reportDrift(List<Drift> drift, String version) {
for (Drift d : drift) {
if (d.recorded() == null) {
Log.warn(d.className() + " is replaced but has no stamp in patches/classes.txt");
continue;
}
Log.warn(d.className() + " changed upstream: replacement written against " + d.recorded()
+ ", vendor is now " + d.current());
String relative = d.path().substring(Workspace.CLIENT_SOURCE_DIR.length() + 1);
Path old = ws.decompiledDir(d.recorded().version()).resolve(relative);
Path now = ws.decompiledDir(version).resolve(relative);
if (!d.recorded().version().equals(version) && Files.isRegularFile(old)) {
Log.info("see what changed: git diff --no-index "
+ ws.repoRoot().relativize(old) + " " + ws.repoRoot().relativize(now));
} else if (d.recorded().version().equals(version)) {
Log.info("same version, different decompiled source: a decompiler change?");
}
}
if (!drift.isEmpty()) {
Log.info("Bring each replacement in line with the new original, then: ./incari classes --stamp");
}
}
private ClassManifest.Stamp vendorStamp(ClassManifest.Replace replace, String version)
throws IOException, InterruptedException {
ProcessRunner.Result result =
git.tryRun("rev-parse", "--verify", "--quiet", VENDOR_TAG + ":" + replace.treePath());
if (result.exitCode() != 0) {
throw new CliException(ClassManifest.FILE_NAME + ": " + replace.className()
+ " isn't in the vendor tree (renamed or removed in this Minecraft version?)");
}
return new ClassManifest.Stamp(version, result.stdout().strip().substring(0, ClassManifest.STAMP_DIGITS));
}
// ------------------------------------------------------------------------------------
// Guarding unsaved work
// ------------------------------------------------------------------------------------
private void recordSyncedHead() throws IOException, InterruptedException {
String head = git.run("rev-parse", "HEAD").strip();
Files.writeString(ws.clientTree().resolve(".git").resolve(SYNCED_HEAD_FILE), head);
}
private void requireNoUnsavedWork() throws IOException, InterruptedException {
Path synced = ws.clientTree().resolve(".git").resolve(SYNCED_HEAD_FILE);
if (!Files.isRegularFile(synced)) {
// A tree from an interrupted first apply: nothing in it was ever the user's.
return;
}
boolean dirty = !git.run("status", "--porcelain").isBlank();
boolean moved = !git.run("rev-parse", "HEAD")
.strip()
.equals(Files.readString(synced).strip());
if (dirty || moved) {
throw new CliException(
"work/client has " + (dirty ? "uncommitted changes" : "commits not saved to patches/")
+ ". Applying would discard them.\n"
+ " Save them first: commit, then ./incari rebuild\n"
+ " Or throw them away: ./incari apply --force");
}
}
private void requireTree() {
if (!Files.isDirectory(ws.clientTree().resolve(".git"))) {
throw new CliException("work/client doesn't exist yet. Run: ./incari setup");
}
}
}
@@ -0,0 +1,28 @@
package incari.tools.build;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
final class Concurrency {
private Concurrency() {}
/** Waits for {@code future}, rethrowing its failure unwrapped so CLI errors keep their message. */
static void join(Future<?> future) throws IOException, InterruptedException {
try {
future.get();
} catch (ExecutionException e) {
Throwable cause = e.getCause();
if (cause == null) {
throw new IllegalStateException(e);
}
switch (cause) {
case IOException io -> throw io;
case RuntimeException runtime -> throw runtime;
case InterruptedException interrupted -> throw interrupted;
case Throwable other -> throw new IllegalStateException(other);
}
}
}
}
@@ -0,0 +1,99 @@
package incari.tools.build;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.JarFile;
/**
* Runs Vineflower over the client jar into {@code work/decompiled/<version>}.
*
* <p>The output is only as stable as its inputs: the same jar, the same Vineflower version
* and the same options must give byte-identical sources on every machine, or patches stop
* applying. All three go into a stamp file, and a matching stamp skips the (multi-minute)
* decompile.
*/
public final class Decompiler {
private static final String MAIN_CLASS = "org.jetbrains.java.decompiler.main.decompiler.ConsoleDecompiler";
private static final String STAMP_FILE = ".incari-decompile-stamp";
/**
* Changing any of these changes every decompiled file, so every patch must be
* regenerated. Treat an edit here like a Minecraft version bump.
*/
private static final List<String> OPTIONS = List.of(
"--folder",
// Only classes: assets and data stay in the jar and never enter the git tree.
"--skip-extra-files",
// Mojang's own style, so the tree reads like the game's sources.
"--indent-string= ",
"--log-level=warn");
private Decompiler() {}
public static void decompile(Workspace ws, GameFiles game) throws IOException, InterruptedException {
Path output = ws.decompiledDir(game.version().id());
Path vineflowerJar = vineflowerJar();
String stamp = stamp(game, vineflowerJar);
Path stampFile = output.resolve(STAMP_FILE);
if (Files.isRegularFile(stampFile) && Files.readString(stampFile).equals(stamp)) {
Log.step("Decompiled sources for " + game.version().id() + " are up to date");
return;
}
Log.step("Decompiling " + game.version().id() + " with Vineflower (takes a few minutes)");
Path temp = output.resolveSibling(output.getFileName() + ".tmp");
FileTrees.deleteRecursively(temp);
Files.createDirectories(temp);
List<String> command = new ArrayList<>();
command.add(ProcessRunner.javaExecutable());
command.add(System.getenv().getOrDefault("INCARI_DECOMPILE_XMX", "-Xmx8g"));
command.add("-cp");
command.add(vineflowerJar.toString());
command.add(MAIN_CLASS);
command.addAll(OPTIONS);
for (GameFiles.LibraryJar library : game.libraries()) {
// Libraries let Vineflower resolve generics and overloads it would otherwise
// guess at, which means fewer casts and fewer decompile errors to patch around.
command.add("-e=" + library.jar());
}
command.add(game.clientJar().toString());
command.add(temp.toString());
ProcessRunner.run(command, ws.repoRoot(), true);
Files.writeString(temp.resolve(STAMP_FILE), stamp);
FileTrees.deleteRecursively(output);
Files.move(temp, output);
}
private static String stamp(GameFiles game, Path vineflowerJar) throws IOException {
String vineflowerVersion;
try (JarFile jar = new JarFile(vineflowerJar.toFile())) {
vineflowerVersion = jar.getManifest().getMainAttributes().getValue("Implementation-Version");
}
return "client=" + Downloader.sha1(game.clientJar()) + "\n"
+ "vineflower=" + vineflowerVersion + "\n"
+ "options=" + String.join(" ", OPTIONS) + "\n"
+ "libraries="
+ game.libraries().stream()
.map(l -> l.jar().getFileName().toString())
.sorted()
.toList() + "\n";
}
private static Path vineflowerJar() {
try {
Class<?> main = Class.forName(MAIN_CLASS, false, Decompiler.class.getClassLoader());
return Path.of(
main.getProtectionDomain().getCodeSource().getLocation().toURI());
} catch (ClassNotFoundException | URISyntaxException e) {
throw new IllegalStateException("Vineflower must be on the CLI's runtime classpath", e);
}
}
}
@@ -0,0 +1,99 @@
package incari.tools.build;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.util.HexFormat;
/**
* Downloads files and checks their SHA-1. A file already on disk with the right hash is
* reused, so re-running {@code incari fetch} costs only the hash checks.
*
* <p>Writes go to a temp file first and are moved into place only after the hash matches,
* so an interrupted download never leaves a truncated jar that later steps trust.
*/
public final class Downloader {
private static final int ATTEMPTS = 3;
private final HttpClient http = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.NORMAL)
.connectTimeout(Duration.ofSeconds(30))
.build();
/** Downloads {@code url} to {@code target} unless it's already there with {@code sha1}. */
public void fetch(URI url, String sha1, Path target) throws IOException, InterruptedException {
if (Files.isRegularFile(target) && sha1(target).equals(sha1)) {
return;
}
Files.createDirectories(target.getParent());
Path temp = target.resolveSibling(target.getFileName() + ".part");
IOException last = null;
for (int attempt = 1; attempt <= ATTEMPTS; attempt++) {
try {
download(url, temp);
String actual = sha1(temp);
if (!actual.equals(sha1)) {
throw new IOException("SHA-1 mismatch for " + url + ": expected " + sha1 + ", got " + actual);
}
Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
return;
} catch (IOException e) {
last = e;
} finally {
Files.deleteIfExists(temp);
}
}
throw new CliException("Download failed after " + ATTEMPTS + " attempts: " + url, last);
}
/** Downloads without a known hash (only the version manifest, which changes over time). */
public String fetchString(URI url) throws IOException, InterruptedException {
HttpResponse<String> response = http.send(request(url), HttpResponse.BodyHandlers.ofString());
checkStatus(url, response.statusCode());
return response.body();
}
private void download(URI url, Path temp) throws IOException, InterruptedException {
HttpResponse<InputStream> response = http.send(request(url), HttpResponse.BodyHandlers.ofInputStream());
try (InputStream body = response.body()) {
checkStatus(url, response.statusCode());
Files.copy(body, temp, StandardCopyOption.REPLACE_EXISTING);
}
}
private static HttpRequest request(URI url) {
return HttpRequest.newBuilder(url).timeout(Duration.ofMinutes(5)).GET().build();
}
private static void checkStatus(URI url, int status) throws IOException {
if (status != 200) {
throw new IOException("HTTP " + status + " from " + url);
}
}
public static String sha1(Path file) throws IOException {
MessageDigest digest;
try {
digest = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("Every JDK ships SHA-1", e);
}
try (InputStream in = Files.newInputStream(file)) {
byte[] buffer = new byte[1 << 16];
for (int n; (n = in.read(buffer)) > 0; ) {
digest.update(buffer, 0, n);
}
}
return HexFormat.of().formatHex(digest.digest());
}
}
@@ -0,0 +1,58 @@
package incari.tools.build;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;
/** Recursive copy and delete. */
public final class FileTrees {
private FileTrees() {}
public static void deleteRecursively(Path root) throws IOException {
if (!Files.exists(root, LinkOption.NOFOLLOW_LINKS)) {
return;
}
Files.walkFileTree(root, new SimpleFileVisitor<>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
// Git marks its object files read-only; Windows refuses to delete those.
file.toFile().setWritable(true);
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
if (exc != null) {
throw exc;
}
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
}
/** Copies every regular file under {@code from} whose name ends in {@code suffix} into {@code to}. */
public static int copyTree(Path from, Path to, String suffix) throws IOException {
int[] count = {0};
Files.walkFileTree(from, new SimpleFileVisitor<>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (file.getFileName().toString().endsWith(suffix)) {
Path target = to.resolve(from.relativize(file).toString());
Files.createDirectories(target.getParent());
Files.copy(file, target, StandardCopyOption.REPLACE_EXISTING);
count[0]++;
}
return FileVisitResult.CONTINUE;
}
});
return count[0];
}
}
@@ -0,0 +1,126 @@
package incari.tools.build;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* The pinned client jar and its platform-neutral libraries, cached under {@code work/cache}.
*
* <p>{@link #fetch} downloads what's missing, plus this machine's native libraries for the
* desktop runtime. {@link #load} only reads the cache, for steps (decompile, survey) that must
* not touch the network.
*/
public record GameFiles(MojangMetadata.Version version, Path clientJar, List<LibraryJar> libraries) {
/** A platform-neutral library and where its jar is cached. */
public record LibraryJar(MojangMetadata.Library library, Path jar) {}
public static GameFiles fetch(Workspace ws, BuildConfig config, Downloader downloader)
throws IOException, InterruptedException {
String id = config.minecraftVersion();
Path versionJson = ws.versionJson(id);
if (!Files.isRegularFile(versionJson) || !Downloader.sha1(versionJson).equals(config.versionJsonSha1())) {
Log.step("Reading Mojang's version manifest");
String manifest = downloader.fetchString(MojangMetadata.VERSION_MANIFEST);
Files.createDirectories(ws.cacheDir());
Files.writeString(ws.versionManifestFile(), manifest);
MojangMetadata.Download listed = MojangMetadata.findVersion(manifest, id);
if (!listed.sha1().equals(config.versionJsonSha1())) {
throw new CliException("Mojang's metadata for " + id + " has SHA-1 " + listed.sha1()
+ " but " + BuildConfig.FILE_NAME + " pins " + config.versionJsonSha1()
+ ". Mojang changed a published version; review before re-pinning.");
}
downloader.fetch(listed.url(), listed.sha1(), versionJson);
}
MojangMetadata.Version version = MojangMetadata.parseVersion(Files.readString(versionJson));
checkClientPin(version, config);
Log.step("Downloading client " + id);
downloader.fetch(version.client().url(), version.client().sha1(), ws.clientJar(id));
List<MojangMetadata.Library> natives = hostNatives(version, NativePlatform.current());
List<MojangMetadata.Library> libraries = new ArrayList<>(neutralLibraries(version));
libraries.addAll(natives);
Log.step("Downloading " + libraries.size() + " libraries (" + natives.size() + " native, for "
+ NativePlatform.current().classifier() + ")");
try (ExecutorService pool = Executors.newFixedThreadPool(8)) {
List<Future<?>> pending = new ArrayList<>();
for (MojangMetadata.Library lib : libraries) {
pending.add(pool.submit(() -> {
downloader.fetch(
lib.download().url(),
lib.download().sha1(),
ws.librariesDir().resolve(lib.path()));
return null;
}));
}
for (Future<?> future : pending) {
Concurrency.join(future);
}
}
writeList(ws, ws.classpathList(id), neutralLibraries(version));
writeList(ws, ws.nativesList(id), natives);
return load(ws, config);
}
/** Reads the cache written by {@link #fetch}. Fails with a hint if it's missing. */
public static GameFiles load(Workspace ws, BuildConfig config) throws IOException {
String id = config.minecraftVersion();
Path versionJson = ws.versionJson(id);
Path clientJar = ws.clientJar(id);
if (!Files.isRegularFile(versionJson) || !Files.isRegularFile(clientJar)) {
throw new CliException("Minecraft " + id + " isn't downloaded yet. Run: ./incari fetch");
}
MojangMetadata.Version version = MojangMetadata.parseVersion(Files.readString(versionJson));
checkClientPin(version, config);
List<LibraryJar> libraries = new ArrayList<>();
for (MojangMetadata.Library lib : neutralLibraries(version)) {
Path jar = ws.librariesDir().resolve(lib.path());
if (!Files.isRegularFile(jar)) {
throw new CliException("Library " + lib.name() + " is missing. Run: ./incari fetch");
}
libraries.add(new LibraryJar(lib, jar));
}
return new GameFiles(version, clientJar, List.copyOf(libraries));
}
private static List<MojangMetadata.Library> neutralLibraries(MojangMetadata.Version version) {
return version.libraries().stream()
.filter(lib -> !lib.platformSpecific())
.toList();
}
/** The native jars for {@code platform}, one per library that has them. */
static List<MojangMetadata.Library> hostNatives(MojangMetadata.Version version, NativePlatform platform) {
return version.libraries().stream()
.filter(lib -> lib.classifier().equals(platform.classifier()))
.toList();
}
/** Repo-relative jar paths, one per line: the format Gradle reads (see {@link Workspace#classpathList}). */
private static void writeList(Workspace ws, Path file, List<MojangMetadata.Library> libraries) throws IOException {
StringBuilder out = new StringBuilder();
for (MojangMetadata.Library lib : libraries) {
Path jar = ws.librariesDir().resolve(lib.path());
out.append(ws.repoRoot().relativize(jar).toString().replace('\\', '/'))
.append('\n');
}
Files.writeString(file, out.toString());
}
private static void checkClientPin(MojangMetadata.Version version, BuildConfig config) {
if (!version.client().sha1().equals(config.clientSha1())) {
throw new CliException("Client jar for " + version.id() + " has SHA-1 "
+ version.client().sha1() + " but " + BuildConfig.FILE_NAME + " pins " + config.clientSha1());
}
}
}
@@ -0,0 +1,93 @@
package incari.tools.build;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Runs git in one repository, isolated from the user's and the system's git config.
*
* <p>Isolation is what makes patch files byte-identical across machines: settings like
* {@code diff.noprefix}, {@code diff.algorithm} or {@code format.signature} in someone's
* {@code ~/.gitconfig} would otherwise change every regenerated patch.
*/
public final class Git {
/** Identity for commits the tool makes itself (vendor and manifest commits, applied patches). */
static final String TOOL_NAME = "Incari Build";
static final String TOOL_EMAIL = "build@incari.invalid";
/** Fixed so the tool's own commits get the same hash on every machine. */
static final String TOOL_DATE = "2000-01-01T00:00:00Z";
private final Path dir;
public Git(Path dir) {
this.dir = dir;
}
public Path dir() {
return dir;
}
/** Runs a git command, returning stdout. Throws with git's stderr on failure. */
public String run(String... args) throws IOException, InterruptedException {
ProcessRunner.Result result = tryRun(args);
if (result.exitCode() != 0) {
throw new CliException("git " + String.join(" ", args) + " failed in " + dir
+ (result.stderr().isBlank() ? "" : ":\n" + result.stderr().strip()));
}
return result.stdout();
}
public ProcessRunner.Result tryRun(String... args) throws IOException, InterruptedException {
return ProcessRunner.start(command(args), dir, environment(), false, null);
}
private static List<String> command(String... args) {
List<String> command = new ArrayList<>(List.of(
"git",
"-c",
"core.autocrlf=false",
"-c",
"core.safecrlf=false",
"-c",
"core.quotePath=false",
"-c",
"commit.gpgSign=false",
"-c",
"tag.gpgSign=false",
// No hooks: a user's global pre-commit hook has no business running on vendor code.
"-c",
"core.hooksPath=.git/incari-no-hooks",
"-c",
"gc.auto=0",
"-c",
"init.defaultBranch=main",
"-c",
"advice.detachedHead=false",
// Paired with the "* diff=incari" attribute ClientTree writes: a function-name
// regex that never matches, so hunk headers don't quote a vendor line as context.
"-c",
"diff.incari.xfuncname=x^"));
command.addAll(List.of(args));
return command;
}
private static Map<String, String> environment() {
Map<String, String> env = new HashMap<>();
env.put("GIT_CONFIG_NOSYSTEM", "1");
env.put("GIT_CONFIG_GLOBAL", System.getProperty("os.name").startsWith("Windows") ? "NUL" : "/dev/null");
env.put("GIT_TERMINAL_PROMPT", "0");
env.put("GIT_COMMITTER_NAME", TOOL_NAME);
env.put("GIT_COMMITTER_EMAIL", TOOL_EMAIL);
env.put("GIT_COMMITTER_DATE", TOOL_DATE);
env.put("GIT_AUTHOR_NAME", TOOL_NAME);
env.put("GIT_AUTHOR_EMAIL", TOOL_EMAIL);
env.put("GIT_AUTHOR_DATE", TOOL_DATE);
return env;
}
}
@@ -0,0 +1,30 @@
package incari.tools.build;
import java.io.IOException;
/** Points the checkout's git hooks at {@code tools/git-hooks}, so the pre-commit checks run. */
final class GitHooks {
static final String HOOKS_DIR = "tools/git-hooks";
private GitHooks() {}
/** Installs the hooks unless this clone already chose its own hooks directory. */
static void install(Workspace ws) throws IOException, InterruptedException {
Git repo = new Git(ws.repoRoot());
if (repo.tryRun("rev-parse", "--git-dir").exitCode() != 0) {
return; // A source archive, not a clone: nothing to install into.
}
// --local reads only this clone's config, not the overrides the Git class passes with -c.
ProcessRunner.Result current = repo.tryRun("config", "--local", "--get", "core.hooksPath");
String configured = current.stdout().strip();
if (current.exitCode() == 0 && !configured.equals(HOOKS_DIR)) {
Log.info("Keeping this clone's own core.hooksPath (" + configured + "); Incari's are in " + HOOKS_DIR);
return;
}
if (!configured.equals(HOOKS_DIR)) {
repo.run("config", "--local", "core.hooksPath", HOOKS_DIR);
Log.info("Installed the pre-commit checks (" + HOOKS_DIR + ")");
}
}
}
@@ -0,0 +1,448 @@
package incari.tools.build;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.IOException;
import java.io.Reader;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import org.jspecify.annotations.Nullable;
/**
* The experimental Rust build (ADR 0068): Horizon's browser port with Incari's native mods.
*
* <p>Horizon is pinned in {@code incari.properties} and cloned into {@code work/horizon}, never
* committed, as the game is (ADR 0001). {@code INCARI_HORIZON_DIR} names a checkout to build
* instead, for work on Horizon itself. {@link #build} prepares Horizon's resources from the game
* files {@code ./incari fetch} and {@code ./incari assets} downloaded, applies {@code rust/mods}
* with horizon-mixins into {@code work/horizon-stage}, and runs Horizon's {@code web/package.py} there.
* The folder it writes, {@code app-web/build/rust/}, is what the page offers as Rust.
*/
final class Horizon {
/** A checkout to build instead of the pinned one. */
static final String DIR_VARIABLE = "INCARI_HORIZON_DIR";
/** What {@code incari.properties} pins. */
record Pin(String repository, String revision, String mixinsRepository, String mixinsRevision) {
static Pin load(Path repoRoot) throws IOException {
Path file = repoRoot.resolve(BuildConfig.FILE_NAME);
Properties props = new Properties();
try (Reader reader = Files.newBufferedReader(file)) {
props.load(reader);
}
return new Pin(
require(props, file, "horizon.repository"),
require(props, file, "horizon.revision"),
require(props, file, "horizon.mixins.repository"),
require(props, file, "horizon.mixins.revision"));
}
private static String require(Properties props, Path file, String key) {
String value = props.getProperty(key);
if (value == null || value.isBlank()) {
throw new CliException("Missing '" + key + "' in " + file);
}
return value.trim();
}
}
private Horizon() {}
static Path pinnedSource(Workspace ws) {
return ws.workDir().resolve("horizon");
}
static Path stage(Workspace ws) {
return ws.workDir().resolve("horizon-stage");
}
/** Where the browser build lands, for {@code :app-web:serve} and {@code :app-web:webFolder}. */
static Path output(Workspace ws) {
return ws.repoRoot().resolve("app-web/build/rust");
}
static Path mods(Workspace ws) {
return ws.repoRoot().resolve("rust/mods");
}
/** The checkout {@code INCARI_HORIZON_DIR} names, or null to use the pinned one. */
static @Nullable Path override() {
String dir = System.getenv(DIR_VARIABLE);
if (dir == null || dir.isBlank()) {
return null;
}
Path path = Path.of(System.getProperty("incari.cwd", "."))
.resolve(dir)
.toAbsolutePath()
.normalize();
if (!Files.isRegularFile(path.resolve("web/package.py"))) {
throw new CliException(
DIR_VARIABLE + "=" + dir + " isn't a checkout of Horizon's browser port" + " (no web/package.py)");
}
return path;
}
/**
* Clones the pinned commit into {@code work/horizon}, or moves the clone to it. Refuses to move
* a clone with changes in it: unsaved work is never dropped.
*/
static Path fetch(Workspace ws, Pin pin) throws IOException, InterruptedException {
Path dir = pinnedSource(ws);
if (!Files.isDirectory(dir.resolve(".git"))) {
Log.step("Cloning Horizon " + pin.revision().substring(0, 12) + " into work/horizon");
Files.createDirectories(dir);
git(dir, "init", "--quiet");
git(dir, "remote", "add", "origin", pin.repository());
} else if (head(dir).equals(pin.revision())) {
return dir;
} else if (!git(dir, "status", "--porcelain").stdout().isBlank()) {
throw new CliException("work/horizon has changes and isn't at the pinned commit. Commit them in your"
+ " Horizon fork, or set " + DIR_VARIABLE + " to build a checkout of your own");
} else {
Log.step("Moving work/horizon to " + pin.revision().substring(0, 12));
git(dir, "remote", "set-url", "origin", pin.repository());
}
git(dir, "fetch", "--quiet", "--depth", "1", "origin", pin.revision());
git(dir, "checkout", "--quiet", "--detach", "FETCH_HEAD");
if (!head(dir).equals(pin.revision())) {
throw new CliException(
"Fetched " + head(dir) + " but " + BuildConfig.FILE_NAME + " pins " + pin.revision());
}
return dir;
}
/**
* What the Rust build needs that this machine lacks, each with how to get it; empty when it can
* build. Reads the versions from the source: the nightly {@code web/build.sh} names, and the
* wasm-bindgen of its {@code Cargo.lock}.
*/
static List<String> missingTools(Path source) throws IOException, InterruptedException {
List<String> missing = new ArrayList<>();
if (!runs("python3", "--version")) {
missing.add("python3");
}
if (!runs("rustup", "--version") || !runs("cargo", "--version")) {
missing.add("Rust (https://rustup.rs)");
return missing;
}
String nightly = match(Files.readString(source.resolve("web/build.sh")), "(?m)^nightly=(\\S+)");
String components = ProcessRunner.start(
List.of("rustup", "component", "list", "--installed", "--toolchain", nightly),
source,
Map.of(),
false,
null)
.stdout();
if (!components.contains("rust-src") || !components.contains("rust-std-wasm32-unknown-unknown")) {
missing.add("Rust " + nightly + ": rustup toolchain install " + nightly
+ " --component rust-src --target wasm32-unknown-unknown");
}
String bindgen = match(
Files.readString(source.resolve("Cargo.lock")), "name = \"wasm-bindgen\"\\nversion = \"([^\"]+)\"");
ProcessRunner.Result installed =
ProcessRunner.start(List.of("wasm-bindgen", "--version"), source, Map.of(), false, null);
if (installed.exitCode() != 0 || !installed.stdout().strip().equals("wasm-bindgen " + bindgen)) {
missing.add("wasm-bindgen " + bindgen + ": cargo install wasm-bindgen-cli --version " + bindgen);
}
if (!runs("wasm-opt", "--version")) {
missing.add("binaryen's wasm-opt (your package manager's binaryen)");
}
return missing;
}
/**
* Builds the Rust build into {@link #output}: Horizon's resources, the mods, and its
* threaded WebAssembly build (the page's service worker makes it cross-origin isolated).
*/
static void build(Workspace ws, BuildConfig config, Path checkout, Pin pin)
throws IOException, InterruptedException {
Path source = checkout.equals(pinnedSource(ws)) ? checkout : snapshot(ws, checkout);
Path resources = prepare(ws, config, source);
incariPack(ws, resources);
Path tool = mixins(ws, pin);
Path stage = stage(ws);
// web/package.py writes its builds inside the source it runs in, and horizon-mixins refuses
// to restage over them (a symlink among them). They were copied out after the last build.
for (String built : List.of("web/dist", "web/out")) {
FileTrees.deleteRecursively(stage.resolve(built));
}
Log.step("Applying rust/mods to Horizon (horizon-mixins)");
// horizon-mixins rewrites the stage in place, keeping unchanged files' times, so Cargo
// recompiles only what the mods touch.
ProcessRunner.run(
List.of(
tool.toString(),
"apply",
"--workspace",
source.toString(),
"--mods",
mods(ws).toString(),
"--out",
stage.toString()),
ws.repoRoot(),
false);
Log.step("Compiling Horizon for the browser (long the first time)");
Path packaged = ws.workDir().resolve("horizon-out");
ProcessRunner.Result result = ProcessRunner.start(
List.of("python3", "web/package.py", "--out", packaged.toString()),
stage,
Map.of(
"HORIZON_RESOURCES", resources.toString(),
// Outside the stage, which horizon-mixins owns.
"CARGO_TARGET_DIR",
ws.workDir().resolve("horizon-target/web").toString()),
true,
null);
if (result.exitCode() != 0) {
throw new CliException("Horizon's web build failed (exit " + result.exitCode() + "); its output is above");
}
Path out = output(ws);
FileTrees.deleteRecursively(out);
FileTrees.copyTree(packaged.resolve("horizon-web"), out, "");
brandPage(ws, out);
Log.step("Rust build in " + ws.repoRoot().relativize(out));
}
/** The tab's icon, served beside the page. */
private static final String TAB_ICON = "icon.png";
/** Horizon's page is titled "Horizon" with no icon; the tab says "Incari Client" with Incari's icon, as the main page does. */
static void brandPage(Workspace ws, Path out) throws IOException {
Files.copy(
ws.repoRoot().resolve(PACK).resolve("assets/incari/textures/gui/icon_256.png"),
out.resolve(TAB_ICON),
StandardCopyOption.REPLACE_EXISTING);
Path page = out.resolve("index.html");
String html = Files.readString(page);
String branded = html.replace(
"<title>Horizon</title>",
"<title>Incari Client</title>\n<link rel=\"icon\" type=\"image/png\" href=\"" + TAB_ICON + "\">");
if (branded.equals(html)) {
throw new CliException(page + " has no <title>Horizon</title> to rename; Horizon's page changed");
}
Files.writeString(page, branded);
}
/**
* Horizon's resources, from the jars and assets {@code ./incari setup} and {@code assets} fetched:
* {@code work/horizon-resources/<version>}. Skipped when {@code horizon-prepare --check} says
* they're complete for this preparer.
*/
static Path prepare(Workspace ws, BuildConfig config, Path source) throws IOException, InterruptedException {
String version = config.minecraftVersion();
Path out = ws.workDir().resolve("horizon-resources").resolve(version);
Map<String, String> env = Map.of(
"CARGO_TARGET_DIR", ws.workDir().resolve("horizon-target/tools").toString());
List<String> prepare = List.of("cargo", "run", "--quiet", "--release", "-p", "horizon-prepare", "--");
List<String> check = new ArrayList<>(prepare);
check.addAll(List.of("--check", "--root", source.toString(), "--output", out.toString()));
if (ProcessRunner.start(check, source, env, false, null).exitCode() == 0) {
return out;
}
GameFiles game = GameFiles.load(ws, config);
Log.step("Checking the game's sounds (./incari assets)");
Assets.fetch(ws, config, new Downloader());
Path serverJar = serverJar(ws, config);
Log.step("Preparing Horizon's resources from Minecraft " + version + " (several minutes, once)");
List<String> run = new ArrayList<>(prepare);
run.addAll(List.of(
"--prepare",
"--complete",
"--root",
source.toString(),
"--output",
out.toString(),
"--version-json",
ws.versionJson(version).toString(),
"--client-jar",
game.clientJar().toString(),
"--libraries-dir",
ws.librariesDir().toString(),
"--assets-dir",
ws.assetsDir().toString(),
"--server-jar",
serverJar.toString(),
"--java-home",
System.getProperty("java.home")));
ProcessRunner.Result result = ProcessRunner.start(run, source, env, true, null);
if (result.exitCode() != 0) {
throw new CliException("horizon-prepare failed (exit " + result.exitCode() + "); its output is above");
}
return out;
}
/** Incari's pack, as the Java client serves it: listed in {@code files.txt}, by path in the pack. */
private static final String PACK = "client/src/main/resources/incari-pack";
/** The pack's files {@code rust/mods/incari} compiles in (ADR 0069), into its git-ignored {@code data/}. */
private static final List<String> BUNDLE_DATA = List.of(
"assets/incari/textures/gui/icon_256.png",
"assets/incari/textures/gui/title_backdrop.png",
"assets/incari/font/michroma.ttf");
/**
* Incari's pack over Horizon's prepared resources, as the Java client always has it on: its
* fonts, the game's default font made Incari's (ADR 0069). Also the files the client's bundle
* compiles in. One copy of each in the repo: copied at each build.
*/
static void incariPack(Workspace ws, Path resources) throws IOException {
Path pack = ws.repoRoot().resolve(PACK);
for (String line : Files.readAllLines(pack.resolve("files.txt"))) {
String entry = line.strip();
if (entry.isEmpty() || entry.startsWith("#")) {
continue;
}
int eq = entry.indexOf('=');
String served = (eq < 0 ? entry : entry.substring(0, eq)).strip();
String file = (eq < 0 ? entry : entry.substring(eq + 1)).strip();
Path to = resources.resolve(served);
Files.createDirectories(to.getParent());
Files.copy(pack.resolve(file), to, StandardCopyOption.REPLACE_EXISTING);
}
Path data = mods(ws).resolve("incari").resolve("data");
Files.createDirectories(data);
for (String file : BUNDLE_DATA) {
Path from = pack.resolve(file);
Files.copy(from, data.resolve(from.getFileName()), StandardCopyOption.REPLACE_EXISTING);
}
// The version, repository and featured servers the client shows.
Files.copy(
ws.repoRoot().resolve(BuildConfig.FILE_NAME),
data.resolve(BuildConfig.FILE_NAME),
StandardCopyOption.REPLACE_EXISTING);
}
/** The server jar, which Horizon's resources are exported from too, checked against its SHA-1. */
private static Path serverJar(Workspace ws, BuildConfig config) throws IOException, InterruptedException {
Path versionJson = ws.versionJson(config.minecraftVersion());
JsonObject server = JsonParser.parseString(Files.readString(versionJson))
.getAsJsonObject()
.getAsJsonObject("downloads")
.getAsJsonObject("server");
if (server == null) {
throw new CliException(versionJson + " names no server jar");
}
Path jar = ws.versionDir(config.minecraftVersion()).resolve("server.jar");
new Downloader()
.fetch(
URI.create(server.get("url").getAsString()),
server.get("sha1").getAsString(),
jar);
return jar;
}
/** horizon-mixins at the pinned commit, built once into {@code work/cache/horizon-mixins/<commit>}. */
private static Path mixins(Workspace ws, Pin pin) throws IOException, InterruptedException {
Path root = ws.cacheDir().resolve("horizon-mixins").resolve(pin.mixinsRevision());
boolean windows = System.getProperty("os.name").startsWith("Windows");
Path tool = root.resolve("bin").resolve(windows ? "horizon-mixins.exe" : "horizon-mixins");
if (Files.isRegularFile(tool)) {
return tool;
}
Log.step("Building horizon-mixins " + pin.mixinsRevision().substring(0, 12) + " (once)");
ProcessRunner.run(
List.of(
"cargo",
"install",
"--quiet",
"--locked",
"--git",
pin.mixinsRepository(),
"--rev",
pin.mixinsRevision(),
"--root",
root.toString(),
"horizon-mixins-cli"),
ws.repoRoot(),
true);
return tool;
}
/**
* The files of a checkout {@code INCARI_HORIZON_DIR} names, as git sees them (tracked, and new
* ones it doesn't ignore), copied into {@code work/horizon-override}: horizon-mixins reads every
* file of its workspace, and a checkout's own web build leaves a symlink in its ignored
* {@code web/dist} that it refuses. Unchanged files keep their times, so the stage stays
* incremental.
*/
static Path snapshot(Workspace ws, Path checkout) throws IOException, InterruptedException {
Path copy = ws.workDir().resolve("horizon-override");
Log.step("Copying " + checkout + " into work/horizon-override");
Set<Path> kept = new HashSet<>();
String names = git(checkout, "ls-files", "-z", "--cached", "--others", "--exclude-standard")
.stdout();
for (String name : names.split("\0", -1)) {
Path from = checkout.resolve(name);
// A tracked file deleted in the checkout, or a link: neither is staged.
if (name.isEmpty() || !Files.isRegularFile(from, LinkOption.NOFOLLOW_LINKS)) {
continue;
}
Path to = copy.resolve(name);
kept.add(to);
if (Files.isRegularFile(to, LinkOption.NOFOLLOW_LINKS)
&& Files.size(to) == Files.size(from)
&& Files.getLastModifiedTime(to).equals(Files.getLastModifiedTime(from))) {
continue;
}
Files.createDirectories(to.getParent());
Files.copy(from, to, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);
}
List<Path> stale;
try (Stream<Path> files = Files.walk(copy)) {
stale = files.filter(f -> !Files.isDirectory(f, LinkOption.NOFOLLOW_LINKS) && !kept.contains(f))
.toList();
}
for (Path file : stale) {
Files.delete(file);
}
return copy;
}
private static String head(Path dir) throws IOException, InterruptedException {
ProcessRunner.Result result = ProcessRunner.start(
List.of("git", "rev-parse", "--verify", "--quiet", "HEAD"), dir, Map.of(), false, null);
return result.exitCode() == 0 ? result.stdout().strip() : "";
}
private static ProcessRunner.Result git(Path dir, String... args) throws IOException, InterruptedException {
List<String> command = new ArrayList<>(List.of("git"));
command.addAll(Arrays.asList(args));
return ProcessRunner.run(command, dir, false);
}
private static boolean runs(String... command) {
try {
return ProcessRunner.start(List.of(command), Path.of("."), Map.of(), false, null)
.exitCode()
== 0;
} catch (IOException e) {
return false;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
}
}
static String match(String text, String regex) {
Matcher m = Pattern.compile(regex).matcher(text);
if (!m.find()) {
throw new CliException("Horizon's source changed: no match for " + regex);
}
return m.group(1);
}
}
@@ -0,0 +1,20 @@
package incari.tools.build;
/** Console output for the CLI. Kept deliberately plain so CI logs stay readable. */
public final class Log {
private Log() {}
/** A top-level step the user is waiting on. */
public static void step(String message) {
System.out.println("==> " + message);
}
public static void info(String message) {
System.out.println(" " + message);
}
public static void warn(String message) {
System.err.println("warning: " + message);
}
}
@@ -0,0 +1,197 @@
package incari.tools.build;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
/**
* The {@code incari} build CLI. Run it through {@code ./incari} at the repo root.
*
* <p>Pipeline: {@code fetch} (Mojang jar + libraries) → {@code decompile} (Vineflower) →
* {@code apply} (vendor commit, class manifest, patches into {@code work/client}).
* {@code setup} runs all three. {@code rebuild} goes the other way, from commits in
* {@code work/client} back to {@code patches/}. {@code build} compiles the browser build into a
* folder for a web server ({@link WebBuild}).
*/
public final class Main {
private static final String USAGE = """
Usage: ./incari <command> [options]
Commands:
setup fetch + decompile + apply: a fresh clone to a patched tree
fetch download the pinned Minecraft client jar and its libraries
assets download the game's assets (sounds, languages; ~480 MB), for the
desktop runtime only
decompile decompile the client jar with Vineflower into work/decompiled
apply [--force] rebuild work/client from the decompiled sources and patches/
(--force discards unsaved commits and edits in work/client)
rebuild [--check] regenerate patches/ from the commits in work/client
(--check writes nothing, fails if patches/ is out of date
or a replaced class's original changed, see classes)
classes [--stamp] list the classes patches/classes.txt replaces whose Mojang
original changed since the replacement was checked against it
(--stamp records the current originals once they're reviewed)
build [--out <dir>] [--only fast|compatible|rust] [--no-sounds] [--html]
compile the release browser builds, Fast, Compatible and the
experimental Rust (or just one with --only), into one folder for
a static web server (default dist/web), or with --html into one
HTML file that plays from the disk, without music or Rust
(smaller sounds need ffmpeg) (default dist/incari.html).
Rust is skipped, saying why, without its tools or work/horizon;
INCARI_HORIZON_DIR builds another Horizon checkout.
It holds Minecraft's code and files: for your own use, never
shared or published
survey TeaVM compile survey, see tools/survey/README.md
copycheck fail if Incari code repeats decompiled game code, see tools/copycheck
help show this message
""";
private Main() {}
public static void main(String[] args) {
try {
System.exit(run(List.of(args)));
} catch (CliException e) {
System.err.println("error: " + e.getMessage());
System.exit(1);
} catch (Exception e) {
e.printStackTrace();
System.exit(2);
}
}
static int run(List<String> args) throws Exception {
if (args.isEmpty() || args.getFirst().equals("help") || args.contains("--help") || args.contains("-h")) {
System.out.print(USAGE);
return args.isEmpty() ? 1 : 0;
}
String command = args.getFirst();
List<String> flags = new ArrayList<>(args.subList(1, args.size()));
Workspace ws = Workspace.discover(Path.of(System.getProperty("incari.cwd", ".")));
BuildConfig config = BuildConfig.load(ws.repoRoot());
switch (command) {
case "setup" -> {
noFlags(command, flags);
GameFiles game = GameFiles.fetch(ws, config, new Downloader());
Decompiler.decompile(ws, game);
new ClientTree(ws).apply(ws.decompiledDir(config.minecraftVersion()), config.minecraftVersion(), false);
GitHooks.install(ws);
// The Rust build's source (ADR 0068). Optional: Fast and Compatible build without it.
try {
Horizon.fetch(ws, Horizon.Pin.load(ws.repoRoot()));
} catch (CliException e) {
Log.warn("Horizon not fetched, so ./incari build will skip the Rust build: " + e.getMessage());
}
Log.step("Done. The patched tree is in work/client");
}
case "fetch" -> {
noFlags(command, flags);
GameFiles.fetch(ws, config, new Downloader());
}
case "assets" -> {
noFlags(command, flags);
String index = Assets.fetch(ws, config, new Downloader());
Log.step("Done. Asset index " + index + " is in work/cache/assets");
}
case "decompile" -> {
noFlags(command, flags);
Decompiler.decompile(ws, GameFiles.load(ws, config));
}
case "apply" -> {
boolean force = flags.remove("--force");
noFlags(command, flags);
Path decompiled = ws.decompiledDir(config.minecraftVersion());
if (!decompiled.resolve(".incari-decompile-stamp").toFile().isFile()) {
throw new CliException("No decompiled sources yet. Run: ./incari setup");
}
new ClientTree(ws).apply(decompiled, config.minecraftVersion(), force);
Log.step("Done. The patched tree is in work/client");
}
case "rebuild" -> {
boolean check = flags.remove("--check");
noFlags(command, flags);
ClientTree.RebuildResult result = new ClientTree(ws).rebuildPatches(check);
Log.step((check ? "Checked" : "Rebuilt") + " patches: " + result.written() + " changed, "
+ result.unchanged() + " unchanged, " + result.removed() + " removed");
if (check && result.changed()) {
throw new CliException(
"patches/ doesn't match work/client. Run ./incari rebuild and commit the result.");
}
if (check) {
ClientTree tree = new ClientTree(ws);
List<ClientTree.Drift> drift = tree.replacementDrift(config.minecraftVersion());
if (!drift.isEmpty()) {
tree.reportDrift(drift, config.minecraftVersion());
throw new CliException(drift.size() + " replaced class(es) in patches/classes.txt"
+ " aren't stamped against this vendor tree. Review them, then run"
+ " ./incari classes --stamp and commit classes.txt.");
}
}
}
case "classes" -> {
boolean stamp = flags.remove("--stamp");
noFlags(command, flags);
ClientTree tree = new ClientTree(ws);
if (stamp) {
int count = tree.stampReplacements(config.minecraftVersion());
Log.step("Stamped " + count + " replaced classes against Minecraft " + config.minecraftVersion());
} else {
List<ClientTree.Drift> drift = tree.replacementDrift(config.minecraftVersion());
tree.reportDrift(drift, config.minecraftVersion());
Log.step(
drift.isEmpty()
? "Every replaced class matches its stamp"
: drift.size() + " replaced class(es) to review");
return drift.isEmpty() ? 0 : 1;
}
}
case "build" -> {
boolean sounds = !flags.remove("--no-sounds");
boolean html = flags.remove("--html");
// The single file holds TeaVM's builds only; Rust is its own page (ADR 0068).
List<String> builds = html ? List.of("fast", "compatible") : List.of("fast", "compatible", "rust");
boolean only = false;
int onlyFlag = flags.indexOf("--only");
if (onlyFlag >= 0) {
if (onlyFlag + 1 >= flags.size() || !builds.contains(flags.get(onlyFlag + 1))) {
throw new CliException(
html
? "--only takes fast or compatible with --html"
: "--only takes fast, compatible or rust");
}
builds = List.of(flags.get(onlyFlag + 1));
only = true;
flags.subList(onlyFlag, onlyFlag + 2).clear();
}
Path out = ws.repoRoot().resolve("dist").resolve(html ? "incari.html" : "web");
int outFlag = flags.indexOf("--out");
if (outFlag >= 0) {
if (outFlag + 1 >= flags.size()) {
throw new CliException(html ? "--out needs a file name" : "--out needs a folder");
}
out = Path.of(System.getProperty("incari.cwd", ".")).resolve(flags.get(outFlag + 1));
flags.subList(outFlag, outFlag + 2).clear();
}
noFlags(command, flags);
WebBuild.build(ws, config, out, builds, only, sounds, html);
}
case "survey", "copycheck" ->
throw new CliException(
"'" + command + "' runs in its own JVM; use ./incari " + command + " (the launcher script)");
default -> {
System.err.print(USAGE);
throw new CliException("Unknown command '" + command + "'");
}
}
return 0;
}
private static void noFlags(String command, List<String> flags) {
if (!flags.isEmpty()) {
throw new CliException("Unknown option(s) for " + command + ": " + String.join(" ", flags));
}
}
}
@@ -0,0 +1,97 @@
package incari.tools.build;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.jspecify.annotations.Nullable;
/**
* The few fields Incari reads from Mojang's launcher metadata: the version manifest
* (every version and where its JSON lives) and a version JSON (client jar and libraries).
*
* <p>Parsed by hand from a JSON tree rather than bound to classes, because the launcher
* format has many fields we don't use and Mojang adds more over time.
*/
public final class MojangMetadata {
public static final URI VERSION_MANIFEST =
URI.create("https://piston-meta.mojang.com/mc/game/version_manifest_v2.json");
private MojangMetadata() {}
/** A download Mojang describes by URL and SHA-1. */
public record Download(URI url, String sha1, long size) {}
/** One library. {@code path} is the Maven-layout path, used as its cache location. */
public record Library(String name, String path, Download download, boolean platformSpecific) {
/** The Maven classifier ({@code natives-linux}), or empty for a platform-neutral jar. */
public String classifier() {
String[] parts = name.split(":", -1);
return parts.length > 3 ? parts[3] : "";
}
}
/** The game's asset index: which sounds, languages and other assets this version uses. */
public record AssetIndex(String id, Download download) {}
/** {@code assetIndex} is null only in test fixtures; every real version JSON has one. */
public record Version(
String id,
Download client,
int javaMajorVersion,
List<Library> libraries,
@Nullable AssetIndex assetIndex) {}
/** Finds a version's JSON download in the manifest. */
public static Download findVersion(String manifestJson, String versionId) {
JsonObject manifest = JsonParser.parseString(manifestJson).getAsJsonObject();
for (JsonElement element : manifest.getAsJsonArray("versions")) {
JsonObject version = element.getAsJsonObject();
if (version.get("id").getAsString().equals(versionId)) {
return new Download(
URI.create(version.get("url").getAsString()),
version.get("sha1").getAsString(),
-1);
}
}
throw new CliException("Version " + versionId + " is not in Mojang's version manifest");
}
public static Version parseVersion(String versionJson) {
JsonObject root = JsonParser.parseString(versionJson).getAsJsonObject();
Download client = download(root.getAsJsonObject("downloads").getAsJsonObject("client"));
int java = root.getAsJsonObject("javaVersion").get("majorVersion").getAsInt();
List<Library> libraries = new ArrayList<>();
JsonArray libs = root.getAsJsonArray("libraries");
for (JsonElement element : libs) {
JsonObject lib = element.getAsJsonObject();
JsonObject downloads = lib.getAsJsonObject("downloads");
if (downloads == null || !downloads.has("artifact")) {
continue;
}
JsonObject artifact = downloads.getAsJsonObject("artifact");
String name = lib.get("name").getAsString();
// Natives carry a classifier ("group:artifact:version:natives-linux") and are only
// useful to the desktop JVM, never to the browser build or the decompiler.
boolean platformSpecific = name.split(":").length > 3;
libraries.add(new Library(name, artifact.get("path").getAsString(), download(artifact), platformSpecific));
}
JsonObject assets = root.getAsJsonObject("assetIndex");
AssetIndex assetIndex =
assets == null ? null : new AssetIndex(assets.get("id").getAsString(), download(assets));
return new Version(root.get("id").getAsString(), client, java, List.copyOf(libraries), assetIndex);
}
private static Download download(JsonObject object) {
return new Download(
URI.create(object.get("url").getAsString()),
object.get("sha1").getAsString(),
object.get("size").getAsLong());
}
}
@@ -0,0 +1,34 @@
package incari.tools.build;
import java.util.Locale;
/**
* The operating system and CPU the desktop runtime runs on, named the way Mojang's version JSON
* classifies native jars ({@code natives-linux}, {@code natives-windows-arm64}, ...).
*/
public record NativePlatform(String os, boolean arm64) {
public static NativePlatform current() {
return of(System.getProperty("os.name", ""), System.getProperty("os.arch", ""));
}
static NativePlatform of(String osName, String osArch) {
String name = osName.toLowerCase(Locale.ROOT);
String os;
if (name.startsWith("windows")) {
os = "windows";
} else if (name.startsWith("mac") || name.startsWith("darwin")) {
os = "macos";
} else if (name.startsWith("linux")) {
os = "linux";
} else {
throw new CliException("Minecraft ships no native libraries for " + osName);
}
String arch = osArch.toLowerCase(Locale.ROOT);
return new NativePlatform(os, arch.equals("aarch64") || arch.equals("arm64"));
}
public String classifier() {
return "natives-" + os + (arm64 ? "-arm64" : "");
}
}
@@ -0,0 +1,85 @@
package incari.tools.build;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
/**
* The patch files under {@code patches/}, laid out as {@code <subsystem>/<NNNN>-<slug>.patch}.
*
* <p>The number is the patch's position in one global order (patches build on each other
* across subsystems); the directory groups them for reading and review. A patch's commit
* subject is {@code "<subsystem>: <summary>"}, which is how {@code rebuild} knows where
* each regenerated file belongs.
*/
public final class PatchSet {
/** {@code "render: Route section compile to the mesher"} */
static final Pattern SUBJECT = Pattern.compile("([a-z0-9][a-z0-9-]*): (\\S.*)");
private static final Pattern FILE_NAME = Pattern.compile("(\\d{4})-[a-z0-9-]+\\.patch");
private static final int MAX_SLUG = 60;
private PatchSet() {}
public record PatchFile(int number, String subsystem, Path path) {}
/** Every patch file in application order. Rejects stray names and duplicate numbers. */
public static List<PatchFile> list(Path patchesDir) throws IOException {
if (!Files.isDirectory(patchesDir)) {
return List.of();
}
List<PatchFile> patches = new ArrayList<>();
try (Stream<Path> files = Files.walk(patchesDir)) {
for (Path file : files.filter(p -> p.toString().endsWith(".patch")).toList()) {
Path relative = patchesDir.relativize(file);
Matcher name = FILE_NAME.matcher(file.getFileName().toString());
if (relative.getNameCount() != 2 || !name.matches()) {
throw new CliException("Unexpected patch file " + relative
+ " (expected <subsystem>/<NNNN>-<slug>.patch; run ./incari rebuild to regenerate names)");
}
patches.add(new PatchFile(
Integer.parseInt(name.group(1)), relative.getName(0).toString(), file));
}
}
patches.sort(Comparator.comparingInt(PatchFile::number));
Map<Integer, Path> byNumber = new HashMap<>();
for (PatchFile patch : patches) {
Path clash = byNumber.put(patch.number(), patch.path());
if (clash != null) {
throw new CliException(
"Two patches share number " + patch.number() + ": " + clash + " and " + patch.path());
}
}
return List.copyOf(patches);
}
/** The repo-relative file a commit with this subject is written to, at position {@code number}. */
static String fileFor(int number, String subject) {
Matcher matcher = SUBJECT.matcher(subject);
if (!matcher.matches()) {
throw new CliException("Commit subject \"" + subject + "\" must look like \"<subsystem>: <summary>\""
+ " (lowercase subsystem, e.g. \"render: Route section compile to the mesher\")");
}
return matcher.group(1) + "/" + String.format(Locale.ROOT, "%04d", number) + "-" + slug(matcher.group(2))
+ ".patch";
}
static String slug(String summary) {
String slug =
summary.toLowerCase(Locale.ROOT).replaceAll("[^a-z0-9]+", "-").replaceAll("^-|-$", "");
if (slug.length() > MAX_SLUG) {
slug = slug.substring(0, MAX_SLUG).replaceAll("-[^-]*$", "");
}
return slug.isEmpty() ? "patch" : slug;
}
}
@@ -0,0 +1,99 @@
package incari.tools.build;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import org.jspecify.annotations.Nullable;
/** Runs child processes (git, the decompiler JVM) and turns failures into {@link CliException}s. */
public final class ProcessRunner {
/** Variables with which git tells a hook which repository it runs in. */
private static final List<String> OUTER_GIT_ENVIRONMENT = List.of(
"GIT_DIR",
"GIT_WORK_TREE",
"GIT_INDEX_FILE",
"GIT_COMMON_DIR",
"GIT_OBJECT_DIRECTORY",
"GIT_ALTERNATE_OBJECT_DIRECTORIES",
"GIT_PREFIX");
private ProcessRunner() {}
public record Result(int exitCode, String stdout, String stderr) {}
/**
* Runs {@code command} in {@code dir}. With {@code inheritOutput}, the child writes straight
* to the console (long-running steps the user watches); otherwise output is captured.
* Throws on a non-zero exit.
*/
public static Result run(List<String> command, Path dir, boolean inheritOutput)
throws IOException, InterruptedException {
Result result = start(command, dir, Map.of(), inheritOutput, null);
if (result.exitCode() != 0) {
throw new CliException("Command failed (exit " + result.exitCode() + "): " + String.join(" ", command)
+ (result.stderr().isBlank() ? "" : "\n" + result.stderr().strip()));
}
return result;
}
/** Runs {@code command} and returns its result whatever the exit code. */
public static Result start(
List<String> command, Path dir, Map<String, String> env, boolean inheritOutput, @Nullable String stdin)
throws IOException, InterruptedException {
ProcessBuilder builder = new ProcessBuilder(command).directory(dir.toFile());
// Run from a git hook (the pre-commit hook's `rebuild --check`), the CLI inherits the outer
// repo's GIT_DIR and GIT_INDEX_FILE, which would point git in work/client at the wrong
// repository. Every command here names its own directory.
builder.environment().keySet().removeAll(OUTER_GIT_ENVIRONMENT);
builder.environment().putAll(env);
if (inheritOutput) {
builder.redirectOutput(ProcessBuilder.Redirect.INHERIT).redirectError(ProcessBuilder.Redirect.INHERIT);
}
if (stdin == null) {
builder.redirectInput(ProcessBuilder.Redirect.from(nullDevice()));
}
Process process = builder.start();
if (stdin != null) {
try (var in = process.getOutputStream()) {
in.write(stdin.getBytes(StandardCharsets.UTF_8));
}
}
if (inheritOutput) {
return new Result(process.waitFor(), "", "");
}
// Drain stderr on its own thread: a child that fills one pipe while we block reading
// the other would deadlock.
ByteArrayOutputStream err = new ByteArrayOutputStream();
Thread errReader = Thread.ofVirtual().start(() -> copy(process.getErrorStream(), err));
String out = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
int exit = process.waitFor();
errReader.join();
return new Result(exit, out, err.toString(StandardCharsets.UTF_8));
}
/** The {@code java} binary running this CLI, so child JVMs use the same JDK. */
public static String javaExecutable() {
return ProcessHandle.current()
.info()
.command()
.orElse(Path.of(System.getProperty("java.home"), "bin", "java").toString());
}
private static java.io.File nullDevice() {
return new java.io.File(System.getProperty("os.name").startsWith("Windows") ? "NUL" : "/dev/null");
}
private static void copy(InputStream in, ByteArrayOutputStream out) {
try (in) {
in.transferTo(out);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
@@ -0,0 +1,157 @@
package incari.tools.build;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* {@code ./incari build} (ADR 0028): from a set-up checkout to one folder a static web server
* can serve. Compiles the game's two release builds with Gradle (ADR 0036), Compatible
* ({@code :app-web:teavm -Pteavm.release}) and Fast (the same with {@code -Pteavm.fast}), or the one
* {@code --only} names, then {@code :app-web:webFolder} copies them, the page, the client jar and the
* sounds into the folder. With both, the page lets the player pick, Fast recommended. The
* experimental Rust build ({@link Horizon}, ADR 0068) goes in its {@code rust/} folder when this
* machine can build it; otherwise it's skipped, saying why.
*
* <p>With {@code --html} it packs that folder, with every sound but the music encoded smaller (about
* 38 MB of 377; ffmpeg, else only the common sounds), into one HTML file that plays from the disk ({@code :app-web:singleFile}, ADR 0057), writing the folder under
* {@code app-web/build/} on the way.
*
* <p>The folder holds Mojang's code and files. It is for the person who built it: never committed,
* never shared or published. Inside the checkout it must be git-ignored, so it can't be committed.
*/
final class WebBuild {
static final String NOTICE = """
------------------------------------------------------------------------------------
DO NOT SHARE, UPLOAD OR PUBLISH THIS BUILD.
It contains Minecraft's code and files, which Mojang doesn't allow redistributing.
The Incari project never publishes builds and gives nobody permission to. It's for
your own use; if you serve it, it's your server and your responsibility.
See docs/self-hosting.md (and README.txt in the folder).
------------------------------------------------------------------------------------
""";
private WebBuild() {}
/**
* @param only true when {@code --only} named the one build: a Rust build that can't be made
* fails instead of being skipped
* @param html true for one HTML file at {@code out} instead of a folder
*/
static void build(
Workspace ws, BuildConfig config, Path out, List<String> builds, boolean only, boolean sounds, boolean html)
throws IOException, InterruptedException {
if (!Files.isDirectory(ws.clientTree())) {
throw new CliException("No patched tree in work/client yet. Run: ./incari setup");
}
out = out.toAbsolutePath().normalize();
requireIgnored(ws, out, !html);
// The single file is packed from a folder of the build's own, with its sounds smaller.
Path folder = html ? ws.repoRoot().resolve("app-web/build/web-single") : out;
if (sounds) {
Log.step("Checking the game's sounds (./incari assets)");
Assets.fetch(ws, config, new Downloader());
}
builds = new ArrayList<>(builds);
if (builds.contains("rust") && !rust(ws, config, only)) {
builds.remove("rust");
}
if (builds.contains("compatible")) {
Log.step("Compiling the Compatible build (release; about ten minutes when the code changed)");
gradle(ws, List.of(":app-web:teavm", "-Pteavm.release"));
}
if (builds.contains("fast")) {
Log.step("Compiling the Fast build (release; about ten minutes when the code changed)");
gradle(ws, List.of(":app-web:teavm", "-Pteavm.release", "-Pteavm.fast"));
}
Log.step("Writing " + out);
List<String> task = new ArrayList<>(List.of(
":app-web:webFolder",
"-Pteavm.release",
"-Pweb.skipBuild",
"-Pweb.builds=" + String.join(",", builds),
"-Pweb.out=" + folder));
if (!sounds) {
task.add("-Pweb.noSounds");
}
if (html) {
task.addAll(List.of(":app-web:singleFile", "-Pweb.smallSounds", "-Pweb.html=" + out));
}
gradle(ws, task);
Log.step(
html
? "Done. Open " + out
+ " in Chrome, Edge or Firefox; it plays without a server"
+ (sounds ? " (no music)" : " (and without sounds)")
: "Done. Serve " + out + " with any static web server; its README.txt says how");
System.out.print(NOTICE);
}
/**
* Builds Rust (ADR 0068) into {@code app-web/build/rust/}, or says why it can't and returns false.
* With {@code only}, a reason is an error.
*/
private static boolean rust(Workspace ws, BuildConfig config, boolean only)
throws IOException, InterruptedException {
Horizon.Pin pin = Horizon.Pin.load(ws.repoRoot());
Path override = Horizon.override();
Path source = null;
List<String> missing;
try {
source = override != null ? override : Horizon.fetch(ws, pin);
missing = Horizon.missingTools(source);
} catch (CliException e) {
missing = List.of(e.getMessage());
}
if (!missing.isEmpty()) {
String why = "The Rust build needs: " + String.join("; ", missing);
if (only) {
throw new CliException(why);
}
Log.warn(why + ". Skipping it; Fast and Compatible still build");
return false;
}
if (source == null) {
throw new IllegalStateException("A source with nothing missing");
}
Horizon.build(ws, config, source, pin);
return true;
}
/**
* Refuses an output folder (or file) inside the checkout that git would track: the build must
* never be committed. The default, {@code dist/}, is ignored.
*/
static void requireIgnored(Workspace ws, Path out, boolean folder) throws IOException, InterruptedException {
if (!out.startsWith(ws.repoRoot())) {
return;
}
if (out.equals(ws.repoRoot())) {
throw new CliException(
"The build can't go in the checkout's root. Use the default under dist/, or somewhere outside it");
}
ProcessRunner.Result ignored = ProcessRunner.start(
List.of("git", "check-ignore", "-q", "--no-index", ws.repoRoot().relativize(out) + (folder ? "/" : "")),
ws.repoRoot(),
Map.of(),
false,
null);
if (ignored.exitCode() != 0) {
throw new CliException(out + " is inside the checkout and not git-ignored, so the build could be "
+ "committed. Use the default under dist/, or somewhere outside the checkout");
}
}
private static void gradle(Workspace ws, List<String> arguments) throws IOException, InterruptedException {
boolean windows = System.getProperty("os.name").startsWith("Windows");
Path wrapper = ws.repoRoot().resolve(windows ? "gradlew.bat" : "gradlew");
List<String> command = new ArrayList<>(List.of(wrapper.toString(), "--console=plain"));
command.addAll(arguments);
ProcessRunner.run(command, ws.repoRoot(), true);
}
}
@@ -0,0 +1,107 @@
package incari.tools.build;
import java.nio.file.Files;
import java.nio.file.Path;
/**
* Where everything lives. Two roots: the repo (tracked, Incari-owned files only) and
* {@code work/} inside it (git-ignored, everything derived from Mojang's jar).
*
* <p>Nothing outside {@code work/} may ever hold Mojang content. Every path that does is
* defined here, so that rule can be checked in one place.
*/
public record Workspace(Path repoRoot) {
/** The client tree's Java sources, relative to {@link #clientTree()}. */
public static final String CLIENT_SOURCE_DIR = "src/main/java";
public Workspace {
repoRoot = repoRoot.toAbsolutePath().normalize();
}
/**
* Finds the repo root by walking up from {@code start} to the directory holding
* {@code incari.properties}. Lets the CLI run from any subdirectory.
*/
public static Workspace discover(Path start) {
for (Path dir = start.toAbsolutePath().normalize(); dir != null; dir = dir.getParent()) {
if (Files.isRegularFile(dir.resolve(BuildConfig.FILE_NAME))) {
return new Workspace(dir);
}
}
throw new CliException("Not inside an Incari checkout (no " + BuildConfig.FILE_NAME + " found above "
+ start.toAbsolutePath() + ")");
}
// --- Tracked inputs ---
public Path patchesDir() {
return repoRoot.resolve("patches");
}
public Path classManifest() {
return patchesDir().resolve(ClassManifest.FILE_NAME);
}
// --- Generated, git-ignored ---
public Path workDir() {
return repoRoot.resolve("work");
}
public Path cacheDir() {
return workDir().resolve("cache");
}
public Path versionManifestFile() {
return cacheDir().resolve("version_manifest_v2.json");
}
public Path versionDir(String version) {
return cacheDir().resolve("versions").resolve(version);
}
public Path versionJson(String version) {
return versionDir(version).resolve(version + ".json");
}
public Path clientJar(String version) {
return versionDir(version).resolve("client.jar");
}
/**
* Repo-relative paths of the platform-neutral library jars, one per line. Written by
* {@code fetch} for Gradle, which compiles the client tree against them.
*/
public Path classpathList(String version) {
return versionDir(version).resolve("classpath.txt");
}
/** Like {@link #classpathList}, for this machine's native library jars (desktop runtime only). */
public Path nativesList(String version) {
return versionDir(version).resolve("natives.txt");
}
/** The launcher's asset layout: {@code indexes/<id>.json} and {@code objects/<ab>/<hash>}. */
public Path assetsDir() {
return cacheDir().resolve("assets");
}
public Path librariesDir() {
return cacheDir().resolve("libraries");
}
/** Pristine Vineflower output. Never edited; the client tree is copied from it. */
public Path decompiledDir(String version) {
return workDir().resolve("decompiled").resolve(version);
}
/** The git repo people edit: vendor commit, then the class manifest, then one commit per patch. */
public Path clientTree() {
return workDir().resolve("client");
}
public Path surveyDir(String version) {
return workDir().resolve("survey").resolve(version);
}
}
@@ -0,0 +1,285 @@
package incari.tools.build;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
/**
* The apply/rebuild cycle on a tiny synthetic "vendor" tree, so the tests need neither
* network nor Mojang's jar.
*/
class ClientTreeTest {
@TempDir
Path root;
private Workspace ws;
private Path decompiled;
private ClientTree tree;
@BeforeEach
void setUp() throws IOException {
Files.writeString(root.resolve(BuildConfig.FILE_NAME), "minecraft.version=test\n");
ws = new Workspace(root);
decompiled = ws.decompiledDir("test");
writeVendor("com/example/Greeter.java", """
package com.example;
public class Greeter {
public String greet() {
return "hello";
}
}
""");
writeVendor("com/example/Telemetry.java", "package com.example;\n\npublic class Telemetry {}\n");
writeVendor("com/example/Buffer.java", "package com.example;\n\npublic class Buffer { int pointer; }\n");
Files.writeString(decompiled.resolve(".incari-decompile-stamp"), "stamp-1");
tree = new ClientTree(ws);
}
@Test
void rebuildThenApplyRoundTripsByteForByte() throws Exception {
tree.apply(decompiled, "test", false);
edit("com/example/Greeter.java", "\"hello\"", "\"hi\"");
commit("core: Change the greeting", "Explains why.");
ClientTree.RebuildResult first = tree.rebuildPatches(false);
Path patch = root.resolve("patches/core/0001-change-the-greeting.patch");
assertThat(first.written()).isEqualTo(1);
assertThat(patch).exists();
String text = Files.readString(patch);
assertThat(text)
.contains("Subject: [PATCH] core: Change the greeting")
.contains("From: Tester <tester@example.com>")
.doesNotContain("public class Greeter"); // no function-context hunk header
// Fresh apply from the patch file, then regenerate: nothing may change.
FileTrees.deleteRecursively(ws.clientTree());
tree.apply(decompiled, "test", false);
assertThat(Files.readString(treeFile("com/example/Greeter.java"))).contains("\"hi\"");
ClientTree.RebuildResult second = tree.rebuildPatches(true);
assertThat(second.changed()).isFalse();
assertThat(second.unchanged()).isEqualTo(1);
}
@Test
void checkModeReportsUnsavedCommitsWithoutWriting() throws Exception {
tree.apply(decompiled, "test", false);
edit("com/example/Greeter.java", "\"hello\"", "\"hi\"");
commit("core: Change the greeting", null);
assertThat(tree.rebuildPatches(true).changed()).isTrue();
assertThat(root.resolve("patches")).doesNotExist();
}
@Test
void rebuildRemovesPatchesWhoseCommitsWereDropped() throws Exception {
tree.apply(decompiled, "test", false);
edit("com/example/Greeter.java", "\"hello\"", "\"hi\"");
commit("core: Change the greeting", null);
tree.rebuildPatches(false);
git().run("reset", "--quiet", "--hard", ClientTree.BASE_TAG);
ClientTree.RebuildResult result = tree.rebuildPatches(false);
assertThat(result.removed()).isEqualTo(1);
assertThat(root.resolve("patches/core")).doesNotExist();
}
@Test
void patchesAreNumberedInOneGlobalOrderAcrossSubsystems() throws Exception {
tree.apply(decompiled, "test", false);
edit("com/example/Greeter.java", "\"hello\"", "\"hi\"");
commit("core: Change the greeting", null);
edit("com/example/Buffer.java", "int pointer;", "int offset;");
commit("memory: Replace the raw pointer with an offset", null);
tree.rebuildPatches(false);
assertThat(PatchSet.list(ws.patchesDir()))
.extracting(p -> root.relativize(p.path()).toString())
.containsExactly(
"patches/core/0001-change-the-greeting.patch",
"patches/memory/0002-replace-the-raw-pointer-with-an-offset.patch");
FileTrees.deleteRecursively(ws.clientTree());
tree.apply(decompiled, "test", false);
assertThat(tree.rebuildPatches(true).changed()).isFalse();
}
@Test
void rebuildRejectsSubjectsWithoutASubsystem() throws Exception {
tree.apply(decompiled, "test", false);
edit("com/example/Greeter.java", "\"hello\"", "\"hi\"");
commit("Change the greeting", null);
assertThatThrownBy(() -> tree.rebuildPatches(false))
.isInstanceOf(CliException.class)
.hasMessageContaining("<subsystem>: <summary>");
}
@Test
void rebuildRejectsFileDeletionsInPatches() throws Exception {
tree.apply(decompiled, "test", false);
git().run("rm", "--quiet", Workspace.CLIENT_SOURCE_DIR + "/com/example/Telemetry.java");
commit("telemetry: Remove telemetry", null);
assertThatThrownBy(() -> tree.rebuildPatches(false))
.isInstanceOf(CliException.class)
.hasMessageContaining("classes.txt");
}
@Test
void rebuildRejectsUncommittedEdits() throws Exception {
tree.apply(decompiled, "test", false);
edit("com/example/Greeter.java", "\"hello\"", "\"hi\"");
assertThatThrownBy(() -> tree.rebuildPatches(false))
.isInstanceOf(CliException.class)
.hasMessageContaining("uncommitted changes");
}
@Test
void applyRefusesToDiscardUnsavedWorkUnlessForced() throws Exception {
tree.apply(decompiled, "test", false);
edit("com/example/Greeter.java", "\"hello\"", "\"hi\"");
commit("core: Change the greeting", null);
assertThatThrownBy(() -> tree.apply(decompiled, "test", false))
.isInstanceOf(CliException.class)
.hasMessageContaining("commits not saved");
tree.apply(decompiled, "test", true);
assertThat(Files.readString(treeFile("com/example/Greeter.java"))).contains("\"hello\"");
}
@Test
void classManifestDeletesAndReplacesWholeFiles() throws Exception {
Path replacement = root.resolve("memory/src/Buffer.java");
Files.createDirectories(replacement.getParent());
Files.writeString(replacement, "package com.example;\n\npublic class Buffer { /* Incari */ }\n");
Files.createDirectories(ws.patchesDir());
Files.writeString(ws.classManifest(), """
# test manifest
delete com.example.Telemetry
replace com.example.Buffer memory/src/Buffer.java
""");
tree.apply(decompiled, "test", false);
assertThat(treeFile("com/example/Telemetry.java")).doesNotExist();
assertThat(Files.readString(treeFile("com/example/Buffer.java"))).contains("/* Incari */");
edit("com/example/Buffer.java", "/* Incari */", "/* edited in work/ */");
commit("memory: Edit the replaced class", null);
assertThatThrownBy(() -> tree.rebuildPatches(false))
.isInstanceOf(CliException.class)
.hasMessageContaining("replaces");
}
@Test
void replacementsAreFlaggedWhenTheirOriginalChanges() throws Exception {
Path replacement = root.resolve("memory/src/Buffer.java");
Files.createDirectories(replacement.getParent());
Files.writeString(replacement, "package com.example;\n\npublic class Buffer { /* Incari */ }\n");
Files.createDirectories(ws.patchesDir());
Files.writeString(ws.classManifest(), "replace com.example.Buffer memory/src/Buffer.java\n");
tree.apply(decompiled, "test", false);
assertThat(tree.replacementDrift("test"))
.singleElement()
.satisfies(d -> assertThat(d.recorded()).isNull());
assertThat(tree.stampReplacements("test")).isEqualTo(1);
assertThat(Files.readString(ws.classManifest())).matches("(?s).*memory/src/Buffer\\.java test@[0-9a-f]{12}\n");
assertThat(tree.replacementDrift("test")).isEmpty();
// The next "Minecraft version" changes the original the replacement was written against.
Files.writeString(
decompiled.resolve("com/example/Buffer.java"),
"package com.example;\n\npublic class Buffer { long pointer; }\n");
Files.writeString(decompiled.resolve(".incari-decompile-stamp"), "stamp-2");
tree.apply(decompiled, "next", false);
assertThat(tree.replacementDrift("next")).singleElement().satisfies(d -> {
assertThat(d.className()).isEqualTo("com.example.Buffer");
assertThat(d.recorded().version()).isEqualTo("test");
assertThat(d.current().version()).isEqualTo("next");
});
tree.stampReplacements("next");
assertThat(tree.replacementDrift("next")).isEmpty();
}
@Test
void manifestEntryForAMissingClassFailsClearly() throws Exception {
Files.createDirectories(ws.patchesDir());
Files.writeString(ws.classManifest(), "delete com.example.Gone\n");
assertThatThrownBy(() -> tree.apply(decompiled, "test", false))
.isInstanceOf(CliException.class)
.hasMessageContaining("com.example.Gone");
}
@Test
void conflictingPatchStopsMidApplyWithInstructions() throws Exception {
tree.apply(decompiled, "test", false);
edit("com/example/Greeter.java", "\"hello\"", "\"hi\"");
commit("core: Change the greeting", null);
tree.rebuildPatches(false);
// A new "Minecraft version" whose line the patch touches changed underneath it.
writeVendor(
"com/example/Greeter.java",
Files.readString(decompiled.resolve("com/example/Greeter.java"))
.replace("\"hello\"", "\"hello there\""));
Files.writeString(decompiled.resolve(".incari-decompile-stamp"), "stamp-2");
assertThatThrownBy(() -> tree.apply(decompiled, "test", false))
.isInstanceOf(CliException.class)
.hasMessageContaining("am --continue");
}
// --- helpers ---
private void writeVendor(String relative, String content) throws IOException {
Path file = decompiled.resolve(relative);
Files.createDirectories(file.getParent());
Files.writeString(file, content);
}
private Path treeFile(String relative) {
return ws.clientTree().resolve(Workspace.CLIENT_SOURCE_DIR).resolve(relative);
}
private void edit(String relative, String from, String to) throws IOException {
Path file = treeFile(relative);
String content = Files.readString(file);
assertThat(content).contains(from);
Files.writeString(file, content.replace(from, to));
}
private void commit(String subject, String body) throws Exception {
git().run("add", "--all");
List<String> args = new java.util.ArrayList<>(List.of(
"commit",
"--quiet",
"--author=Tester <tester@example.com>",
"--date=2026-09-25T12:00:00+02:00",
"-m",
subject));
if (body != null) {
args.addAll(List.of("-m", body));
}
git().run(args.toArray(String[]::new));
}
private Git git() {
return new Git(ws.clientTree());
}
}
@@ -0,0 +1,190 @@
package incari.tools.build;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
class ParsingTest {
@Test
void classManifestParsesDeletesReplacesAndComments() {
ClassManifest manifest = ClassManifest.parse(
List.of(
"# comment",
"",
"delete a.b.Telemetry # trailing comment",
"replace a.b.Buffer render-webgl2/src/Buffer.java"),
"classes.txt");
assertThat(manifest.entries())
.containsExactly(
new ClassManifest.Delete("a.b.Telemetry"),
new ClassManifest.Replace("a.b.Buffer", "render-webgl2/src/Buffer.java"));
assertThat(manifest.treePaths())
.containsExactlyInAnyOrder("src/main/java/a/b/Telemetry.java", "src/main/java/a/b/Buffer.java");
}
@Test
void classManifestRejectsBadLines() {
assertThatThrownBy(() -> ClassManifest.parse(List.of("remove a.B"), "m"))
.hasMessageContaining("m:1")
.hasMessageContaining("unknown action");
assertThatThrownBy(() -> ClassManifest.parse(List.of("delete a.B$Inner"), "m"))
.hasMessageContaining("top-level");
assertThatThrownBy(() -> ClassManifest.parse(List.of("replace a.B work/B.java"), "m"))
.hasMessageContaining("outside work/");
assertThatThrownBy(() -> ClassManifest.parse(List.of("replace a.B ../B.java"), "m"))
.hasMessageContaining("outside work/");
assertThatThrownBy(() -> ClassManifest.parse(List.of("delete a.B", "delete a.B"), "m"))
.hasMessageContaining("twice");
}
@Test
void classManifestReadsReplacementStamps() {
ClassManifest manifest = ClassManifest.parse(
List.of("replace a.b.Buffer render-webgl2/src/Buffer.java 26.3@0123456789ab"), "m");
assertThat(manifest.entries())
.containsExactly(new ClassManifest.Replace(
"a.b.Buffer",
"render-webgl2/src/Buffer.java",
new ClassManifest.Stamp("26.3", "0123456789ab")));
assertThatThrownBy(() -> ClassManifest.parse(List.of("replace a.B src/B.java 26.3"), "m"))
.hasMessageContaining("not a stamp");
assertThatThrownBy(() -> ClassManifest.parse(List.of("replace a.B src/B.java 26.3@xyz"), "m"))
.hasMessageContaining("not a stamp");
}
@Test
void stampsAreWrittenInOneColumnAndEverythingElseIsKept() {
List<String> lines = List.of(
"# comment",
"delete a.Gone",
"replace a.Short src/Short.java",
"replace a.LongerName src/LongerName.java 26.2@aaaaaaaaaaaa # note");
var stamps = new java.util.LinkedHashMap<String, ClassManifest.Stamp>();
stamps.put("a.Short", new ClassManifest.Stamp("26.3", "111111111111"));
stamps.put("a.LongerName", new ClassManifest.Stamp("26.3", "222222222222"));
List<String> stamped = ClassManifest.withStamps(lines, stamps);
assertThat(stamped)
.containsExactly(
"# comment",
"delete a.Gone",
"replace a.Short src/Short.java 26.3@111111111111",
"replace a.LongerName src/LongerName.java 26.3@222222222222 # note");
assertThat(ClassManifest.withStamps(stamped, stamps)).isEqualTo(stamped);
assertThat(ClassManifest.parse(stamped, "m").entries()).hasSize(3);
}
@Test
void patchFileNamesComeFromTheSubject() {
assertThat(PatchSet.fileFor(3, "render: Route section compile to the mesher"))
.isEqualTo("render/0003-route-section-compile-to-the-mesher.patch");
assertThat(PatchSet.slug("Fix `MemoryUtil` (again!)")).isEqualTo("fix-memoryutil-again");
assertThat(PatchSet.slug("a".repeat(30) + " " + "b".repeat(40))).isEqualTo("a".repeat(30));
assertThatThrownBy(() -> PatchSet.fileFor(1, "Render: capitalised subsystem"))
.isInstanceOf(CliException.class);
}
@Test
void patchListRejectsDuplicateNumbersAndStrayFiles(@TempDir Path dir) throws Exception {
Files.createDirectories(dir.resolve("render"));
Files.createDirectories(dir.resolve("net"));
Files.writeString(dir.resolve("render/0002-b.patch"), "");
Files.writeString(dir.resolve("net/0001-a.patch"), "");
assertThat(PatchSet.list(dir)).extracting(PatchSet.PatchFile::subsystem).containsExactly("net", "render");
Files.writeString(dir.resolve("net/0002-c.patch"), "");
assertThatThrownBy(() -> PatchSet.list(dir)).hasMessageContaining("share number 2");
Files.delete(dir.resolve("net/0002-c.patch"));
Files.writeString(dir.resolve("loose.patch"), "");
assertThatThrownBy(() -> PatchSet.list(dir)).hasMessageContaining("Unexpected patch file");
}
@Test
void versionJsonKeepsOnlyArtifactsAndFlagsNatives() {
String json = """
{
"id": "26.3",
"javaVersion": {"component": "java-runtime-epsilon", "majorVersion": 25},
"downloads": {"client": {"url": "https://example.invalid/client.jar", "sha1": "abc", "size": 10}},
"libraries": [
{"name": "org.example:lib:1.0",
"downloads": {"artifact": {"path": "org/example/lib/1.0/lib-1.0.jar", "url": "https://example.invalid/lib.jar", "sha1": "def", "size": 5}}},
{"name": "org.example:lib:1.0:natives-linux",
"downloads": {"artifact": {"path": "org/example/lib/1.0/lib-1.0-natives-linux.jar", "url": "https://example.invalid/n.jar", "sha1": "123", "size": 5}},
"rules": [{"action": "allow", "os": {"name": "linux"}}]},
{"name": "org.example:no-artifact:1.0"}
]
}
""";
MojangMetadata.Version version = MojangMetadata.parseVersion(json);
assertThat(version.javaMajorVersion()).isEqualTo(25);
assertThat(version.client().sha1()).isEqualTo("abc");
assertThat(version.libraries())
.extracting(MojangMetadata.Library::name, MojangMetadata.Library::platformSpecific)
.containsExactly(
org.assertj.core.groups.Tuple.tuple("org.example:lib:1.0", false),
org.assertj.core.groups.Tuple.tuple("org.example:lib:1.0:natives-linux", true));
}
@Test
void manifestLookupFindsTheVersionJson() {
String manifest = """
{"latest": {"release": "26.3"},
"versions": [{"id": "26.3", "url": "https://example.invalid/26.3.json", "sha1": "bc09"}]}
""";
assertThat(MojangMetadata.findVersion(manifest, "26.3").sha1()).isEqualTo("bc09");
assertThatThrownBy(() -> MojangMetadata.findVersion(manifest, "1.0")).isInstanceOf(CliException.class);
}
@Test
void workspaceIsFoundFromASubdirectory(@TempDir Path dir) throws Exception {
Files.writeString(dir.resolve(BuildConfig.FILE_NAME), "");
Path nested = Files.createDirectories(dir.resolve("a/b"));
assertThat(Workspace.discover(nested).repoRoot())
.isEqualTo(dir.toAbsolutePath().normalize());
}
@Test
void nativePlatformNamesMatchMojangsClassifiers() {
assertThat(NativePlatform.of("Linux", "amd64").classifier()).isEqualTo("natives-linux");
assertThat(NativePlatform.of("Windows 11", "aarch64").classifier()).isEqualTo("natives-windows-arm64");
assertThat(NativePlatform.of("Mac OS X", "aarch64").classifier()).isEqualTo("natives-macos-arm64");
assertThatThrownBy(() -> NativePlatform.of("FreeBSD", "amd64")).isInstanceOf(CliException.class);
}
@Test
void hostNativesPickOnlyThisPlatformsJars() {
String json = """
{
"id": "26.3",
"javaVersion": {"majorVersion": 25},
"downloads": {"client": {"url": "https://example.invalid/c.jar", "sha1": "abc", "size": 1}},
"libraries": [
{"name": "org.lwjgl:lwjgl:3.4.3",
"downloads": {"artifact": {"path": "l.jar", "url": "https://example.invalid/l.jar", "sha1": "1", "size": 1}}},
{"name": "org.lwjgl:lwjgl:3.4.3:natives-linux",
"downloads": {"artifact": {"path": "ll.jar", "url": "https://example.invalid/ll.jar", "sha1": "2", "size": 1}}},
{"name": "org.lwjgl:lwjgl:3.4.3:natives-windows",
"downloads": {"artifact": {"path": "lw.jar", "url": "https://example.invalid/lw.jar", "sha1": "3", "size": 1}}}
]
}
""";
MojangMetadata.Version version = MojangMetadata.parseVersion(json);
assertThat(GameFiles.hostNatives(version, NativePlatform.of("Linux", "amd64")))
.extracting(MojangMetadata.Library::path)
.containsExactly("ll.jar");
assertThat(version.libraries().getFirst().classifier()).isEmpty();
}
}