Skip to content

Commit

Permalink
#244 Use temporary working file when adding module-info
Browse files Browse the repository at this point in the history
  • Loading branch information
aalmiray committed Mar 26, 2024
1 parent 80c1c1d commit 774e118
Showing 1 changed file with 13 additions and 4 deletions.
17 changes: 13 additions & 4 deletions core/src/main/java/org/moditect/commands/AddModuleInfo.java
Expand Up @@ -13,6 +13,7 @@
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.FileTime;
import java.time.Instant;
import java.util.Enumeration;
Expand Down Expand Up @@ -97,12 +98,12 @@ public void run() {
ModuleDeclaration module = ModuleInfoCompiler.parseModuleInfo(moduleInfoSource);
byte[] clazz = ModuleInfoCompiler.compileModuleInfo(module, mainClass, version);

Path tmpOutputJar = null;
try {
Files.createDirectories(outputJar.toAbsolutePath().getParent());
Files.createFile(outputJar.toAbsolutePath());
tmpOutputJar = Files.createTempFile("moditect", "jar");
}
catch (IOException e) {
throw new RuntimeException("Couldn't copy JAR file", e);
throw new RuntimeException("Couldn't create tmp JAR file", e);
}

boolean versionedModuleInfo = jvmVersion != null;
Expand All @@ -111,7 +112,7 @@ public void run() {

// brute force copy all entries
try (JarFile jarFile = new JarFile(inputJar.toAbsolutePath().toFile());
JarOutputStream jarout = new JarOutputStream(Files.newOutputStream(outputJar.toAbsolutePath(), TRUNCATE_EXISTING))) {
JarOutputStream jarout = new JarOutputStream(Files.newOutputStream(tmpOutputJar.toAbsolutePath(), TRUNCATE_EXISTING))) {
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry inputEntry = entries.nextElement();
Expand Down Expand Up @@ -157,6 +158,14 @@ else if ((MODULE_INFO_CLASS.equals(inputEntry.getName()) && !versionedModuleInfo
catch (IOException e) {
throw new RuntimeException("Couldn't add module-info.class to JAR", e);
}

try {
Files.createDirectories(outputJar.toAbsolutePath().getParent());
Files.move(tmpOutputJar, outputJar, StandardCopyOption.REPLACE_EXISTING);
}
catch (IOException e) {
throw new RuntimeException("Couldn't copy JAR file", e);
}
}

private FileTime toFileTime(Instant timestamp) {
Expand Down

0 comments on commit 774e118

Please sign in to comment.