Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Fix getOriginalSourceFragment and getRawJavadoc for zip file inputs #4850

Merged
merged 3 commits into from
Sep 11, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/main/java/spoon/support/Internal.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@
import java.lang.annotation.Target;

/**
* Tells that a class or method is not in the public API (even if it has Java visibility "public")
* Tells that an element is not in the public API (even if it has Java visibility "public")
* Required because package-visibility is too coarse-grained.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.TYPE })
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.TYPE })
MartinWitt marked this conversation as resolved.
Show resolved Hide resolved
public @interface Internal {
}
77 changes: 57 additions & 20 deletions src/main/java/spoon/support/compiler/ZipFile.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,32 +7,68 @@
*/
package spoon.support.compiler;

import spoon.SpoonException;
import spoon.compiler.SpoonFile;
import spoon.compiler.SpoonFolder;
import spoon.support.Internal;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Objects;

import spoon.compiler.SpoonFile;
import spoon.compiler.SpoonFolder;

public class ZipFile implements SpoonFile {

byte[] content;

String name;

ZipFolder parent;

private final String name;
private final ZipFolder parent;
private final Path tempFile;
private final byte[] content;

/**
* Creates a new zip file. Should never be called manually.
*
* @param parent the parent folder
* @param name the name of the file
* @param content the content of the file
* @deprecated use {@link ZipFile#ZipFile(ZipFolder, String, Path)}
*/
@Deprecated
public ZipFile(ZipFolder parent, String name, byte[] content) {
this.content = content;
this.name = name;
this.parent = parent;
this.tempFile = null;
}

/**
* Creates a new zip file. Should never be called manually.
*
* @param parent the parent folder
* @param name the name of the file
* @param tempFile the temporary file it was cached to
*/
@Internal
public ZipFile(ZipFolder parent, String name, Path tempFile) {
this.parent = parent;
this.name = name;
this.tempFile = tempFile;
this.content = null;
}

@Override
public InputStream getContent() {
return new ByteArrayInputStream(content);
if (content != null) {
return new ByteArrayInputStream(content);
}
try {
return Files.newInputStream(Objects.requireNonNull(tempFile));
} catch (IOException e) {
throw new SpoonException(e);
}
}

@Override
Expand Down Expand Up @@ -62,6 +98,9 @@ public boolean isJava() {

@Override
public String getPath() {
if (tempFile != null) {
return tempFile.toAbsolutePath().toString();
}
return toString();
}

Expand All @@ -82,15 +121,13 @@ public File toFile() {

@Override
public boolean isActualFile() {
return false;
return tempFile != null;
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(content);
result = prime * result + Objects.hash(name, parent);
int result = Objects.hash(name, parent, tempFile);
result = 31 * result + Arrays.hashCode(content);
return result;
}

Expand All @@ -102,11 +139,11 @@ public boolean equals(Object obj) {
if (!(obj instanceof ZipFile)) {
return false;
}
ZipFile other = (ZipFile) obj;
return Arrays.equals(content, other.content) && Objects.equals(name, other.name)
&& Objects.equals(parent, other.parent);
ZipFile zipFile = (ZipFile) obj;
return Objects.equals(name, zipFile.name)
&& Objects.equals(parent, zipFile.parent)
&& Objects.equals(tempFile, zipFile.tempFile)
&& Arrays.equals(content, zipFile.content);
}



}
69 changes: 50 additions & 19 deletions src/main/java/spoon/support/compiler/ZipFolder.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,28 +7,36 @@
*/
package spoon.support.compiler;

import org.apache.commons.io.FileUtils;
import spoon.Launcher;
import spoon.SpoonException;
import spoon.compiler.SpoonFile;
import spoon.compiler.SpoonFolder;
import spoon.compiler.SpoonResourceHelper;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UncheckedIOException;
import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import spoon.Launcher;
import spoon.SpoonException;
import spoon.compiler.SpoonFile;
import spoon.compiler.SpoonFolder;
import spoon.compiler.SpoonResourceHelper;

public class ZipFolder implements SpoonFolder {

File file;
Expand Down Expand Up @@ -57,22 +65,47 @@ public List<SpoonFile> getFiles() {
// Indexing content
if (files == null) {
files = new ArrayList<>();
try (ZipInputStream zipInput = new ZipInputStream(new BufferedInputStream(new FileInputStream(file)));
ByteArrayOutputStream output = new ByteArrayOutputStream(2048)) {

ZipEntry entry;
while ((entry = zipInput.getNextEntry()) != null) {
zipInput.transferTo(output);
files.add(new ZipFile(this, entry.getName(), output.toByteArray()));
output.reset();
try (FileSystem zip = FileSystems.newFileSystem(URI.create("jar:" + file.toURI()), Map.of())) {
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This can be made nicer in Java 13+, but for now we are stuck with it. URI.toString() should round-trip, so this should be safe for arbitrary paths.

Path tempFolder = Files.createTempDirectory("spoon-zip-file-proxy");
// Try to clean up - not guaranteed to work!
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This wasn't guaranteed before as well and depends on the mood of the JVM. File#deleteOnExit() which was used before in Sources also registers a shutdown hook.

Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
FileUtils.deleteDirectory(tempFolder.toFile());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}));


for (Path directory : zip.getRootDirectories()) {
copyFolder(directory, tempFolder);
}
} catch (Exception e) {
Launcher.LOGGER.error(e.getMessage(), e);
Launcher.LOGGER.error("Error copying zip file contents", e);
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LOGGER.error crashes with null messages, which is not ideal if you are trying to log such a message.

}
}
return files;
}

private void copyFolder(Path source, Path target) throws IOException {
try (Stream<Path> stream = Files.walk(source)) {
for (Path path : (Iterable<Path>) stream::iterator) {
// This little dance is needed, as resolve with the Path fails: The two paths are in different and
// incompatible file systems!
String relativePath = source.relativize(path).toString();
Path targetFile = target.resolve(relativePath);

if (Files.isDirectory(path)) {
Files.createDirectories(targetFile);
} else {
// walked in depth-first order, so we can just copy it and expect the parent to exist
Files.copy(path, targetFile);
files.add(new ZipFile(this, relativePath, targetFile));
}
}
}
}

@Override
public String getName() {
return file.getName();
Expand Down Expand Up @@ -128,8 +161,6 @@ public File toFile() {
return file;
}



@Override
public int hashCode() {
return file.hashCode();
Expand Down
67 changes: 67 additions & 0 deletions src/test/java/spoon/support/compiler/ZipFileTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package spoon.support.compiler;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import spoon.Launcher;
import spoon.reflect.declaration.CtMethod;
import spoon.reflect.declaration.CtType;

import java.io.IOException;
import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringContains.containsString;
import static org.junit.jupiter.api.Assertions.assertNotNull;

class ZipFileTest {

@Test
void fetchingSourceFragmentWorks(@TempDir Path tempDir) throws IOException {
// contract: Fetching an original source code fragment from a zip folder input works
Launcher launcher = new Launcher();
launcher.addInputResource(new ZipFolder(createZip(tempDir).toFile()));
launcher.buildModel();

CtType<?> type = launcher.getFactory().Type().get("a.Test");
CtMethod<?> method = type.getMethod("foo");
assertNotNull(method.getOriginalSourceFragment().getSourceCode());
assertThat(method.getOriginalSourceFragment().getSourceCode(), containsString("/**"));
assertThat(method.getOriginalSourceFragment().getSourceCode(), containsString("foo()"));
}

private Path createZip(Path tempDir) throws IOException {
Files.createDirectories(tempDir.resolve("a"));

Path testFile = tempDir.resolve("a").resolve("Test.java");
Files.writeString(
testFile,
"package a;\n" +
"class Test {\n" +
" /**\n" +
" * A foo method.\n" +
" *\n" +
" * @return some int\n" +
" */\n" +
" public int foo() {\n" +
" return 1 + 1;\n" +
" }" +
"}"
);

Path zipPath = tempDir.resolve("test.zip");
try (FileSystem zip = FileSystems.newFileSystem(
URI.create("jar:" + zipPath.toUri()),
Map.of("create", true)
)) {
Files.createDirectories(zip.getPath("a"));
Files.copy(testFile, zip.getPath("a/Test.java"));
}

return zipPath;
}
}