Repository navigation
Expand file tree
/
Copy pathInferConfig.java
More file actions
352 lines (291 loc) · 12.1 KB
/
Copy pathInferConfig.java
File metadata and controls
352 lines (291 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
package org.javacs;
import com.google.common.base.Joiner;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.*;
import java.time.Instant;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
class InferConfig {
/** Root of the workspace that is currently open in VSCode */
private final Path workspaceRoot;
/** User-specified external dependencies, configured with java.externalDependencies */
private final Collection<Artifact> externalDependencies;
/** User-specified class path, configured with java.classPath */
private final List<Path> classPath;
/** Location of the maven repository, usually ~/.m2 */
private final Path mavenHome;
/** Location of the gradle cache, usually ~/.gradle */
private final Path gradleHome;
InferConfig(
Path workspaceRoot,
Collection<Artifact> externalDependencies,
List<Path> classPath,
Path mavenHome,
Path gradleHome) {
this.workspaceRoot = workspaceRoot;
this.externalDependencies = externalDependencies;
this.classPath = classPath;
this.mavenHome = mavenHome;
this.gradleHome = gradleHome;
}
// TODO move to JavaLanguageServer
static Stream<Path> allJavaFiles(Path dir) {
PathMatcher match = FileSystems.getDefault().getPathMatcher("glob:*.java");
try {
// TODO instead of looking at EVERY file, once you see a few files with the same source directory,
// ignore all subsequent files in the directory
return Files.walk(dir).filter(java -> match.matches(java.getFileName()));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
static Instant buildFilesModified(Path workspaceRoot) {
Instant workspaceModified = fileModified(workspaceRoot.resolve("WORKSPACE")),
pomModified = fileModified(workspaceRoot.resolve("pom.xml"));
return maxTime(workspaceModified, pomModified);
}
private static Instant fileModified(Path file) {
if (Files.exists(file)) {
try {
return Files.getLastModifiedTime(file).toInstant();
} catch (IOException e) {
throw new RuntimeException(e);
}
} else return Instant.EPOCH;
}
private static Instant maxTime(Instant... of) {
Instant result = Instant.EPOCH;
for (Instant each : of) {
if (each.isAfter(result)) result = each;
}
return result;
}
/**
* Find .jar files for external dependencies, for examples settings `externalDependencies` in
* local maven / gradle repository.
*/
Set<Path> buildClassPath() {
// Settings `externalDependencies`
Stream<Path> result =
allExternalDependencies()
.stream()
.flatMap(artifact -> stream(findAnyJar(artifact, false)));
// Settings `classPath`
Stream<Path> classPathJars =
classPath.stream().flatMap(jar -> stream(findWorkspaceJar(jar)));
result = Stream.concat(result, classPathJars);
// Bazel
if (Files.exists(workspaceRoot.resolve("WORKSPACE"))) {
Path bazelGenFiles = workspaceRoot.resolve("bazel-genfiles");
if (Files.exists(bazelGenFiles) && Files.isSymbolicLink(bazelGenFiles)) {
result = Stream.concat(result, bazelJars(bazelGenFiles));
}
}
return result.collect(Collectors.toSet());
}
private Optional<Path> findWorkspaceJar(Path jar) {
jar = workspaceRoot.resolve(jar);
if (Files.exists(jar)) return Optional.of(jar);
else {
LOG.warning("No such file " + jar);
return Optional.empty();
}
}
/**
* Find directories that contain java .class files in the workspace, for example files generated
* by maven in target/classes
*/
Set<Path> workspaceClassPath() {
// Bazel
if (Files.exists(workspaceRoot.resolve("WORKSPACE"))) {
Path bazelBin = workspaceRoot.resolve("bazel-bin");
if (Files.exists(bazelBin) && Files.isSymbolicLink(bazelBin)) {
return bazelOutputDirectories(bazelBin).collect(Collectors.toSet());
}
}
// Maven
try {
return Files.walk(workspaceRoot)
.flatMap(this::outputDirectory)
.collect(Collectors.toSet());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/** Recognize build root files like pom.xml and return compiler output directories */
private Stream<Path> outputDirectory(Path file) {
if (file.getFileName().toString().equals("pom.xml")) {
Path target = file.resolveSibling("target");
if (Files.exists(target) && Files.isDirectory(target)) {
return Stream.of(target.resolve("classes"), target.resolve("test-classes"));
}
}
// TODO gradle
return Stream.empty();
}
/**
* Search bazel-bin for per-module output directories matching the pattern:
*
* <p>bazel-bin/path/to/module/_javac/rule/lib*_classes
*/
private Stream<Path> bazelOutputDirectories(Path bazelBin) {
try {
Path target = Files.readSymbolicLink(bazelBin);
PathMatcher match =
FileSystems.getDefault().getPathMatcher("glob:**/_javac/*/lib*_classes");
return Files.walk(target).filter(match::matches).filter(Files::isDirectory);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/** Search bazel-genfiles for jars */
private Stream<Path> bazelJars(Path bazelGenFiles) {
try {
Path target = Files.readSymbolicLink(bazelGenFiles);
return Files.walk(target)
.filter(file -> file.getFileName().toString().endsWith(".jar"));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/** Find source .jar files for `externalDependencies` in local maven / gradle repository. */
Set<Path> buildDocPath() {
return allExternalDependencies()
.stream()
.flatMap(artifact -> stream(findAnyJar(artifact, true)))
.collect(Collectors.toSet());
}
private Optional<Path> findAnyJar(Artifact artifact, boolean source) {
Optional<Path> maven = findMavenJar(artifact, source);
if (maven.isPresent()) return maven;
else return findGradleJar(artifact, source);
}
private Optional<Path> findMavenJar(Artifact artifact, boolean source) {
Path jar =
mavenHome
.resolve("repository")
.resolve(artifact.groupId.replace('.', File.separatorChar))
.resolve(artifact.artifactId)
.resolve(artifact.version)
.resolve(fileName(artifact, source));
if (Files.exists(jar)) return Optional.of(jar);
else return Optional.empty();
}
private Optional<Path> findGradleJar(Artifact artifact, boolean source) {
// Search for caches/modules-*/files-*/groupId/artifactId/version/*/artifactId-version[-sources].jar
Path base = gradleHome.resolve("caches");
String pattern =
"glob:"
+ Joiner.on(File.separatorChar)
.join(
base.toString(),
"modules-*",
"files-*",
artifact.groupId,
artifact.artifactId,
artifact.version,
"*",
fileName(artifact, source));
PathMatcher match = FileSystems.getDefault().getPathMatcher(pattern);
try {
return Files.walk(base, 7).filter(match::matches).findFirst();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private String fileName(Artifact artifact, boolean source) {
return artifact.artifactId + '-' + artifact.version + (source ? "-sources" : "") + ".jar";
}
private boolean isSourceJar(Path jar) {
return jar.getFileName().toString().endsWith("-sources.jar");
}
private int compareMavenVersions(Path leftJar, Path rightJar) {
return compareVersions(mavenVersion(leftJar), mavenVersion(rightJar));
}
private String[] mavenVersion(Path jar) {
return jar.getParent().getFileName().toString().split("\\.");
}
private int compareVersions(String[] left, String[] right) {
int n = Math.min(left.length, right.length);
for (int i = 0; i < n; i++) {
int each = left[i].compareTo(right[i]);
if (each != 0) return each;
}
return 0;
}
private static <T> Stream<T> stream(Optional<T> option) {
return option.map(Stream::of).orElseGet(Stream::empty);
}
static List<Artifact> dependencyList(Path pomXml) {
Objects.requireNonNull(pomXml, "pom.xml path is null");
try {
// Tell maven to output deps to a temporary file
Path outputFile = Files.createTempFile("deps", ".txt");
String cmd =
String.format(
"%s dependency:list -DincludeScope=test -DoutputFile=%s",
getMvnCommand(), outputFile);
File workingDirectory = pomXml.toAbsolutePath().getParent().toFile();
int result = Runtime.getRuntime().exec(cmd, null, workingDirectory).waitFor();
if (result != 0) throw new RuntimeException("`" + cmd + "` returned " + result);
return readDependencyList(outputFile);
} catch (InterruptedException | IOException e) {
throw new RuntimeException(e);
}
}
private static List<Artifact> readDependencyList(Path outputFile) {
Pattern artifact = Pattern.compile(".*:.*:.*:.*:.*");
try (InputStream in = Files.newInputStream(outputFile)) {
return new BufferedReader(new InputStreamReader(in))
.lines()
.map(String::trim)
.filter(line -> artifact.matcher(line).matches())
.map(Artifact::parse)
.collect(Collectors.toList());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Get external dependencies from this.externalDependencies if available, or try to infer them.
*/
private Collection<Artifact> allExternalDependencies() {
if (!externalDependencies.isEmpty()) return externalDependencies;
// If user does not specify java.externalDependencies, look for pom.xml
Path pomXml = workspaceRoot.resolve("pom.xml");
if (Files.exists(pomXml)) return dependencyList(pomXml);
return Collections.emptyList();
}
static String getMvnCommand() {
String mvnCommand = "mvn";
if (File.separatorChar == '\\') {
mvnCommand = findExecutableOnPath("mvn.cmd");
if (mvnCommand == null) {
mvnCommand = findExecutableOnPath("mvn.bat");
}
}
return mvnCommand;
}
private static String findExecutableOnPath(String name) {
for (String dirname : System.getenv("PATH").split(File.pathSeparator)) {
File file = new File(dirname, name);
if (file.isFile() && file.canExecute()) {
return file.getAbsolutePath();
}
}
return null;
}
private static final Logger LOG = Logger.getLogger("main");
}