Inceptum/launcher/src/main/java/io/gitlab/jfronny/inceptum/launcher/system/exporter/Exporter.java

74 lines
3.3 KiB
Java

package io.gitlab.jfronny.inceptum.launcher.system.exporter;
import io.gitlab.jfronny.inceptum.common.Utils;
import io.gitlab.jfronny.inceptum.launcher.system.instance.*;
import io.gitlab.jfronny.inceptum.launcher.util.*;
import io.gitlab.jfronny.inceptum.launcher.util.gitignore.IgnoringWalk;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.*;
import java.util.Objects;
public abstract class Exporter<Manifest> {
private final String name;
private final String fileExtension;
private final String overridesDirName;
public Exporter(String name, String fileExtension, String overridesDirName) {
this.name = Objects.requireNonNull(name);
this.fileExtension = Objects.requireNonNull(fileExtension);
this.overridesDirName = Objects.requireNonNull(overridesDirName);
}
protected abstract Manifest generateManifests(Path root, Instance instance, String version) throws IOException;
protected abstract void addMods(Path root, Instance instance, Iterable<Mod> mods, Manifest manifest, Path modsOverrides) throws IOException;
public void generate(ProcessState state, Instance instance, Path exportPath, String version) throws IOException {
if (Files.exists(exportPath)) Files.delete(exportPath);
try (FileSystem fs = Utils.openZipFile(exportPath, true)) {
Path root = fs.getPath(".");
Path overrides = fs.getPath(overridesDirName);
state.incrementStep("Preparing manifests");
Manifest manifest = generateManifests(root, instance, version);
if (instance.isFabric()) {
state.incrementStep("Adding mods");
addMods(root, instance, new StreamIterable<>(instance.getMods().stream().filter(mod -> {
if (!mod.isEnabled()) return false;
state.updateStep(mod.getName());
return true;
})), manifest, overrides.resolve("mods"));
}
state.incrementStep("Adding files");
filesLoop: for (Path path : new StreamIterable<>(IgnoringWalk.walk(instance.path()))) {
Path relativePath = instance.path().relativize(path).normalize();
Path target = overrides;
for (Path segment : relativePath) {
if (target == overrides && segment.toString().equals("mods")) continue filesLoop;
if (segment.toString().startsWith(".")) continue filesLoop;
target = target.resolve(segment.toString());
}
state.updateStep(relativePath.toString());
Files.createDirectories(target.getParent());
Files.copy(path, target);
}
state.incrementStep("Cleaning up");
Files.walkFileTree(root, new CleanupFileVisitor());
} catch (URISyntaxException se) {
// Can only be thrown by openZipFile, the target file therefore cannot exist
throw new IOException("Could not open export path", se);
} catch (Throwable t) {
if (Files.exists(exportPath)) Files.delete(exportPath);
throw t;
}
}
public String getName() {
return name;
}
public String getFileExtension() {
return fileExtension;
}
}