This is an automated email from the ASF dual-hosted git repository. jdaugherty pushed a commit to branch feature/scaffold-generated-actions in repository https://gitbox.apache.org/repos/asf/grails-intellij-plugin.git
commit 40175406628cde803f97f47be3ebf1bc63fb1e46 Author: James Daugherty <[email protected]> AuthorDate: Mon Oct 12 15:18:14 2026 +0100 Model @Scaffold: inherited superclass and generated-member hints @Scaffold generates no methods. Grails' ScaffoldingControllerInjector and ScaffoldingServiceInjector replace the class's superclass at compile time (Object becomes RestfulController<Domain> or GormService<Domain>, or the base named in the annotation) and add a no-arg constructor. The IDE knew nothing of this, so a scaffolded controller showed no actions, a hand written `def show()` carried no "overrides" marker, and nothing told the user what the annotation had done. ScaffoldTransformationSupport sets the same superclass on the PSI through the Groovy astTransformationSupport extension point, reading the annotation the way the injectors do: @Scaffold(Domain), @Scaffold(Base<Domain>), @Scaffold(value = Base, domain = Domain), the `domain` attribute alone, and the deprecated `static scaffold = Domain`. A class with its own superclass is left alone, as the compiler rejects it. Completion, navigation, the override gutter marker and the structure view's inherited members then come from the platform. ScaffoldInlayHintsProvider shows what was added: `extends RestfulController<Quest>` after the class name and the inherited actions at the end of the header line, each a link to the inherited method. An action the class declares drops out of that list. Compiled Groovy bases carry trait methods and property accessors as public methods, so the listing skips @Generated members, accessors and `$` names. --- .../scaffold/ScaffoldInlayHintsProvider.java | 119 +++++++++ .../scaffold/ScaffoldTransformationSupport.java | 60 +++++ .../plugin/feature/scaffold/Scaffolding.java | 226 +++++++++++++++++ plugin/src/main/resources/META-INF/plugin.xml | 13 + .../resources/messages/GrailsBundle.properties | 5 + .../scaffold/ScaffoldInlayHintsProviderTest.java | 212 ++++++++++++++++ .../ScaffoldTransformationSupportTest.java | 280 +++++++++++++++++++++ .../plugin/feature/scaffold/ScaffoldingStubs.java | 85 +++++++ 8 files changed, 1000 insertions(+) diff --git a/plugin/src/main/java/org/apache/grails/intellij/plugin/feature/scaffold/ScaffoldInlayHintsProvider.java b/plugin/src/main/java/org/apache/grails/intellij/plugin/feature/scaffold/ScaffoldInlayHintsProvider.java new file mode 100644 index 0000000..a28178f --- /dev/null +++ b/plugin/src/main/java/org/apache/grails/intellij/plugin/feature/scaffold/ScaffoldInlayHintsProvider.java @@ -0,0 +1,119 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.grails.intellij.plugin.feature.scaffold; + +import com.intellij.codeInsight.hints.declarative.EndOfLinePosition; +import com.intellij.codeInsight.hints.declarative.HintColorKind; +import com.intellij.codeInsight.hints.declarative.HintFontSize; +import com.intellij.codeInsight.hints.declarative.HintFormat; +import com.intellij.codeInsight.hints.declarative.HintMarginPadding; +import com.intellij.codeInsight.hints.declarative.InlayActionData; +import com.intellij.codeInsight.hints.declarative.InlayHintsCollector; +import com.intellij.codeInsight.hints.declarative.InlayHintsProvider; +import com.intellij.codeInsight.hints.declarative.InlayTreeSink; +import com.intellij.codeInsight.hints.declarative.InlineInlayPosition; +import com.intellij.codeInsight.hints.declarative.PresentationTreeBuilder; +import com.intellij.codeInsight.hints.declarative.PsiPointerInlayActionNavigationHandler; +import com.intellij.codeInsight.hints.declarative.PsiPointerInlayActionPayload; +import com.intellij.codeInsight.hints.declarative.SharedBypassCollector; +import com.intellij.openapi.editor.Document; +import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.project.DumbService; +import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiFile; +import com.intellij.psi.PsiMethod; +import com.intellij.psi.SmartPointerManager; +import kotlin.Unit; +import org.apache.grails.intellij.plugin.GrailsBundle; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.plugins.groovy.lang.psi.GroovyFile; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition; + +import java.util.List; + +/** + * Shows what {@code @Scaffold} adds to a controller or service, since none of it is in the source: + * {@code extends RestfulController<Quest>} after the class name, and the inherited actions at the end + * of the header line, each a link to the method it inherits. An action the class declares itself is + * left out of the list - it is visible in the source, with the platform's "overrides" marker in the + * gutter. + * + * @see Scaffolding#inheritedMembers + */ +public final class ScaffoldInlayHintsProvider implements InlayHintsProvider { + + public static final String PROVIDER_ID = "grails.scaffold.members"; + + private static final HintFormat FORMAT = + new HintFormat(HintColorKind.Default, HintFontSize.ABitSmallerThanInEditor, HintMarginPadding.OnlyPadding); + + @Override + public @Nullable InlayHintsCollector createCollector(@NotNull PsiFile file, @NotNull Editor editor) { + if (!(file instanceof GroovyFile) || DumbService.isDumb(file.getProject())) return null; + return new Collector(); + } + + private static final class Collector implements SharedBypassCollector { + + @Override + public void collectFromElement(@NotNull PsiElement element, @NotNull InlayTreeSink sink) { + if (!(element instanceof GrTypeDefinition clazz)) return; + Scaffolding.ScaffoldInfo info = Scaffolding.resolve(clazz); + if (info == null) return; + + PsiElement nameIdentifier = clazz.getNameIdentifierGroovy(); + String baseText = info.baseType().getPresentableText(); + InlayActionData baseLink = navigateTo(info.baseClass()); + + sink.addPresentation(new InlineInlayPosition(nameIdentifier.getTextRange().getEndOffset(), true, 0), + null, + GrailsBundle.message("inlay.scaffold.base.tooltip"), + FORMAT, + builder -> { + builder.text("extends ", null); + builder.text(baseText, baseLink); + return Unit.INSTANCE; + }); + + List<PsiMethod> members = Scaffolding.inheritedMembers(clazz, info); + if (members.isEmpty()) return; + Document document = clazz.getContainingFile().getViewProvider().getDocument(); + if (document == null) return; + int line = document.getLineNumber(nameIdentifier.getTextRange().getEndOffset()); + + sink.addPresentation(new EndOfLinePosition(line), + null, + GrailsBundle.message("inlay.scaffold.members.tooltip", baseText), + FORMAT, + builder -> { + for (int i = 0; i < members.size(); i++) { + PsiMethod member = members.get(i); + builder.text(i == 0 ? member.getName() : ", " + member.getName(), navigateTo(member)); + } + return Unit.INSTANCE; + }); + } + + private static @NotNull InlayActionData navigateTo(@NotNull PsiElement target) { + return new InlayActionData(new PsiPointerInlayActionPayload(SmartPointerManager.createPointer(target)), + PsiPointerInlayActionNavigationHandler.HANDLER_ID); + } + } +} diff --git a/plugin/src/main/java/org/apache/grails/intellij/plugin/feature/scaffold/ScaffoldTransformationSupport.java b/plugin/src/main/java/org/apache/grails/intellij/plugin/feature/scaffold/ScaffoldTransformationSupport.java new file mode 100644 index 0000000..a691269 --- /dev/null +++ b/plugin/src/main/java/org/apache/grails/intellij/plugin/feature/scaffold/ScaffoldTransformationSupport.java @@ -0,0 +1,60 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.grails.intellij.plugin.feature.scaffold; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierFlags; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition; +import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightMethodBuilder; +import org.jetbrains.plugins.groovy.transformations.AstTransformationSupport; +import org.jetbrains.plugins.groovy.transformations.TransformationContext; + +/** + * Applies {@code @Scaffold} to the PSI the way Grails applies it to the AST: the class extends + * {@code RestfulController<Domain>} / {@code GormService<Domain>} (or the base the annotation names) + * and gets the no-arg constructor the transform adds. + * + * <p>Everything else follows from the superclass: the scaffolded actions resolve and complete, a + * method declared in the class gets the platform's "overrides" gutter marker, the structure view lists + * the inherited actions, and "Go To View" and GSP action references see them as the controller's actions. + * + * @see Scaffolding + */ +public final class ScaffoldTransformationSupport implements AstTransformationSupport { + + @Override + public void applyTransformation(@NotNull TransformationContext context) { + GrTypeDefinition clazz = context.getCodeClass(); + Scaffolding.ScaffoldInfo info = Scaffolding.resolve(clazz); + if (info == null) return; + + context.setSuperType(info.baseType()); + + // ResourceTransform.addConstructor(): Foo() { super(Domain, readOnly) } + String name = clazz.getName(); + if (name != null) { + GrLightMethodBuilder constructor = new GrLightMethodBuilder(context.getManager(), name); + constructor.setConstructor(true); + constructor.addModifier(GrModifierFlags.PUBLIC_MASK); + constructor.setContainingClass(clazz); + constructor.setNavigationElement(info.anchor()); + context.addMethod(constructor); + } + } +} diff --git a/plugin/src/main/java/org/apache/grails/intellij/plugin/feature/scaffold/Scaffolding.java b/plugin/src/main/java/org/apache/grails/intellij/plugin/feature/scaffold/Scaffolding.java new file mode 100644 index 0000000..9a160e3 --- /dev/null +++ b/plugin/src/main/java/org/apache/grails/intellij/plugin/feature/scaffold/Scaffolding.java @@ -0,0 +1,226 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.grails.intellij.plugin.feature.scaffold; + +import com.intellij.psi.CommonClassNames; +import com.intellij.psi.JavaPsiFacade; +import com.intellij.psi.PsiAnnotation; +import com.intellij.psi.PsiAnnotationMemberValue; +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiClassType; +import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiElementFactory; +import com.intellij.psi.PsiField; +import com.intellij.psi.PsiMethod; +import com.intellij.psi.PsiModifier; +import com.intellij.psi.PsiModifierList; +import com.intellij.psi.PsiType; +import com.intellij.psi.util.PropertyUtilBase; +import org.apache.grails.intellij.plugin.util.GrailsArtifact; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrExtendsClause; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod; +import org.jetbrains.plugins.groovy.lang.psi.impl.GrAnnotationUtil; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrAccessorMethod; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * What {@code @Scaffold} does to a Grails controller or service, resolved from the source the IDE sees. + * + * <p>The annotation generates no methods. Grails' {@code ScaffoldingControllerInjector} and + * {@code ScaffoldingServiceInjector} replace the class's superclass at compile time - {@code Object} + * becomes {@code RestfulController<Domain>} or {@code GormService<Domain>}, or the class named in the + * annotation - and add a constructor that hands the domain class to it. The CRUD actions are therefore + * inherited, not generated, and the IDE models them the same way: {@link ScaffoldTransformationSupport} + * sets that superclass on the PSI, so completion, navigation, the "overrides" gutter marker and the + * structure view's inherited members all come from the platform, and {@link ScaffoldInlayHintsProvider} + * shows what the annotation added. + * + * <p>The annotation is read the way the injectors read it: + * <ul> + * <li>{@code @Scaffold(Domain)} - domain {@code Domain}, default base for the artefact type;</li> + * <li>{@code @Scaffold(Base<Domain>)} - base {@code Base}, domain from the type argument;</li> + * <li>{@code @Scaffold(value = Base, domain = Domain)} - the documented explicit form;</li> + * <li>{@code @Scaffold(domain = Domain)} - default base.</li> + * </ul> + * A controller may also use the deprecated {@code static scaffold = Domain} property. A class that + * declares its own superclass is left alone: the compiler rejects it, so there is nothing to model. + */ +public final class Scaffolding { + + public static final String SCAFFOLD_ANNOTATION = "grails.plugin.scaffolding.annotation.Scaffold"; + public static final String RESTFUL_CONTROLLER = "grails.rest.RestfulController"; + public static final String GORM_SERVICE = "grails.plugin.scaffolding.GormService"; + static final String LEGACY_SCAFFOLD_PROPERTY = "scaffold"; + + private static final String GROOVY_GENERATED = "groovy.transform.Generated"; + private static final String GROOVY_INTERNAL = "groovy.transform.Internal"; + + private Scaffolding() { + } + + /** + * The superclass {@code @Scaffold} gives a class. + * + * @param baseType the base parameterised by the domain when it takes exactly one type parameter, + * otherwise the raw base + * @param domainClass {@code null} when the annotation names no domain, which the compiler reports + * @param anchor the annotation or the legacy {@code scaffold} property, for navigation + */ + public record ScaffoldInfo(@NotNull GrailsArtifact artefact, + @NotNull PsiClass baseClass, + @NotNull PsiClassType baseType, + @Nullable PsiClass domainClass, + @NotNull PsiElement anchor) { + } + + public static @Nullable ScaffoldInfo resolve(@Nullable PsiClass psiClass) { + if (!(psiClass instanceof GrTypeDefinition clazz)) return null; + if (clazz.isInterface() || clazz.isEnum() || clazz.isAnnotationType() || clazz.isTrait()) return null; + + GrailsArtifact artefact = GrailsArtifact.getType(clazz); + String defaultBase; + if (artefact == GrailsArtifact.CONTROLLER) { + defaultBase = RESTFUL_CONTROLLER; + } + else if (artefact == GrailsArtifact.SERVICE) { + defaultBase = GORM_SERVICE; + } + else { + return null; + } + + // "Scaffolded controllers cannot extend other classes" - a compile error, so there is nothing to model. + GrExtendsClause extendsClause = clazz.getExtendsClause(); + if (extendsClause != null && extendsClause.getReferenceElementsGroovy().length > 0) return null; + + PsiClass base = null; + PsiClass domain = null; + PsiElement anchor; + + GrModifierList modifierList = clazz.getModifierList(); + PsiAnnotation annotation = modifierList == null ? null : modifierList.findAnnotation(SCAFFOLD_ANNOTATION); + if (annotation != null) { + anchor = annotation; + ClassRef value = classRef(annotation.findDeclaredAttributeValue("value")); + ClassRef explicitDomain = classRef(annotation.findDeclaredAttributeValue("domain")); + if (explicitDomain != null) domain = explicitDomain.psiClass(); + if (value != null) { + if (value.typeArgument() != null) { + base = value.psiClass(); + if (domain == null) domain = value.typeArgument(); + } + else if (domain != null) { + base = value.psiClass(); + } + else { + domain = value.psiClass(); + } + } + } + else if (artefact == GrailsArtifact.CONTROLLER) { + PsiField field = clazz.findCodeFieldByName(LEGACY_SCAFFOLD_PROPERTY, false); + if (!(field instanceof GrField scaffoldProperty) || !scaffoldProperty.hasModifierProperty(PsiModifier.STATIC)) return null; + ClassRef ref = classRef(scaffoldProperty.getInitializerGroovy()); + if (ref == null) return null; + domain = ref.psiClass(); + anchor = scaffoldProperty; + } + else { + return null; + } + + if (base == null) { + base = JavaPsiFacade.getInstance(clazz.getProject()).findClass(defaultBase, clazz.getResolveScope()); + if (base == null) return null; // scaffolding is not on the classpath + } + + PsiElementFactory factory = JavaPsiFacade.getElementFactory(clazz.getProject()); + PsiClassType baseType = domain != null && base.getTypeParameters().length == 1 + ? factory.createType(base, factory.createType(domain)) + : factory.createType(base); + return new ScaffoldInfo(artefact, base, baseType, domain, anchor); + } + + /** + * The public methods a scaffolded class inherits from its scaffold base and does not declare itself: + * the API {@code @Scaffold} adds. Walks the base's superclass chain but not its traits or interfaces, + * and skips what a compiled Groovy class carries besides the actions - property accessors, + * trait-implemented methods and Groovy's own plumbing, all of which it marks {@code @Generated}. + */ + public static @NotNull List<PsiMethod> inheritedMembers(@NotNull GrTypeDefinition clazz, @NotNull ScaffoldInfo info) { + Set<String> declared = new HashSet<>(); + for (GrMethod method : clazz.getCodeMethods()) declared.add(method.getName()); + for (GrField field : clazz.getCodeFields()) declared.add(field.getName()); // closure actions: def index = { } + + List<PsiMethod> result = new ArrayList<>(); + Set<String> seen = new HashSet<>(declared); + for (PsiClass base = info.baseClass(); + base != null && !CommonClassNames.JAVA_LANG_OBJECT.equals(base.getQualifiedName()); + base = base.getSuperClass()) { + for (PsiMethod method : base.getMethods()) { + if (isScaffoldedMember(method) && seen.add(method.getName())) { + result.add(method); + } + } + } + return result; + } + + private static boolean isScaffoldedMember(@NotNull PsiMethod method) { + if (method.isConstructor()) return false; + if (!method.hasModifierProperty(PsiModifier.PUBLIC) || method.hasModifierProperty(PsiModifier.STATIC)) return false; + if (method.getName().contains("$")) return false; // trait bridges and other Groovy internals + if (method instanceof GrAccessorMethod || PropertyUtilBase.isSimplePropertyAccessor(method)) return false; + PsiModifierList modifiers = method.getModifierList(); + return !modifiers.hasAnnotation(GROOVY_GENERATED) && !modifiers.hasAnnotation(GROOVY_INTERNAL); + } + + /** A class named in an annotation attribute or a property initializer, with its first type argument. */ + private record ClassRef(@NotNull PsiClass psiClass, @Nullable PsiClass typeArgument) { + } + + private static @Nullable ClassRef classRef(@Nullable PsiElement value) { + if (!(value instanceof PsiAnnotationMemberValue memberValue)) return null; + PsiClass psiClass = GrAnnotationUtil.getPsiClass(memberValue); + if (psiClass == null || isVoid(psiClass)) return null; + + PsiClass typeArgument = null; + if (value instanceof GrReferenceExpression reference) { + PsiType[] typeArguments = reference.getTypeArguments(); + if (typeArguments.length > 0 && typeArguments[0] instanceof PsiClassType classType) { + typeArgument = classType.resolve(); + } + } + return new ClassRef(psiClass, typeArgument); + } + + private static boolean isVoid(@NotNull PsiClass psiClass) { + return CommonClassNames.JAVA_LANG_VOID.equals(psiClass.getQualifiedName()); + } +} diff --git a/plugin/src/main/resources/META-INF/plugin.xml b/plugin/src/main/resources/META-INF/plugin.xml index a6cc3af..81a067e 100644 --- a/plugin/src/main/resources/META-INF/plugin.xml +++ b/plugin/src/main/resources/META-INF/plugin.xml @@ -185,11 +185,24 @@ <astTransformationSupport implementation="org.apache.grails.intellij.plugin.feature.linkable.LinkableTransformationSupport"/> <namedArgumentProvider implementation="org.apache.grails.intellij.plugin.feature.linkable.LinkableNamedArgumentsProvider"/> + <!--grails.plugin.scaffolding.annotation.Scaffold: the class extends RestfulController<Domain> / GormService<Domain>--> + <astTransformationSupport implementation="org.apache.grails.intellij.plugin.feature.scaffold.ScaffoldTransformationSupport"/> + <delegatesToProvider implementation="org.apache.grails.intellij.plugin.references.domain.detachedCriteria.DetachedCriteriaDelegatesToProvider"/> </extensions> <extensions defaultExtensionNs="com.intellij"> + <!--What @Scaffold adds to a controller or service, since none of it is in the source--> + <codeInsight.declarativeInlayProvider language="Groovy" + implementationClass="org.apache.grails.intellij.plugin.feature.scaffold.ScaffoldInlayHintsProvider" + isEnabledByDefault="true" + group="OTHER_GROUP" + providerId="grails.scaffold.members" + bundle="messages.GrailsBundle" + nameKey="inlay.scaffold.name" + descriptionKey="inlay.scaffold.description"/> + <registryKey key="grails.advanced.mode" defaultValue="false" description="Use to enable advanced mode for the domain class relations editor."/> <registryKey key="grails.simple.debug" defaultValue="false" diff --git a/plugin/src/main/resources/messages/GrailsBundle.properties b/plugin/src/main/resources/messages/GrailsBundle.properties index f82e575..0c5da78 100644 --- a/plugin/src/main/resources/messages/GrailsBundle.properties +++ b/plugin/src/main/resources/messages/GrailsBundle.properties @@ -341,3 +341,8 @@ gradle.sync.blocked.action.reload=Reload Gradle Project gradle.sync.blocked.action.show.build=Show Build Output gradle.sync.blocked.notification.title=Grails support unavailable gradle.sync.blocked.notification.content=The Gradle import of ''{0}'' failed. Its Grails view, GSP support and console stay off until the build imports successfully. + +inlay.scaffold.name=Scaffolded members +inlay.scaffold.description=Shows the superclass that @Scaffold gives a Grails controller or service, and the actions it inherits from it. +inlay.scaffold.base.tooltip=Superclass set by @Scaffold at compile time +inlay.scaffold.members.tooltip=Inherited from {0}. Declare a method with the same name to override it. diff --git a/plugin/src/test/java/org/apache/grails/intellij/plugin/feature/scaffold/ScaffoldInlayHintsProviderTest.java b/plugin/src/test/java/org/apache/grails/intellij/plugin/feature/scaffold/ScaffoldInlayHintsProviderTest.java new file mode 100644 index 0000000..701790c --- /dev/null +++ b/plugin/src/test/java/org/apache/grails/intellij/plugin/feature/scaffold/ScaffoldInlayHintsProviderTest.java @@ -0,0 +1,212 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.grails.intellij.plugin.feature.scaffold; + +import com.intellij.codeInsight.hints.declarative.CollapseState; +import com.intellij.codeInsight.hints.declarative.CollapsiblePresentationTreeBuilder; +import com.intellij.codeInsight.hints.declarative.EndOfLinePosition; +import com.intellij.codeInsight.hints.declarative.HintFormat; +import com.intellij.codeInsight.hints.declarative.InlayActionData; +import com.intellij.codeInsight.hints.declarative.InlayHintsCollector; +import com.intellij.codeInsight.hints.declarative.InlayPayload; +import com.intellij.codeInsight.hints.declarative.InlayPosition; +import com.intellij.codeInsight.hints.declarative.InlayTreeSink; +import com.intellij.codeInsight.hints.declarative.InlineInlayPosition; +import com.intellij.codeInsight.hints.declarative.PresentationTreeBuilder; +import com.intellij.codeInsight.hints.declarative.PsiPointerInlayActionPayload; +import com.intellij.codeInsight.hints.declarative.SharedBypassCollector; +import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiFile; +import com.intellij.psi.PsiMethod; +import kotlin.Unit; +import kotlin.jvm.functions.Function0; +import kotlin.jvm.functions.Function1; +import org.apache.grails.intellij.lib.testFramework.GrailsTestCase; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.plugins.groovy.lang.psi.GroovyFile; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition; + +import java.util.ArrayList; +import java.util.List; + +/** + * The hints that show what {@code @Scaffold} added: the superclass after the class name, and the + * inherited actions at the end of the header line, minus the ones the class declares itself. + */ +public class ScaffoldInlayHintsProviderTest extends GrailsTestCase { + + /** One entry per hint: its text, position and the elements its links navigate to. */ + private record Hint(@NotNull String text, @NotNull InlayPosition position, @NotNull List<PsiElement> targets) { + } + + private static final class RecordingSink implements InlayTreeSink { + final List<Hint> hints = new ArrayList<>(); + + @Override + public void addPresentation(@NotNull InlayPosition position, + @Nullable List<InlayPayload> payloads, + @Nullable String tooltip, + @NotNull HintFormat hintFormat, + @NotNull Function1<? super PresentationTreeBuilder, Unit> builder) { + StringBuilder text = new StringBuilder(); + List<PsiElement> targets = new ArrayList<>(); + builder.invoke(new PresentationTreeBuilder() { + @Override + public void list(@NotNull Function1<? super PresentationTreeBuilder, Unit> block) { + block.invoke(this); + } + + @Override + public void collapsibleList(@NotNull CollapseState state, + @NotNull Function1<? super CollapsiblePresentationTreeBuilder, Unit> expanded, + @NotNull Function1<? super CollapsiblePresentationTreeBuilder, Unit> collapsed) { + throw new UnsupportedOperationException(); + } + + @Override + public void text(@NotNull String fragment, @Nullable InlayActionData action) { + text.append(fragment); + if (action != null && action.getPayload() instanceof PsiPointerInlayActionPayload pointer) { + targets.add(pointer.getPointer().getElement()); + } + } + + @Override + public void clickHandlerScope(@NotNull InlayActionData action, @NotNull Function1<? super PresentationTreeBuilder, Unit> block) { + block.invoke(this); + } + }); + hints.add(new Hint(text.toString(), position, targets)); + } + + @Override + public void whenOptionEnabled(@NotNull String option, @NotNull Function0<Unit> block) { + block.invoke(); + } + } + + private @NotNull List<Hint> hintsFor(@NotNull PsiFile file) { + myFixture.configureFromExistingVirtualFile(file.getVirtualFile()); + InlayHintsCollector collector = new ScaffoldInlayHintsProvider().createCollector(myFixture.getFile(), myFixture.getEditor()); + assertNotNull(collector); + RecordingSink sink = new RecordingSink(); + GrTypeDefinition clazz = ((GroovyFile)myFixture.getFile()).getTypeDefinitions()[0]; + ((SharedBypassCollector)collector).collectFromElement(clazz, sink); + return sink.hints; + } + + private void addScaffolding() { + ScaffoldingStubs.addTo(myFixture); + addDomain(""" + +package com.kousenit + +class Quest { + String name +} +"""); + } + + public void testControllerShowsBaseAndInheritedActions() { + addScaffolding(); + PsiFile controller = addController(""" + +package com.kousenit + +import grails.plugin.scaffolding.annotation.Scaffold + +@Scaffold(Quest) +class QuestController { + def show() {} +} +"""); + + List<Hint> hints = hintsFor(controller); + assertSize(2, hints); + + Hint base = hints.get(0); + assertEquals("extends RestfulController<Quest>", base.text()); + GrTypeDefinition clazz = ((GroovyFile)myFixture.getFile()).getTypeDefinitions()[0]; + assertEquals(clazz.getNameIdentifierGroovy().getTextRange().getEndOffset(), ((InlineInlayPosition)base.position()).getOffset()); + assertEquals("grails.rest.RestfulController", ((com.intellij.psi.PsiClass)base.targets().get(0)).getQualifiedName()); + + Hint members = hints.get(1); + // show is declared in the class (and overrides); getResource, render and the static getter are not actions + assertEquals("index, create, save, edit, patch, update, delete", members.text()); + assertEquals(myFixture.getEditor().getDocument().getLineNumber(clazz.getNameIdentifierGroovy().getTextOffset()), + ((EndOfLinePosition)members.position()).getLine()); + assertSize(7, members.targets()); + PsiMethod index = (PsiMethod)members.targets().get(0); + assertEquals("index", index.getName()); + assertEquals("grails.rest.RestfulController", index.getContainingClass().getQualifiedName()); + } + + /** A base that extends another scaffold base contributes the whole chain, once per name. */ + public void testBaseChainIsWalked() { + addScaffolding(); + PsiFile controller = addController(""" + +package com.kousenit + +import grails.plugin.scaffolding.RestfulServiceController +import grails.plugin.scaffolding.annotation.Scaffold + +@Scaffold(RestfulServiceController<Quest>) +class QuestController { +} +"""); + + List<Hint> hints = hintsFor(controller); + assertEquals("extends RestfulServiceController<Quest>", hints.get(0).text()); + assertEquals("index, show, create, save, edit, patch, update, delete", hints.get(1).text()); + } + + public void testServiceShowsGormServiceMembers() { + addScaffolding(); + PsiFile service = addService(""" + +package com.kousenit + +import grails.plugin.scaffolding.annotation.Scaffold + +@Scaffold(Quest) +class CastleService { +} +"""); + + List<Hint> hints = hintsFor(service); + assertEquals("extends GormService<Quest>", hints.get(0).text()); + assertEquals("get, list, count, delete, save", hints.get(1).text()); // isReadOnly is a property accessor + } + + public void testPlainControllerHasNoHints() { + addScaffolding(); + PsiFile controller = addController(""" + +package com.kousenit + +class QuestController { + def index() {} +} +"""); + + assertEmpty(hintsFor(controller)); + } +} diff --git a/plugin/src/test/java/org/apache/grails/intellij/plugin/feature/scaffold/ScaffoldTransformationSupportTest.java b/plugin/src/test/java/org/apache/grails/intellij/plugin/feature/scaffold/ScaffoldTransformationSupportTest.java new file mode 100644 index 0000000..5d58702 --- /dev/null +++ b/plugin/src/test/java/org/apache/grails/intellij/plugin/feature/scaffold/ScaffoldTransformationSupportTest.java @@ -0,0 +1,280 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.grails.intellij.plugin.feature.scaffold; + +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiClassType; +import com.intellij.psi.PsiFile; +import com.intellij.psi.PsiMethod; +import org.apache.grails.intellij.lib.testFramework.GrailsTestCase; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.plugins.groovy.lang.psi.GroovyFile; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition; + +/** + * {@code @Scaffold} replaces a controller's or service's superclass at compile time. The PSI must show + * the same superclass, or the scaffolded actions neither resolve nor complete, a {@code def show()} in + * the class carries no "overrides" marker, and nothing tells the user what the annotation did. + */ +public class ScaffoldTransformationSupportTest extends GrailsTestCase { + + private static final String QUEST = """ + +package com.kousenit + +class Quest { + String name +} +"""; + + private void addScaffolding() { + ScaffoldingStubs.addTo(myFixture); + addDomain(QUEST); + } + + private static @NotNull GrTypeDefinition classOf(@NotNull PsiFile file) { + return ((GroovyFile)file).getTypeDefinitions()[0]; + } + + private static @Nullable String superType(@NotNull GrTypeDefinition clazz) { + PsiClassType[] types = clazz.getExtendsListTypes(true); + return types.length == 0 ? null : types[0].getCanonicalText(); + } + + public void testDomainOnlyControllerExtendsRestfulController() { + addScaffolding(); + GrTypeDefinition controller = classOf(addController(""" + +package com.kousenit + +import grails.plugin.scaffolding.annotation.Scaffold + +@Scaffold(Quest) +class QuestController { +} +""")); + + assertEquals("grails.rest.RestfulController<com.kousenit.Quest>", superType(controller)); + PsiClass superClass = controller.getSuperClass(); + assertNotNull(superClass); + assertEquals("grails.rest.RestfulController", superClass.getQualifiedName()); + } + + /** {@code generate-all}'s own form: the base with the domain as its type argument. */ + public void testParameterisedBaseInValue() { + addScaffolding(); + GrTypeDefinition controller = classOf(addController(""" + +package com.kousenit + +import grails.plugin.scaffolding.RestfulServiceController +import grails.plugin.scaffolding.annotation.Scaffold + +@Scaffold(RestfulServiceController<Quest>) +class QuestController { +} +""")); + + assertEquals("grails.plugin.scaffolding.RestfulServiceController<com.kousenit.Quest>", superType(controller)); + } + + public void testExplicitBaseAndDomain() { + addScaffolding(); + GrTypeDefinition controller = classOf(addController(""" + +package com.kousenit + +import grails.plugin.scaffolding.RestfulServiceController +import grails.plugin.scaffolding.annotation.Scaffold + +@Scaffold(value = RestfulServiceController, domain = Quest) +class QuestController { +} +""")); + + assertEquals("grails.plugin.scaffolding.RestfulServiceController<com.kousenit.Quest>", superType(controller)); + } + + public void testDomainClassLiteral() { + addScaffolding(); + GrTypeDefinition controller = classOf(addController(""" + +package com.kousenit + +import grails.plugin.scaffolding.annotation.Scaffold + +@Scaffold(domain = Quest.class) +class QuestController { +} +""")); + + assertEquals("grails.rest.RestfulController<com.kousenit.Quest>", superType(controller)); + } + + public void testServiceExtendsGormService() { + addScaffolding(); + GrTypeDefinition service = classOf(addService(""" + +package com.kousenit + +import grails.plugin.scaffolding.annotation.Scaffold + +@Scaffold(Quest) +class CastleService { +} +""")); + + assertEquals("grails.plugin.scaffolding.GormService<com.kousenit.Quest>", superType(service)); + assertSize(1, service.findMethodsByName("save", true)); + } + + /** The deprecated form the controller injector still accepts and warns about. */ + public void testLegacyStaticScaffoldProperty() { + addScaffolding(); + GrTypeDefinition controller = classOf(addController(""" + +package com.kousenit + +class QuestController { + static scaffold = Quest +} +""")); + + assertEquals("grails.rest.RestfulController<com.kousenit.Quest>", superType(controller)); + } + + /** The actions are inherited: they resolve, and declaring one overrides it (what the gutter marker reads). */ + public void testActionsAreInheritedAndOverridable() { + addScaffolding(); + GrTypeDefinition controller = classOf(addController(""" + +package com.kousenit + +import grails.plugin.scaffolding.annotation.Scaffold + +@Scaffold(Quest) +class QuestController { + def show() { + respond Quest.get(params.id) + } +} +""")); + + PsiMethod[] index = controller.findMethodsByName("index", true); + assertSize(1, index); + assertEquals("grails.rest.RestfulController", index[0].getContainingClass().getQualifiedName()); + assertSize(1, controller.findMethodsByName("queryForResource", true)); + + PsiMethod show = controller.findCodeMethodsByName("show", false)[0]; + PsiMethod[] overridden = show.findSuperMethods(); + assertSize(1, overridden); + assertEquals("grails.rest.RestfulController", overridden[0].getContainingClass().getQualifiedName()); + } + + /** ResourceTransform.addConstructor(): the generated no-arg constructor that hands the domain to the base. */ + public void testGeneratedConstructorNavigatesToTheAnnotation() { + addScaffolding(); + GrTypeDefinition controller = classOf(addController(""" + +package com.kousenit + +import grails.plugin.scaffolding.annotation.Scaffold + +@Scaffold(Quest) +class QuestController { +} +""")); + + PsiMethod[] constructors = controller.getConstructors(); + assertSize(1, constructors); + assertEmpty(constructors[0].getParameterList().getParameters()); + assertEquals("@Scaffold(Quest)", constructors[0].getNavigationElement().getText()); + } + + /** "Scaffolded controllers cannot extend other classes" is a compile error, so the declared superclass stays. */ + public void testDeclaredSuperclassIsKept() { + addScaffolding(); + myFixture.addClass("package com.kousenit; public class Base {}"); + GrTypeDefinition controller = classOf(addController(""" + +package com.kousenit + +import grails.plugin.scaffolding.annotation.Scaffold + +@Scaffold(Quest) +class QuestController extends Base { +} +""")); + + assertEquals("com.kousenit.Base", superType(controller)); + assertNull(Scaffolding.resolve(controller)); + } + + /** The injectors only run on controllers and services. */ + public void testClassOutsideArtefactDirectoriesIsUntouched() { + addScaffolding(); + GrTypeDefinition helper = classOf(myFixture.addFileToProject("src/main/groovy/com/kousenit/QuestHelper.groovy", """ + +package com.kousenit + +import grails.plugin.scaffolding.annotation.Scaffold + +@Scaffold(Quest) +class QuestHelper { +} +""")); + + assertNull(superType(helper)); + assertNull(Scaffolding.resolve(helper)); + } + + /** Without grails-scaffolding on the classpath there is no base to extend, and nothing to do. */ + public void testWithoutScaffoldingLibrary() { + addDomain(QUEST); + GrTypeDefinition controller = classOf(addController(""" + +package com.kousenit + +import grails.plugin.scaffolding.annotation.Scaffold + +@Scaffold(Quest) +class QuestController { +} +""")); + + assertNull(superType(controller)); + assertEmpty(controller.findMethodsByName("index", true)); + } + + public void testPlainControllerIsUntouched() { + addScaffolding(); + GrTypeDefinition controller = classOf(addController(""" + +package com.kousenit + +class QuestController { + def index() {} +} +""")); + + assertNull(superType(controller)); + assertEmpty(controller.getConstructors()); + } +} diff --git a/plugin/src/test/java/org/apache/grails/intellij/plugin/feature/scaffold/ScaffoldingStubs.java b/plugin/src/test/java/org/apache/grails/intellij/plugin/feature/scaffold/ScaffoldingStubs.java new file mode 100644 index 0000000..ea85774 --- /dev/null +++ b/plugin/src/test/java/org/apache/grails/intellij/plugin/feature/scaffold/ScaffoldingStubs.java @@ -0,0 +1,85 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.grails.intellij.plugin.feature.scaffold; + +import com.intellij.testFramework.fixtures.JavaCodeInsightTestFixture; +import org.jetbrains.annotations.NotNull; + +/** + * The slice of grails-scaffolding and grails-rest the tests need: the annotation and the two scaffold + * bases, with the extras a compiled Groovy class carries - a property accessor and a {@code @Generated} + * trait method - so the member listing can be seen to skip them. + */ +final class ScaffoldingStubs { + + private ScaffoldingStubs() { + } + + static void addTo(@NotNull JavaCodeInsightTestFixture fixture) { + fixture.addClass(""" + package groovy.transform; + public @interface Generated {} + """); + fixture.addClass(""" + package grails.plugin.scaffolding.annotation; + public @interface Scaffold { + Class<?> value() default Void.class; + Class<?> domain() default Void.class; + boolean readOnly() default false; + } + """); + fixture.addClass(""" + package grails.rest; + public class RestfulController<T> { + public RestfulController(Class<T> resource) {} + public RestfulController(Class<T> resource, boolean readOnly) {} + public Class<T> getResource() { return null; } + @groovy.transform.Generated public void render(Object o) {} + public Object index(Integer max) { return null; } + public Object show() { return null; } + public Object create() { return null; } + public Object save() { return null; } + public Object edit() { return null; } + public Object patch() { return null; } + public Object update() { return null; } + public Object delete() { return null; } + protected T queryForResource(java.io.Serializable id) { return null; } + public static Object getStaticApplicationContext() { return null; } + } + """); + fixture.addClass(""" + package grails.plugin.scaffolding; + public class RestfulServiceController<T> extends grails.rest.RestfulController<T> { + public RestfulServiceController(Class<T> resource, boolean readOnly) { super(resource, readOnly); } + } + """); + fixture.addClass(""" + package grails.plugin.scaffolding; + public class GormService<T> { + public GormService(Class<T> resource, boolean readOnly) {} + public boolean isReadOnly() { return false; } + public T get(java.io.Serializable id) { return null; } + public java.util.List<T> list(java.util.Map args) { return null; } + public Long count(java.util.Map args) { return null; } + public void delete(java.io.Serializable id) {} + public T save(T instance) { return null; } + } + """); + } +}
