Skip to content

Commit 774e118

Browse files
committed
#244 Use temporary working file when adding module-info
1 parent 80c1c1d commit 774e118

1 file changed

Lines changed: 13 additions & 4 deletions

File tree

core/src/main/java/org/moditect/commands/AddModuleInfo.java

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
import java.io.OutputStream;
1414
import java.nio.file.Files;
1515
import java.nio.file.Path;
16+
import java.nio.file.StandardCopyOption;
1617
import java.nio.file.attribute.FileTime;
1718
import java.time.Instant;
1819
import java.util.Enumeration;
@@ -97,12 +98,12 @@ public void run() {
9798
ModuleDeclaration module = ModuleInfoCompiler.parseModuleInfo(moduleInfoSource);
9899
byte[] clazz = ModuleInfoCompiler.compileModuleInfo(module, mainClass, version);
99100

101+
Path tmpOutputJar = null;
100102
try {
101-
Files.createDirectories(outputJar.toAbsolutePath().getParent());
102-
Files.createFile(outputJar.toAbsolutePath());
103+
tmpOutputJar = Files.createTempFile("moditect", "jar");
103104
}
104105
catch (IOException e) {
105-
throw new RuntimeException("Couldn't copy JAR file", e);
106+
throw new RuntimeException("Couldn't create tmp JAR file", e);
106107
}
107108

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

112113
// brute force copy all entries
113114
try (JarFile jarFile = new JarFile(inputJar.toAbsolutePath().toFile());
114-
JarOutputStream jarout = new JarOutputStream(Files.newOutputStream(outputJar.toAbsolutePath(), TRUNCATE_EXISTING))) {
115+
JarOutputStream jarout = new JarOutputStream(Files.newOutputStream(tmpOutputJar.toAbsolutePath(), TRUNCATE_EXISTING))) {
115116
Enumeration<JarEntry> entries = jarFile.entries();
116117
while (entries.hasMoreElements()) {
117118
JarEntry inputEntry = entries.nextElement();
@@ -157,6 +158,14 @@ else if ((MODULE_INFO_CLASS.equals(inputEntry.getName()) && !versionedModuleInfo
157158
catch (IOException e) {
158159
throw new RuntimeException("Couldn't add module-info.class to JAR", e);
159160
}
161+
162+
try {
163+
Files.createDirectories(outputJar.toAbsolutePath().getParent());
164+
Files.move(tmpOutputJar, outputJar, StandardCopyOption.REPLACE_EXISTING);
165+
}
166+
catch (IOException e) {
167+
throw new RuntimeException("Couldn't copy JAR file", e);
168+
}
160169
}
161170

162171
private FileTime toFileTime(Instant timestamp) {

0 commit comments

Comments
 (0)