-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathDefaultCodemodExecutor.java
More file actions
459 lines (412 loc) · 17.3 KB
/
DefaultCodemodExecutor.java
File metadata and controls
459 lines (412 loc) · 17.3 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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
package io.codemodder;
import static java.util.Collections.emptyMap;
import com.github.difflib.DiffUtils;
import com.github.difflib.UnifiedDiffUtils;
import io.codemodder.codetf.*;
import io.codemodder.javaparser.JavaParserChanger;
import io.codemodder.javaparser.JavaParserCodemodRunner;
import io.codemodder.javaparser.JavaParserFacade;
import java.io.IOException;
import java.nio.charset.MalformedInputException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.VisibleForTesting;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
final class DefaultCodemodExecutor implements CodemodExecutor {
private final CodemodIdPair codemod;
private final List<ProjectProvider> projectProviders;
private final List<CodeTFProvider> codetfProviders;
private final JavaParserFacade javaParserFacade;
private final Path projectDir;
private final IncludesExcludes includesExcludes;
private final EncodingDetector encodingDetector;
private final FileCache fileCache;
private final boolean perCodemodIncludesExcludes;
/** The max size of a file we'll scan. If a file is larger than this, we'll skip it. */
private final int maxFileSize;
/**
* The max number of files we'll scan. If there are more than this number of files, we'll skip
* them.
*/
private final int maxFiles;
/** The max number of workers we'll use to scan files. */
private final int maxWorkers;
DefaultCodemodExecutor(
final Path projectDir,
final CodemodIdPair codemod,
final List<ProjectProvider> projectProviders,
final List<CodeTFProvider> codetfProviders,
final FileCache fileCache,
final JavaParserFacade javaParserFacade,
final EncodingDetector encodingDetector,
final int maxFileSize,
final int maxFiles,
final int maxWorkers) {
this.projectDir = Objects.requireNonNull(projectDir);
this.includesExcludes = IncludesExcludes.any();
this.perCodemodIncludesExcludes = true;
this.codemod = Objects.requireNonNull(codemod);
this.codetfProviders = Objects.requireNonNull(codetfProviders);
this.projectProviders = Objects.requireNonNull(projectProviders);
this.javaParserFacade = Objects.requireNonNull(javaParserFacade);
this.fileCache = Objects.requireNonNull(fileCache);
this.encodingDetector = Objects.requireNonNull(encodingDetector);
this.maxFileSize = maxFileSize;
this.maxFiles = maxFiles;
this.maxWorkers = maxWorkers;
}
DefaultCodemodExecutor(
final Path projectDir,
final IncludesExcludes includesExcludes,
final CodemodIdPair codemod,
final List<ProjectProvider> projectProviders,
final List<CodeTFProvider> codetfProviders,
final FileCache fileCache,
final JavaParserFacade javaParserFacade,
final EncodingDetector encodingDetector,
final int maxFileSize,
final int maxFiles,
final int maxWorkers) {
this.projectDir = Objects.requireNonNull(projectDir);
this.includesExcludes = Objects.requireNonNull(includesExcludes);
this.perCodemodIncludesExcludes = false;
this.codemod = Objects.requireNonNull(codemod);
this.codetfProviders = Objects.requireNonNull(codetfProviders);
this.projectProviders = Objects.requireNonNull(projectProviders);
this.javaParserFacade = Objects.requireNonNull(javaParserFacade);
this.fileCache = Objects.requireNonNull(fileCache);
this.encodingDetector = Objects.requireNonNull(encodingDetector);
this.maxFileSize = maxFileSize;
this.maxFiles = maxFiles;
this.maxWorkers = maxWorkers;
}
@Override
public CodeTFResult execute(final List<Path> filePaths) {
Set<Path> unscannableFiles = new ConcurrentSkipListSet<>();
DefaultCodeDirectory codeDirectory = new DefaultCodeDirectory(projectDir);
CodeChanger codeChanger = codemod.getChanger();
/*
* Create the right CodemodRunner based on the type of CodeChanger.
*/
CodemodRunner codemodRunner;
if (codeChanger instanceof JavaParserChanger) {
if (perCodemodIncludesExcludes) {
codemodRunner =
new JavaParserCodemodRunner(
javaParserFacade, (JavaParserChanger) codeChanger, projectDir, encodingDetector);
} else {
codemodRunner =
new JavaParserCodemodRunner(
javaParserFacade,
(JavaParserChanger) codeChanger,
projectDir,
includesExcludes,
encodingDetector);
}
} else if (codeChanger instanceof RawFileChanger) {
if (perCodemodIncludesExcludes) {
codemodRunner = new RawFileCodemodRunner((RawFileChanger) codeChanger, projectDir);
} else {
codemodRunner = new RawFileCodemodRunner((RawFileChanger) codeChanger, includesExcludes);
}
} else {
throw new UnsupportedOperationException(
"unsupported codeChanger type: " + codeChanger.getClass().getName());
}
/*
* Filter the files to those that the CodemodRunner supports.
*/
List<Path> codemodTargetFiles =
filePaths.stream()
.filter(codemodRunner::supports)
.sorted()
.limit(maxFiles != -1 ? maxFiles : Long.MAX_VALUE)
.sorted()
.toList();
/*
* The changeset doesn't need to be thread-safe because it's only added to within a synchronized block.
*/
List<CodeTFChangesetEntry> changeset = new ArrayList<>();
int workers = maxWorkers != -1 ? maxWorkers : 1;
ExecutorService executor = Executors.newFixedThreadPool(workers);
CompletionService<String> service = new ExecutorCompletionService<>(executor);
List<UnfixedFinding> unfixedFindings = new CopyOnWriteArrayList<>();
// for each file, add a task to the completion service
for (Path filePath : codemodTargetFiles) {
executor.submit(
() -> {
// create the context necessary for the codemod to run
LineIncludesExcludes lineIncludesExcludes =
includesExcludes.getIncludesExcludesForFile(filePath.toFile());
try {
if (maxFileSize != -1) {
long size = Files.size(filePath);
if (size > maxFileSize) {
unscannableFiles.add(filePath);
return;
}
}
final String beforeFileContents;
try {
beforeFileContents = fileCache.get(filePath);
} catch (final MalformedInputException e) {
log.warn("file uses unsupported character encoding: {}", filePath);
unscannableFiles.add(filePath);
return;
}
Collection<DependencyGAV> deps =
projectProviders.stream()
.flatMap(
provider -> {
try {
return provider.getAllDependencies(projectDir, filePath).stream();
} catch (Exception e) {
log.error("Problem getting dependencies for file {}", filePath, e);
return Stream.empty();
}
})
.toList();
CodemodInvocationContext context =
new DefaultCodemodInvocationContext(
codeDirectory,
filePath,
beforeFileContents,
codemod.getId(),
lineIncludesExcludes,
deps);
// run the codemod on the file
CodemodFileScanningResult codemodFileScanningResult = codemodRunner.run(context);
final CodeTFAiMetadata codeTFAiMetadata;
if (codemodFileScanningResult instanceof AIMetadataProvider aiMetadataProvider) {
codeTFAiMetadata = aiMetadataProvider.codeTFAiMetadata();
} else {
codeTFAiMetadata = null;
}
List<CodemodChange> codemodChanges = codemodFileScanningResult.changes();
if (!codemodChanges.isEmpty()) {
synchronized (this) {
FilesUpdateResult updateResult =
updateFiles(
codeChanger,
filePath,
beforeFileContents,
codemodChanges,
codeTFAiMetadata);
unscannableFiles.addAll(updateResult.filesFailedToChange());
changeset.addAll(updateResult.changeset());
}
}
unfixedFindings.addAll(codemodFileScanningResult.unfixedFindings());
} catch (Exception e) {
unscannableFiles.add(filePath);
log.error("Problem scanning file {}", filePath, e);
}
});
}
executor.shutdown();
try {
boolean success = executor.awaitTermination(10, TimeUnit.MINUTES);
log.trace("Success running codemod: {}", success);
while (!executor.isTerminated()) {
final Future<String> future = service.poll(5, TimeUnit.SECONDS);
if (future != null) {
log.trace("Finished: {}", future.get());
}
}
} catch (Exception e) {
log.error("Problem waiting for scanning threads to exit", e);
}
DetectionTool detectionTool = null;
if (codeChanger instanceof FixOnlyCodeChanger fixOnlyCodeChanger) {
detectionTool = new DetectionTool(fixOnlyCodeChanger.vendorName());
}
CodeTFResult result =
new CodeTFResult(
codemod.getId(),
codeChanger.getSummary(),
codeChanger.getDescription(),
detectionTool,
// TODO augment CodeTF with failure metadata
null,
unscannableFiles.stream()
.map(file -> getRelativePath(projectDir, file))
.collect(Collectors.toSet()),
codeChanger.getReferences(),
emptyMap(),
changeset,
unfixedFindings);
for (CodeTFProvider provider : codetfProviders) {
result = provider.onResultCreated(result);
}
return result;
}
/**
* This file method does the hard work of updating files, based on a list of codemod changes
* reported to have occurred.
*/
private FilesUpdateResult updateFiles(
final CodeChanger codeChanger,
final Path filePath,
final String beforeFileContents,
final List<CodemodChange> codemodChanges,
final CodeTFAiMetadata codeTFAiMetadata)
throws IOException {
List<Path> filesFailedToChange = List.of();
// update the dependencies in the manifest file if needed
// We suppress warnings because we conditionally remove items from this list instance
@SuppressWarnings("java:S6204")
List<DependencyGAV> dependencies =
codemodChanges.stream()
.map(CodemodChange::getDependenciesNeeded)
.flatMap(Collection::stream)
.distinct()
.collect(Collectors.toList());
List<CodeTFPackageAction> pkgActions;
List<CodeTFChangesetEntry> dependencyChangesetEntries = Collections.emptyList();
if (!dependencies.isEmpty()) {
CodemodPackageUpdateResult packageAddResult = addPackages(filePath, dependencies);
filesFailedToChange = new ArrayList<>(packageAddResult.filesFailedToChange());
pkgActions = packageAddResult.packageActions();
dependencyChangesetEntries = packageAddResult.manifestChanges();
} else {
pkgActions = Collections.emptyList();
}
// record the change for the file
List<CodeTFChange> changes =
codemodChanges.stream()
.map(
change ->
translateCodemodChangetoCodeTFChange(codeChanger, filePath, change, pkgActions))
.toList();
// make sure we add the file's entry first, then the dependency entries, so the causality
// is clear
List<String> beforeFile = beforeFileContents.lines().toList();
String afterContents = Files.readString(filePath);
List<String> afterFile = afterContents.lines().toList();
List<String> patchDiff =
UnifiedDiffUtils.generateUnifiedDiff(
filePath.getFileName().toString(),
filePath.getFileName().toString(),
beforeFile,
DiffUtils.diff(beforeFile, afterFile),
3);
String diff = String.join("\n", patchDiff);
// create a changeset for this file change + its downstream dependency changes
List<CodeTFChangesetEntry> changeset = new ArrayList<>();
Strategy codeChangeStrategy = codeTFAiMetadata != null ? Strategy.AI : Strategy.DETERMINISTIC;
changeset.add(
new CodeTFChangesetEntry(
getRelativePath(projectDir, filePath),
diff,
changes,
codeTFAiMetadata,
codeChangeStrategy,
false,
List.of(),
null));
changeset.addAll(dependencyChangesetEntries);
// update the cache
fileCache.overrideEntry(filePath, afterContents);
dependencyChangesetEntries.forEach(
entry -> fileCache.removeEntry(projectDir.resolve(entry.getPath())));
return new FilesUpdateResult(changeset, filesFailedToChange);
}
@NotNull
private CodeTFChange translateCodemodChangetoCodeTFChange(
final CodeChanger codeChanger,
final Path filePath,
final CodemodChange codemodChange,
final List<CodeTFPackageAction> pkgActions) {
Optional<String> customizedChangeDescription = codemodChange.getDescription();
String changeDescription =
customizedChangeDescription.orElse(
codeChanger.getIndividualChangeDescription(filePath, codemodChange));
CodeTFChange change =
new CodeTFChange(
codemodChange.lineNumber(),
emptyMap(),
changeDescription,
CodeTFDiffSide.LEFT,
pkgActions,
codemodChange.getParameters(),
codemodChange.getFixedFindings());
for (CodeTFProvider provider : codetfProviders) {
change = provider.onChangeCreated(filePath, codemod.getId(), change);
}
return change;
}
/**
* After updating the files, this method asks the project providers to apply any corrective
* changers to the project as a whole regarding the dependencies. This is useful for things like
* adding a dependency to the project's pom.xml file. Eventually we want support other operations
* besides "add" (like, obviously, "remove")
*/
private CodemodPackageUpdateResult addPackages(
final Path file, final List<DependencyGAV> dependencies) throws IOException {
List<CodeTFPackageAction> pkgActions = new ArrayList<>();
Set<Path> unscannableFiles = new HashSet<>();
List<DependencyGAV> skippedDependencies = new ArrayList<>();
List<CodeTFChangesetEntry> pkgChanges = new ArrayList<>();
for (ProjectProvider projectProvider : projectProviders) {
DependencyUpdateResult result =
projectProvider.updateDependencies(projectDir, file, dependencies);
unscannableFiles.addAll(result.erroredFiles().stream().map(Path::toAbsolutePath).toList());
pkgChanges.addAll(result.packageChanges());
for (DependencyGAV dependency : result.injectedPackages()) {
String packageUrl = toPackageUrl(dependency);
pkgActions.add(
new CodeTFPackageAction(
CodeTFPackageAction.CodeTFPackageActionType.ADD,
CodeTFPackageAction.CodeTFPackageActionResult.COMPLETED,
packageUrl));
}
for (DependencyGAV dependency : result.skippedPackages()) {
String packageUrl = toPackageUrl(dependency);
skippedDependencies.add(dependency);
pkgActions.add(
new CodeTFPackageAction(
CodeTFPackageAction.CodeTFPackageActionType.ADD,
CodeTFPackageAction.CodeTFPackageActionResult.SKIPPED,
packageUrl));
}
dependencies.removeAll(new HashSet<>(result.injectedPackages()));
}
dependencies.stream()
.filter(d -> !skippedDependencies.contains(d))
.forEach(
dep ->
pkgActions.add(
new CodeTFPackageAction(
CodeTFPackageAction.CodeTFPackageActionType.ADD,
CodeTFPackageAction.CodeTFPackageActionResult.FAILED,
toPackageUrl(dep))));
return CodemodPackageUpdateResult.from(pkgActions, pkgChanges, unscannableFiles);
}
@VisibleForTesting
static String toPackageUrl(DependencyGAV dependency) {
return "pkg:maven/"
+ dependency.group()
+ "/"
+ dependency.artifact()
+ "@"
+ dependency.version();
}
/** Return the relative path name (e.g., src/test/foo) of a file within the project dir. */
private String getRelativePath(final Path projectDir, final Path filePath) {
String path = projectDir.relativize(filePath).toString();
if (path.startsWith("/")) {
path = path.substring(1);
}
return path;
}
/** Describes the results of updating files after a codemod execution. */
private record FilesUpdateResult(
List<CodeTFChangesetEntry> changeset, List<Path> filesFailedToChange) {}
private static final Logger log = LoggerFactory.getLogger(DefaultCodemodExecutor.class);
}