-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathCodemodLoaderTest.java
More file actions
550 lines (484 loc) · 18.3 KB
/
CodemodLoaderTest.java
File metadata and controls
550 lines (484 loc) · 18.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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
package io.codemodder;
import static io.codemodder.CodemodLoader.isValidCodemodId;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.jupiter.api.Assertions.assertThrows;
import com.github.javaparser.JavaParser;
import io.codemodder.codetf.*;
import io.codemodder.javaparser.JavaParserFacade;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import org.hamcrest.CoreMatchers;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
final class CodemodLoaderTest {
@Codemod(
id = "test_mod",
importance = Importance.LOW,
reviewGuidance = ReviewGuidance.MERGE_AFTER_CURSORY_REVIEW)
static class InvalidCodemodName extends NoReportChanger {}
@Codemod(
id = "pixee:java/id",
importance = Importance.LOW,
reviewGuidance = ReviewGuidance.MERGE_AFTER_CURSORY_REVIEW)
static class ValidCodemod extends NoReportChanger {}
private static class NoReportChanger implements CodeChanger {
@Override
public String getSummary() {
return "summary";
}
@Override
public String getDescription() {
return "description";
}
@Override
public List<CodeTFReference> getReferences() {
return List.of();
}
@Override
public String getIndividualChangeDescription(Path filePath, CodemodChange change) {
return null;
}
@Override
public boolean supports(final Path file) {
return true;
}
}
@Test
void it_validates_codemod_ids() {
assertThat(isValidCodemodId("pixee:java/id"), CoreMatchers.is(true));
assertThat(isValidCodemodId("pixee:java/id-with-slashes-numbers-34"), CoreMatchers.is(true));
assertThat(isValidCodemodId("some-thing:java/id"), CoreMatchers.is(false));
assertThat(isValidCodemodId("missing:token"), CoreMatchers.is(false));
assertThat(isValidCodemodId("missing:separator/"), CoreMatchers.is(false));
assertThat(isValidCodemodId("vendor:java/java.lang.security.some-vuln"), CoreMatchers.is(true));
}
@Test
void it_blows_up_on_duplicate_codemod_ids(@TempDir Path tmpDir) {
assertThrows(
UnsupportedOperationException.class,
() -> {
createLoader(List.of(ValidCodemod.class, ValidCodemod.class), tmpDir);
});
}
@Codemod(
id = "test:java/changes-file",
reviewGuidance = ReviewGuidance.MERGE_AFTER_CURSORY_REVIEW,
importance = Importance.LOW,
executionPriority = CodemodExecutionPriority.HIGH)
static class ChangesFile extends RawFileChanger {
ChangesFile() {
super(new EmptyReporter());
}
public CodemodFileScanningResult visitFile(final CodemodInvocationContext context)
throws IOException {
Path path = context.path();
String contents = Files.readString(path);
contents += "\nb";
Files.writeString(path, contents);
return CodemodFileScanningResult.none();
}
@Override
public String getSummary() {
return "summary";
}
@Override
public String getDescription() {
return "description";
}
@Override
public List<CodeTFReference> getReferences() {
return List.of();
}
@Override
public String getIndividualChangeDescription(Path filePath, CodemodChange change) {
return null;
}
@Override
public boolean supports(final Path file) {
return true;
}
}
@Codemod(
id = "test:java/changes-file-again",
importance = Importance.LOW,
reviewGuidance = ReviewGuidance.MERGE_AFTER_CURSORY_REVIEW)
static class ChangesFileAgain extends RawFileChanger {
ChangesFileAgain() {
super(new EmptyReporter());
}
public CodemodFileScanningResult visitFile(final CodemodInvocationContext context)
throws IOException {
Path path = context.path();
String contents = Files.readString(path);
contents += "\nc";
Files.writeString(path, contents);
return CodemodFileScanningResult.none();
}
@Override
public String getSummary() {
return "summary";
}
@Override
public String getDescription() {
return "description";
}
@Override
public List<CodeTFReference> getReferences() {
return List.of();
}
@Override
public String getIndividualChangeDescription(Path filePath, CodemodChange change) {
return null;
}
@Override
public boolean supports(Path file) {
return true;
}
}
@Codemod(
id = "test:java/changes-file-yet-again",
reviewGuidance = ReviewGuidance.MERGE_AFTER_CURSORY_REVIEW,
importance = Importance.LOW,
executionPriority = CodemodExecutionPriority.LOW)
static class ChangesFileYetAgain extends RawFileChanger {
ChangesFileYetAgain() {
super(new EmptyReporter());
}
public CodemodFileScanningResult visitFile(final CodemodInvocationContext context)
throws IOException {
Path path = context.path();
String contents = Files.readString(path);
contents += "\nd\n";
Files.writeString(path, contents);
return CodemodFileScanningResult.none();
}
@Override
public String getSummary() {
return "summary";
}
@Override
public String getDescription() {
return "description";
}
@Override
public List<CodeTFReference> getReferences() {
return List.of();
}
@Override
public String getIndividualChangeDescription(Path filePath, CodemodChange change) {
return null;
}
@Override
public boolean supports(Path file) {
return true;
}
}
/** Confirm the codemods respect the order of the regulator. */
@Test
void it_handles_codemod_orders(final @TempDir Path tmpDir) throws IOException {
// create an ordered list of codemods
List<Class<? extends CodeChanger>> codemodTypes =
List.of(
// test:java/changes-file
ChangesFile.class,
// test:java/changes-file-again
ChangesFileAgain.class,
// test:java/changes-file-yet-again
ChangesFileYetAgain.class);
CodemodLoader loader = createLoader(codemodTypes, tmpDir);
List<CodemodIdPair> codemods = loader.getCodemods();
assertThat(codemods.get(0).getId(), equalTo("test:java/changes-file"));
assertThat(codemods.get(1).getId(), equalTo("test:java/changes-file-again"));
assertThat(codemods.get(2).getId(), equalTo("test:java/changes-file-yet-again"));
// now we specify a --codemod-includes order to be in backwards order
CodemodRegulator regulator =
CodemodRegulator.of(
DefaultRuleSetting.DISABLED,
List.of(
"test:java/changes-file-yet-again",
"test:java/changes-file-again",
"test:java/changes-file"));
loader =
new CodemodLoader(
codemodTypes,
regulator,
tmpDir,
List.of("**"),
List.of(),
Files.list(tmpDir).toList(),
Map.of(),
List.of(),
null,
null,
null);
codemods = loader.getCodemods();
assertThat(codemods.get(0).getId(), equalTo("test:java/changes-file-yet-again"));
assertThat(codemods.get(1).getId(), equalTo("test:java/changes-file-again"));
assertThat(codemods.get(2).getId(), equalTo("test:java/changes-file"));
// now do it again, with only the B and C codemods
regulator =
CodemodRegulator.of(
DefaultRuleSetting.ENABLED,
List.of("test:java/changes-file-again", "test:java/changes-file"));
loader =
new CodemodLoader(
codemodTypes,
regulator,
tmpDir,
List.of("**"),
List.of(),
Files.list(tmpDir).toList(),
Map.of(),
List.of(),
null,
null,
null);
codemods = loader.getCodemods();
assertThat(codemods, hasSize(1));
assertThat(codemods.get(0).getId(), equalTo("test:java/changes-file-yet-again"));
}
/**
* We create a file, and then run two codemods on it. The first codemod adds a line, the second
* adds another. This will ensure that the codemods are run in the order they are provided and
* that they both had their effect.
*/
@Test
void it_handles_consecutive_codemod_changes(@TempDir Path tmpDir) throws IOException {
// re-order the codemods in different ways to ensure that the execution priority is honored as
// well
List<List<Class<? extends CodeChanger>>> codemodsInDifferentOrders =
List.of(
// 1, 2, 3
List.of(ChangesFile.class, ChangesFileAgain.class, ChangesFileYetAgain.class),
// 1, 3, 2
List.of(ChangesFile.class, ChangesFileYetAgain.class, ChangesFileAgain.class),
// 2, 1, 3
List.of(ChangesFileAgain.class, ChangesFile.class, ChangesFileYetAgain.class),
// 2, 3, 1
List.of(ChangesFileAgain.class, ChangesFileYetAgain.class, ChangesFile.class),
// 3, 2, 1
List.of(ChangesFileYetAgain.class, ChangesFileAgain.class, ChangesFile.class),
// 3, 1, 2
List.of(ChangesFileYetAgain.class, ChangesFile.class, ChangesFileAgain.class));
for (var codemods : codemodsInDifferentOrders) {
Path file = tmpDir.resolve("file.txt");
Files.writeString(file, "a", StandardCharsets.UTF_8);
CodemodLoader loader = createLoader(codemods, tmpDir);
for (CodemodIdPair codemodIdPair : loader.getCodemods()) {
CodemodExecutor executor =
new DefaultCodemodExecutor(
tmpDir,
IncludesExcludes.any(),
codemodIdPair,
List.of(),
List.of(),
FileCache.createDefault(),
JavaParserFacade.from(JavaParser::new),
EncodingDetector.create(),
-1,
-1,
-1);
executor.execute(List.of(file));
}
String contents = Files.readString(file);
assertThat(contents, equalTo("a\nb\nc\nd\n"));
}
}
@Codemod(
id = "pixee:java/parameterized",
importance = Importance.LOW,
reviewGuidance = ReviewGuidance.MERGE_AFTER_CURSORY_REVIEW)
static class ParameterizedCodemod extends RawFileChanger {
private final Parameter parameter;
@Inject
public ParameterizedCodemod(
@CodemodParameter(
question = "What do you want the number to be?",
name = "my-param-number",
label = "adds a number to the end of a file",
defaultValue = "123",
validationPattern = "\\d+")
final Parameter parameter) {
super(new EmptyReporter());
this.parameter = parameter;
}
@Override
public CodemodFileScanningResult visitFile(final CodemodInvocationContext context)
throws IOException {
Path path = context.path();
List<String> existingLines = Files.readAllLines(path);
List<String> contents = new ArrayList<>(existingLines);
String value = parameter.getValue(path, existingLines.size());
contents.add(value);
Files.write(path, contents, StandardCharsets.UTF_8);
List<CodemodChange> changes =
List.of(CodemodChange.from(existingLines.size(), parameter, value));
return CodemodFileScanningResult.withOnlyChanges(changes);
}
@Override
public String getSummary() {
return "summary";
}
@Override
public String getDescription() {
return "description";
}
@Override
public List<CodeTFReference> getReferences() {
return List.of();
}
@Override
public String getIndividualChangeDescription(Path filePath, CodemodChange change) {
return null;
}
@Override
public boolean supports(final Path file) {
return true;
}
}
@Test
void it_uses_and_reports_parameters(@TempDir final Path tmpDir) throws IOException {
List<Class<? extends CodeChanger>> codemods = List.of(ParameterizedCodemod.class);
// first, we run without any parameters and ensure we get the right stuff
{
CodemodLoader loader = createLoader(codemods, tmpDir);
CodemodIdPair pair = loader.getCodemods().get(0);
ParameterizedCodemod changer = (ParameterizedCodemod) pair.getChanger();
assertThat(changer.parameter.getDefaultValue(), equalTo("123"));
assertThat(changer.parameter.getValue(null, 5), equalTo("123"));
assertThat(changer.parameter.getLabel(), equalTo("adds a number to the end of a file"));
}
// next, we run with a parameter without file info and see that it had the intended effects
{
String paramArg = "codemod=pixee:java/parameterized,name=my-param-number,value=456";
ParameterArgument param = ParameterArgument.fromNameValuePairs(paramArg);
CodemodLoader loader = createLoader(codemods, tmpDir, List.of(param));
CodemodIdPair pair = loader.getCodemods().get(0);
ParameterizedCodemod changer = (ParameterizedCodemod) pair.getChanger();
assertThat(changer.parameter.getDefaultValue(), equalTo("456"));
assertThat(changer.parameter.getValue(null, 5), equalTo("456"));
assertThat(changer.parameter.getLabel(), equalTo("adds a number to the end of a file"));
}
// next, we run with a parameter with file info and see that it had the intended effects
Path bar = Path.of("src/main/java/Bar.java");
Path foo = Path.of("src/main/java/Foo.java");
{
String paramArg =
"codemod=pixee:java/parameterized,name=my-param-number,value=456,file=src/main/java/Foo.java";
ParameterArgument param = ParameterArgument.fromNameValuePairs(paramArg);
CodemodLoader loader = createLoader(codemods, tmpDir, List.of(param));
CodemodIdPair pair = loader.getCodemods().get(0);
ParameterizedCodemod changer = (ParameterizedCodemod) pair.getChanger();
// our parameter is file-scoped, so its not the default value
assertThat(changer.parameter.getDefaultValue(), equalTo("123"));
// for some random file, we should return the original default value
assertThat(changer.parameter.getValue(bar, 5), equalTo("123"));
// for the file we specified, we should return the value we specified
assertThat(changer.parameter.getValue(foo, 5), equalTo("456"));
assertThat(changer.parameter.getLabel(), equalTo("adds a number to the end of a file"));
}
// finally, we run with a parameter with file and line info and see that it had the intended
// effects
{
String paramArg =
"codemod=pixee:java/parameterized,name=my-param-number,value=456,file=src/main/java/Foo.java,line=5";
ParameterArgument param = ParameterArgument.fromNameValuePairs(paramArg);
CodemodLoader loader = createLoader(codemods, tmpDir, List.of(param));
CodemodIdPair pair = loader.getCodemods().get(0);
ParameterizedCodemod changer = (ParameterizedCodemod) pair.getChanger();
// our parameter is file-scoped, so its not the default value
assertThat(changer.parameter.getDefaultValue(), equalTo("123"));
// for some random file, we should return the original default value
assertThat(changer.parameter.getValue(bar, 5), equalTo("123"));
// for the file we specified, we should return the value we specified only on line 5
assertThat(changer.parameter.getValue(foo, 5), equalTo("456"));
assertThat(changer.parameter.getValue(foo, 6), equalTo("123"));
assertThat(changer.parameter.getLabel(), equalTo("adds a number to the end of a file"));
// we run the codemod an make sure the generated codetf has the right parameter
CodemodExecutor executor =
new DefaultCodemodExecutor(
tmpDir,
IncludesExcludes.any(),
pair,
List.of(),
List.of(),
FileCache.createDefault(),
JavaParserFacade.from(JavaParser::new),
EncodingDetector.create(),
-1,
-1,
-1);
Path p = tmpDir.resolve("foo.txt");
Files.writeString(p, "1\n2\n3");
CodeTFResult result = executor.execute(List.of(p));
CodeTFChangesetEntry entry = result.getChangeset().get(0);
assertThat(result.getCodemod(), equalTo("pixee:java/parameterized"));
assertThat(entry.getPath(), equalTo("foo.txt"));
assertThat(entry.getChanges().size(), equalTo(1));
CodeTFChange change = entry.getChanges().get(0);
assertThat(change.getParameters().size(), equalTo(1));
CodeTFParameter parameter = change.getParameters().get(0);
assertThat(parameter.getName(), equalTo("my-param-number"));
assertThat(parameter.getType(), equalTo("string"));
assertThat(parameter.getLabel(), equalTo("adds a number to the end of a file"));
assertThat(parameter.getDefaultValue(), equalTo("123"));
assertThat(parameter.getQuestion(), equalTo("What do you want the number to be?"));
}
}
private CodemodLoader createLoader(final Class<? extends CodeChanger> codemodType, final Path dir)
throws IOException {
return new CodemodLoader(
List.of(codemodType),
CodemodRegulator.of(DefaultRuleSetting.ENABLED, List.of()),
dir,
List.of("**"),
List.of(),
Files.list(dir).toList(),
Map.of(),
List.of(),
null,
null,
null);
}
private CodemodLoader createLoader(
final List<Class<? extends CodeChanger>> codemodTypes, final Path dir) throws IOException {
return new CodemodLoader(
codemodTypes,
CodemodRegulator.of(DefaultRuleSetting.ENABLED, List.of()),
dir,
List.of("**"),
List.of(),
Files.list(dir).toList(),
Map.of(),
List.of(),
null,
null,
null);
}
private CodemodLoader createLoader(
final List<Class<? extends CodeChanger>> codemodTypes,
final Path dir,
final List<ParameterArgument> params)
throws IOException {
return new CodemodLoader(
codemodTypes,
CodemodRegulator.of(DefaultRuleSetting.ENABLED, List.of()),
dir,
List.of("**"),
List.of(),
Files.list(dir).toList(),
Map.of(),
params,
null,
null,
null);
}
}