PT #151978919 VSCode navigation to resource from hovers (POC)

This commit is contained in:
BoykoAlex
2018-01-19 19:26:29 -05:00
parent bf096850a4
commit 286d435d53
14 changed files with 417 additions and 13 deletions

View File

@@ -1,5 +1,5 @@
/*******************************************************************************
* Copyright (c) 2017 Pivotal, Inc.
* Copyright (c) 2017, 2018 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
@@ -10,13 +10,16 @@
*******************************************************************************/
package org.springframework.ide.vscode.boot.java.livehover;
import java.util.Optional;
import java.util.stream.Stream;
import org.springframework.ide.vscode.boot.java.utils.SourceLinks;
import org.springframework.ide.vscode.boot.java.utils.SpringResource;
import org.springframework.ide.vscode.commons.boot.app.cli.SpringBootApp;
import org.springframework.ide.vscode.commons.boot.app.cli.livebean.LiveBean;
import org.springframework.ide.vscode.commons.boot.app.cli.livebean.LiveBeansModel;
import org.springframework.ide.vscode.commons.java.IJavaProject;
import org.springframework.ide.vscode.commons.util.Renderables;
import org.springframework.ide.vscode.commons.util.StringUtil;
public class LiveHoverUtils {
@@ -33,9 +36,17 @@ public class LiveHoverUtils {
public static String showBeanWithResource(LiveBean bean, String indentStr, IJavaProject project) {
String newline = " \n"+indentStr; //Note: the double space before newline makes markdown see it as a real line break
String type = bean.getType(true);
// Try creating a URL link to open source for the type
Optional<String> url = SourceLinks.sourceLinkUrl(project, type);
if (url.isPresent()) {
return Renderables.link(type, url.get()).toMarkdown();
}
StringBuilder buf = new StringBuilder("Bean: ");
buf.append(bean.getId());
String type = bean.getType(true);
if (type != null) {
buf.append(newline);
buf.append("Type: `" + type + "`");

View File

@@ -0,0 +1,152 @@
/*******************************************************************************
* Copyright (c) 2018 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springframework.ide.vscode.boot.java.utils;
import java.io.File;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;
import org.springframework.ide.vscode.commons.java.IClasspath;
import org.springframework.ide.vscode.commons.java.IJavaProject;
import org.springframework.ide.vscode.commons.languageserver.util.LspClient;
import org.springframework.ide.vscode.commons.util.Log;
/**
* Utility for creating code navigate links for Markdown format documentation.
* The utility looks at the environment variable "sts.lsp.client" to create a URL supported on a specific client
*
* @author Alex Boyko
*
*/
public class SourceLinks {
private static final String JAR = ".jar";
private static final String JAVA = ".java";
private static final String CLASS = ".class";
public static Optional<String> sourceLinkUrl(IJavaProject project, String fqName) {
switch (LspClient.currentClient()) {
case VSCODE:
return createVSCodeSourceLink(project, fqName);
default:
return Optional.empty();
}
}
private static Optional<String> createVSCodeSourceLink(IJavaProject project, String fqName) {
Optional<File> classpathResource = project.getClasspath().findClasspathResourceContainer(fqName);
if (classpathResource.isPresent()) {
File file = classpathResource.get();
if (file.isDirectory()) {
return javaSourceLinkUrl(project, fqName, file);
} else if (file.getName().endsWith(JAR)) {
return jarSourceLinkUrl(project, fqName, file);
}
}
return Optional.empty();
}
private static Optional<String> javaSourceLinkUrl(IJavaProject project, String javaRelativePath, String fqName) {
Path path = Paths.get(javaRelativePath);
Optional<Path> sourceResource = project.getClasspath().getSourceFolders().stream()
.map(r -> Paths.get(r).resolve(path)).filter(r -> Files.exists(r)).findFirst();
if (sourceResource.isPresent()) {
StringBuilder sb = new StringBuilder();
sb.append("file://");
sb.append(sourceResource.get().toString());
return Optional.of(sb.toString());
}
return Optional.empty();
}
private static Optional<String> javaSourceLinkUrl(IJavaProject project, String fqName, File containerFolder) {
IClasspath classpath = project.getClasspath();
if (containerFolder.toPath().startsWith(classpath.getOutputFolder())) {
int innerTypeIdx = fqName.indexOf('$');
String topLevelType = innerTypeIdx > 0 ? fqName.substring(0, innerTypeIdx) : fqName;
return javaSourceLinkUrl(project, topLevelType.replaceAll("\\.", "/") + JAVA, fqName);
}
return Optional.empty();
}
private static Optional<String> jarSourceLinkUrl(IJavaProject project, String fqName, File jarFile) {
try {
int lastDotIndex = fqName.lastIndexOf('.');
String packageName = fqName.substring(0, lastDotIndex);
String typeName = fqName.substring(lastDotIndex + 1);
String jarFileName = jarFile.getName();
StringBuilder sb = new StringBuilder();
sb.append("jdt://contents/");
sb.append(jarFileName);
sb.append("/");
sb.append(packageName);
sb.append("/");
sb.append(typeName);
sb.append(CLASS);
sb.append("?");
StringBuilder query = new StringBuilder();
query.append("=");
query.append(project.getElementName());
query.append("/");
String convertedPath = String.join("\\/", jarFile.toString().split(File.separator));
query.append(convertedPath);
query.append("<");
query.append(packageName);
query.append("(");
query.append(typeName);
query.append(CLASS);
sb.append(URLEncoder.encode(query.toString(), "UTF8"));
return Optional.of(sb.toString());
} catch (Throwable t) {
Log.log(t);
}
return Optional.empty();
}
// private static Optional<Region> findTypeRange(CompilationUnit cu, String fqName) {
// int[] values = new int[] {0, -1};
// int lastDotIndex = fqName.lastIndexOf('.');
// String packageName = fqName.substring(0, lastDotIndex);
// String typeName = fqName.substring(lastDotIndex + 1);
// if (packageName.equals(cu.getPackage().getName().getFullyQualifiedName())) {
// Stack<String> visitedType = new Stack<>();
// cu.accept(new ASTVisitor() {
//
// @Override
// public boolean visit(TypeDeclaration node) {
// if (values[1] < 0) {
// visitedType.push(node.getName().getIdentifier());
// if (String.join("$", visitedType.toArray(new String[visitedType.size()])).equals(typeName)) {
// values[0] = node.getName().getStartPosition();
// values[1] = node.getName().getLength();
// }
// }
// return values[1] < 0;
// }
//
// @Override
// public void endVisit(TypeDeclaration node) {
// visitedType.pop();
// super.endVisit(node);
// }
//
// });
// }
// return Optional.ofNullable(values[1] < 0 ? null : new Region(values[0], values[1]));
// }
}

View File

@@ -0,0 +1,91 @@
/*******************************************************************************
* Copyright (c) 2018 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springframework.ide.vscode.boot.java.utils.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.ide.vscode.boot.java.utils.SourceLinks;
import org.springframework.ide.vscode.commons.languageserver.util.LspClient;
import org.springframework.ide.vscode.commons.maven.MavenBuilder;
import org.springframework.ide.vscode.commons.maven.MavenCore;
import org.springframework.ide.vscode.commons.maven.java.MavenJavaProject;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
/**
* Tests for creation of VSCode links in hover documentation
*
* @author Alex Boyko
*
*/
public class VSCodeSourceLinksTest {
private static LoadingCache<String, MavenJavaProject> mavenProjectsCache = CacheBuilder.newBuilder().build(new CacheLoader<String, MavenJavaProject>() {
@Override
public MavenJavaProject load(String projectName) throws Exception {
Path testProjectPath = Paths.get(VSCodeSourceLinksTest.class.getResource("/test-projects/" + projectName).toURI());
MavenBuilder.newBuilder(testProjectPath).clean().pack().javadoc().skipTests().execute();
return new MavenJavaProject(MavenCore.getDefault(), testProjectPath.resolve(MavenCore.POM_XML).toFile());
}
});
@Before
public void setupAll() throws Exception {
System.setProperty("sts.lsp.client", LspClient.Client.VSCODE.toString());
}
@After
public void tearDownAll() throws Exception {
System.setProperty("sts.lsp.client", "");
}
@Test
public void testJavaSourceUrl() throws Exception {
MavenJavaProject project = mavenProjectsCache.get("empty-boot-15-web-app");
Optional<String> url = SourceLinks.sourceLinkUrl(project, "com.example.EmptyBoot15WebAppApplication");
assertTrue(url.isPresent());
Path projectPath = Paths.get(project.pom().getParent());
Path relativePath = projectPath.relativize(Paths.get(new URL(url.get()).toURI()));
assertEquals(Paths.get("src/main/java/com/example/EmptyBoot15WebAppApplication.java"), relativePath);
}
@Test
public void testJarUrl() throws Exception {
MavenJavaProject project = mavenProjectsCache.get("empty-boot-15-web-app");
Optional<String> url = SourceLinks.sourceLinkUrl(project, "org.springframework.boot.autoconfigure.SpringBootApplication");
assertTrue(url.isPresent());
String headerPart = url.get().substring(0, url.get().indexOf('?'));
assertEquals("jdt://contents/spring-boot-autoconfigure-1.5.8.RELEASE.jar/org.springframework.boot.autoconfigure/SpringBootApplication.class", headerPart);
}
@Test
public void testJarUrlInnerType() throws Exception {
MavenJavaProject project = mavenProjectsCache.get("empty-boot-15-web-app");
Optional<String> url = SourceLinks.sourceLinkUrl(project, "org.springframework.web.client.RestTemplate$AcceptHeaderRequestCallback");
assertTrue(url.isPresent());
String headerPart = url.get().substring(0, url.get().indexOf('?'));
assertEquals("jdt://contents/spring-web-4.3.12.RELEASE.jar/org.springframework.web.client/RestTemplate$AcceptHeaderRequestCallback.class", headerPart);
}
}

View File

@@ -1,5 +1,5 @@
/*******************************************************************************
* Copyright (c) 2017 Pivotal, Inc.
* Copyright (c) 2017, 2018 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
@@ -236,5 +236,10 @@ public class GradleProjectClasspath extends JandexClasspath {
return false;
}
@Override
public ImmutableList<String> getSourceFolders() {
return ImmutableList.copyOf(project.getSourceDirectories().stream()
.map(dir -> dir.getDirectory().toPath().toString()).collect(Collectors.toList()));
}
}

View File

@@ -1,7 +1,18 @@
/*******************************************************************************
* Copyright (c) 2017, 2018 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springframework.ide.vscode.commons.jandex;
import java.io.File;
import java.nio.file.Path;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@@ -17,6 +28,12 @@ import com.google.common.base.Suppliers;
import reactor.core.publisher.Flux;
import reactor.util.function.Tuple2;
/**
* Classpath with Jandex Java index for searching types
*
* @author Alex Boyko
*
*/
public abstract class JandexClasspath implements IClasspath {
public static JavadocProviderTypes providerType = JavadocProviderTypes.HTML;
@@ -81,6 +98,11 @@ public abstract class JandexClasspath implements IClasspath {
return JandexIndex.getIndexFolder();
}
@Override
public Optional<File> findClasspathResourceContainer(String fqName) {
return javaIndex.get().findClasspathResourceForType(fqName);
}
abstract protected IJavadocProvider createParserJavadocProvider(File classpathResource);
abstract protected IJavadocProvider createHtmlJavdocProvider(File classpathResource);

View File

@@ -1,5 +1,5 @@
/*******************************************************************************
* Copyright (c) 2016-2017 Pivotal, Inc.
* Copyright (c) 2016, 2018 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
@@ -227,6 +227,27 @@ public class JandexIndex {
.orElse(null));
}
private Optional<Tuple2<File, ClassInfo>> findMatch(DotName fqName) {
return (baseIndex == null ? Stream.<Optional<Tuple2<File, ClassInfo>>>empty()
: Arrays.stream(
baseIndex)
.filter(
jandexIndex -> jandexIndex != null)
.map(jandexIndex -> jandexIndex.findMatch(fqName))).filter(o -> o.isPresent())
.findFirst()
// If not found look at indices owned by this
// JandexIndex instance
.orElseGet(() -> streamOfIndices()
.map(e -> Tuples.of(e.getT1(), Optional.ofNullable(e.getT2().getClassByName(fqName))))
.filter(t -> t.getT2().isPresent())
.map(e -> Tuples.of(e.getT1(), e.getT2().get())).findFirst());
}
public Optional<File> findClasspathResourceForType(String fqName) {
Optional<Tuple2<File, ClassInfo>> match = findMatch(DotName.createSimple(fqName));
return Optional.ofNullable(match.isPresent() ? match.get().getT1() : null);
}
private IType createType(Tuple2<File, ClassInfo> match) {
File classpathResource = match.getT1();

View File

@@ -1,5 +1,5 @@
/*******************************************************************************
* Copyright (c) 2017 Pivotal, Inc.
* Copyright (c) 2017, 2018 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
@@ -18,6 +18,7 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicReference;
@@ -255,5 +256,17 @@ public class DelegatingCachedClasspath<T extends IClasspath> implements IClasspa
new LinkedHashSet<>(newDelegate.getClasspathResources()), newDelegate.getOutputFolder());
}
}
@Override
public ImmutableList<String> getSourceFolders() {
T t = cachedDelegate.get();
return t == null ? ImmutableList.of() : t.getSourceFolders();
}
@Override
public Optional<File> findClasspathResourceContainer(String fqName) {
T t = cachedDelegate.get();
return t == null ? Optional.empty() : t.findClasspathResourceContainer(fqName);
}
}

View File

@@ -1,5 +1,5 @@
/*******************************************************************************
* Copyright (c) 2016 Pivotal, Inc.
* Copyright (c) 2016, 2018 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
@@ -10,7 +10,9 @@
*******************************************************************************/
package org.springframework.ide.vscode.commons.java;
import java.io.File;
import java.nio.file.Path;
import java.util.Optional;
import java.util.function.Predicate;
import com.google.common.collect.ImmutableList;
@@ -54,5 +56,9 @@ public interface IClasspath {
* @return classpath resource relative paths
*/
ImmutableList<String> getClasspathResources();
ImmutableList<String> getSourceFolders();
Optional<File> findClasspathResourceContainer(String fqName);
}

View File

@@ -0,0 +1,46 @@
/*******************************************************************************
* Copyright (c) 2018 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springframework.ide.vscode.commons.languageserver.util;
/**
* LSP Client information utilities
*
* @author Alex Boyko
*
*/
public class LspClient {
public enum Client {
UNKNOWN,
VSCODE,
ECLIPSE,
ATOM,
INTELLIJ
}
/**
* Extracts the LSP client from the current environment
* @return current LSP client
*/
public static Client currentClient() {
Client client = Client.UNKNOWN;
String clientStr = System.getProperty("sts.lsp.client");
if (clientStr != null) {
try {
client = Client.valueOf(clientStr.toUpperCase());
} catch (IllegalArgumentException e) {
// ignore
}
}
return client;
}
}

View File

@@ -1,5 +1,5 @@
/*******************************************************************************
* Copyright (c) 2016 Pivotal, Inc.
* Copyright (c) 2016, 2018 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
@@ -293,7 +293,7 @@ public class MavenCore {
public Stream<Path> getJreLibs() throws MavenException {
String s = (String) maven.createExecutionRequest().getSystemProperties().get(JAVA_BOOT_CLASS_PATH);
return Arrays.stream(s.split(File.pathSeparator)).map(File::new).filter(f -> f.canRead()).map(f -> Paths.get(f.toURI()));
return s == null ? Stream.empty() : Arrays.stream(s.split(File.pathSeparator)).map(File::new).filter(f -> f.canRead()).map(f -> Paths.get(f.toURI()));
}
public String getJavaRuntimeVersion() throws MavenException {

View File

@@ -1,5 +1,5 @@
/*******************************************************************************
* Copyright (c) 2016 Pivotal, Inc.
* Copyright (c) 2016, 2018 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
@@ -85,7 +85,7 @@ public class MavenProjectClasspath extends JandexClasspath {
}
public String getName() {
return project == null ? null : project.getName();
return project == null ? null : project.getArtifact().getArtifactId();
}
@Override
@@ -262,4 +262,9 @@ public class MavenProjectClasspath extends JandexClasspath {
return false;
}
@Override
public ImmutableList<String> getSourceFolders() {
return ImmutableList.of(project.getBuild().getSourceDirectory());
}
}

View File

@@ -1,5 +1,5 @@
/*******************************************************************************
* Copyright (c) 2016 Pivotal, Inc.
* Copyright (c) 2016, 2018 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
@@ -10,8 +10,10 @@
*******************************************************************************/
package org.springframework.ide.vscode.commons.maven.java.classpathfile;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@@ -87,4 +89,14 @@ public class FileClasspath implements IClasspath {
return null;
}
@Override
public ImmutableList<String> getSourceFolders() {
return ImmutableList.of();
}
@Override
public Optional<File> findClasspathResourceContainer(String fqName) {
return Optional.empty();
}
}

View File

@@ -1,5 +1,5 @@
/*******************************************************************************
* Copyright (c) 2016-2017 Pivotal, Inc.
* Copyright (c) 2016, 2018 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
@@ -16,10 +16,12 @@ import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@@ -133,4 +135,21 @@ public class JavaIndexTest {
assertEquals(IVoidType.DEFAULT, m.getReturnType());
assertEquals(Collections.singletonList(IPrimitiveType.INT), m.parameters().collect(Collectors.toList()));
}
@Test
public void testFindJarResource() throws Exception {
MavenJavaProject project = mavenProjectsCache.get("gs-rest-service-cors-boot-1.4.1-with-classpath-file");
Optional<File> jar = project.getClasspath().findClasspathResourceContainer("org.springframework.boot.autoconfigure.SpringBootApplication");
assertTrue(jar.isPresent());
assertEquals("spring-boot-autoconfigure-1.4.1.RELEASE.jar", jar.get().getName());
}
@Test
public void testFindJavaResource() throws Exception {
MavenJavaProject project = mavenProjectsCache.get("gs-rest-service-cors-boot-1.4.1-with-classpath-file");
Optional<File> file = project.getClasspath().findClasspathResourceContainer("hello.GreetingController");
assertTrue(file.isPresent());
assertTrue(file.get().exists());
assertEquals(project.getClasspath().getOutputFolder().toString(), file.get().toString());
}
}

View File

@@ -108,6 +108,7 @@ export function activate(options: ActivatorOptions, context: VSCode.ExtensionCon
log('Redirecting server logs to ' + logfile);
const args = [
'-Dserver.port=' + port,
'-Dsts.lsp.client=vscode',
'-Dorg.slf4j.simpleLogger.logFile=' + logfile
];
if (options.classpath) {