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);
}
}