Polish "Delete layer temp file when layer creation fails"

See gh-51519

Signed-off-by: Andy Wilkinson <andy.wilkinson@broadcom.com>
This commit is contained in:
Andy Wilkinson
2026-09-04 11:12:11 +01:00
parent 5d6e417134
commit 71bfa94d10
@@ -139,25 +139,7 @@ final class ImageBuildpack implements Buildpack {
}
Path layerFile = Files.createTempFile("create-builder-scratch-", null);
try {
try (TarArchiveOutputStream out = new TarArchiveOutputStream(Files.newOutputStream(layerFile))) {
try (TarArchiveInputStream in = new TarArchiveInputStream(
Files.newInputStream(sourceTarFile))) {
out.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
TarArchiveEntry entry = in.getNextEntry();
while (entry != null) {
String entryName = entry.getName();
Path entryPath = Path.of(entryName);
Assert.state(entryPath.toAbsolutePath().equals(entryPath.toAbsolutePath().normalize()),
() -> "Malformed zip entry name '%s'".formatted(entryName));
out.putArchiveEntry(entry);
StreamUtils.copy(in, out);
out.closeArchiveEntry();
entry = in.getNextEntry();
}
out.finish();
}
}
return layerFile;
writeLayerFile(layerFile, sourceTarFile);
}
catch (IOException | RuntimeException ex) {
try {
@@ -168,12 +150,33 @@ final class ImageBuildpack implements Buildpack {
}
throw ex;
}
return layerFile;
}
finally {
Files.deleteIfExists(sourceTarFile);
}
}
private void writeLayerFile(Path layerFile, Path sourceTarFile) throws IOException {
try (TarArchiveOutputStream out = new TarArchiveOutputStream(Files.newOutputStream(layerFile))) {
try (TarArchiveInputStream in = new TarArchiveInputStream(Files.newInputStream(sourceTarFile))) {
out.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
TarArchiveEntry entry = in.getNextEntry();
while (entry != null) {
String entryName = entry.getName();
Path entryPath = Path.of(entryName);
Assert.state(entryPath.toAbsolutePath().equals(entryPath.toAbsolutePath().normalize()),
() -> "Malformed zip entry name '%s'".formatted(entryName));
out.putArchiveEntry(entry);
StreamUtils.copy(in, out);
out.closeArchiveEntry();
entry = in.getNextEntry();
}
out.finish();
}
}
}
void apply(IOConsumer<Layer> layers) throws IOException {
for (Path path : this.layerFiles) {
layers.accept(Layer.fromTarArchive((out) -> {