Consider CodeBlock's imports when added as an argument

Closes gh-1451
This commit is contained in:
Stephane Nicoll 2023-07-31 15:46:52 +02:00
parent d15bcab31d
commit 4bd5893dd4
2 changed files with 16 additions and 3 deletions

View File

@ -264,7 +264,7 @@ public final class CodeBlock {
private void addArgument(String format, char c, Object arg) {
switch (c) {
case 'L' -> this.args.add(arg);
case 'L' -> this.args.add(arg(arg));
case 'S' -> this.args.add(argToString(arg));
case 'T' -> this.args.add(argToType(arg));
default -> throw new IllegalArgumentException(
@ -272,8 +272,15 @@ public final class CodeBlock {
}
}
private String argToString(Object o) {
return (o != null) ? String.valueOf(o) : null;
private Object arg(Object arg) {
if (arg instanceof CodeBlock code) {
this.imports.addAll(code.getImports());
}
return arg;
}
private String argToString(Object arg) {
return (arg != null) ? String.valueOf(arg) : null;
}
private String argToType(Object arg) {

View File

@ -179,6 +179,12 @@ class CodeBlockTests {
assertThat(code.getImports()).isEmpty();
}
@Test
void codeBlockWithParameterCodeBlockAddsImports() {
CodeBlock code = CodeBlock.of("$L", CodeBlock.of("$T.truncate(myString)", ClassName.of(StringUtils.class)));
assertThat(code.getImports()).containsExactly(StringUtils.class.getName());
}
private String writeJava(CodeBlock code) {
return write(code, CodeBlock.JAVA_FORMATTING_OPTIONS);
}