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 78eca5b3aada50877bdb2fe02939ddb5d3b3e237 Author: James Daugherty <[email protected]> AuthorDate: Mon Oct 12 15:56:54 2026 +0100 Model @Scaffold: inherited superclass, in-body method hints, Structure view @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 methods as greyed lines above the class's closing brace, indented like its own members, with the base's type parameter replaced by the domain. Above each method a comment names the annotation responsible, as written in the file (`// @Scaffold(Quest) - inherited from RestfulController<Quest>`), and links back to it; a blank line separates the groups. A method the class declares drops out, leaving the platform's override marker. Compiled Groovy bases carry trait methods and property accessors as public methods, so the listing skips @Generated members, accessors and `$` names. ScaffoldStructureViewExtension lists the same methods under the class node in the Structure view, greyed and located in the base, without "Show Inherited"; with that toggle on the platform lists them itself, so the extension adds nothing then. --- .../scaffold/ScaffoldInlayHintsProvider.java | 156 ++++++++++++ .../scaffold/ScaffoldStructureViewExtension.java | 122 +++++++++ .../scaffold/ScaffoldTransformationSupport.java | 60 +++++ .../plugin/feature/scaffold/Scaffolding.java | 249 ++++++++++++++++++ plugin/src/main/resources/META-INF/plugin.xml | 14 ++ .../resources/messages/GrailsBundle.properties | 7 + .../scaffold/ScaffoldInlayHintsProviderTest.java | 258 +++++++++++++++++++ .../ScaffoldStructureViewExtensionTest.java | 121 +++++++++ .../ScaffoldTransformationSupportTest.java | 280 +++++++++++++++++++++ .../plugin/feature/scaffold/ScaffoldingStubs.java | 85 +++++++ 10 files changed, 1352 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..b0bc7fe --- /dev/null +++ b/plugin/src/main/java/org/apache/grails/intellij/plugin/feature/scaffold/ScaffoldInlayHintsProvider.java @@ -0,0 +1,156 @@ +/* + * 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.application.options.CodeStyle; +import com.intellij.codeInsight.hints.declarative.AboveLineIndentedPosition; +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.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 com.intellij.util.text.CharArrayUtil; +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 org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinitionBody; + +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 methods as greyed + * lines at the bottom of the class body - {@code def index(Integer max)}, {@code def show()}, ... - + * each a link to the method it inherits, under a comment that names the annotation responsible and + * links back to it, with a blank line between methods. A method the class declares itself is left + * out: it is in the source, with the platform's "overrides" marker in the gutter. + * + * @see Scaffolding#inheritedMembers + * @see ScaffoldStructureViewExtension + */ +public final class ScaffoldInlayHintsProvider implements InlayHintsProvider { + + public static final String PROVIDER_ID = "grails.scaffold.members"; + + private static final HintFormat FORMAT = + new HintFormat(HintColorKind.TextWithoutBackground, HintFontSize.AsInEditor, 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(); + 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, navigateTo(info.baseClass())); + return Unit.INSTANCE; + }); + + GrTypeDefinitionBody body = clazz.getBody(); + PsiElement rBrace = body == null ? null : body.getRBrace(); + if (rBrace == null) return; + List<PsiMethod> members = Scaffolding.inheritedMembers(clazz, info); + if (members.isEmpty()) return; + + // Above the closing brace, so the inherited methods follow the class's own, as in the hierarchy. + // A block hint takes the indent of its anchor line - the brace's - so one level is added to + // line the methods up with the class's own members. + int anchor = rBrace.getTextRange().getStartOffset(); + String indent = indentUnit(clazz.getContainingFile()); + String tooltip = GrailsBundle.message("inlay.scaffold.members.tooltip", baseText); + // A comment above each method names the annotation that put it there and links back to it. + String comment = indent + "// " + GrailsBundle.message("inlay.scaffold.members.comment", + info.anchor().getText(), baseText); + String commentTooltip = GrailsBundle.message("inlay.scaffold.members.comment.tooltip"); + InlayActionData annotationLink = navigateTo(info.anchor()); + for (int i = 0; i < members.size(); i++) { + PsiMethod member = members.get(i); + String signature = indent + Scaffolding.signature(member, info); + InlayActionData link = navigateTo(member); + // Higher vertical priority sits closer to the anchor line. Per method: a blank line, the + // comment, the method - so each group reads like a method in the source. + sink.addPresentation(new AboveLineIndentedPosition(anchor, 3 * i, 0), null, null, FORMAT, builder -> { + builder.text(" ", null); + return Unit.INSTANCE; + }); + sink.addPresentation(new AboveLineIndentedPosition(anchor, 3 * i + 1, 0), null, commentTooltip, FORMAT, builder -> { + builder.text(comment, annotationLink); + return Unit.INSTANCE; + }); + sink.addPresentation(new AboveLineIndentedPosition(anchor, 3 * i + 2, 0), null, tooltip, FORMAT, builder -> { + builder.text(signature, link); + return Unit.INSTANCE; + }); + } + } + + private static @NotNull String indentUnit(@NotNull PsiFile file) { + Document document = file.getViewProvider().getDocument(); + if (document != null) { + // Prefer what the file already does: the indent of its first indented line. + CharSequence text = document.getCharsSequence(); + for (int line = 0; line < document.getLineCount(); line++) { + int start = document.getLineStartOffset(line); + int textStart = CharArrayUtil.shiftForward(text, start, " \t"); + if (textStart > start && textStart < document.getLineEndOffset(line)) { + return text.subSequence(start, textStart).toString(); + } + } + } + return CodeStyle.getIndentOptions(file).USE_TAB_CHARACTER ? "\t" : " ".repeat(CodeStyle.getIndentOptions(file).INDENT_SIZE); + } + + 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/ScaffoldStructureViewExtension.java b/plugin/src/main/java/org/apache/grails/intellij/plugin/feature/scaffold/ScaffoldStructureViewExtension.java new file mode 100644 index 0000000..85631b7 --- /dev/null +++ b/plugin/src/main/java/org/apache/grails/intellij/plugin/feature/scaffold/ScaffoldStructureViewExtension.java @@ -0,0 +1,122 @@ +/* + * 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.icons.AllIcons; +import com.intellij.ide.projectView.PresentationData; +import com.intellij.ide.structureView.StructureViewExtension; +import com.intellij.ide.structureView.StructureViewFactoryEx; +import com.intellij.ide.structureView.StructureViewTreeElement; +import com.intellij.ide.util.InheritedMembersNodeProvider; +import com.intellij.ide.util.treeView.smartTree.TreeElement; +import com.intellij.navigation.ItemPresentation; +import com.intellij.openapi.editor.Editor; +import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiMethod; +import com.intellij.ui.SimpleTextAttributes; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition; + +import java.util.List; + +/** + * Lists the methods {@code @Scaffold} gives a controller or service under its node in the Structure + * view, greyed and located in the base class, without the user having to turn on "Show Inherited". + * When that toggle is on the platform already lists them (the superclass is set by + * {@link ScaffoldTransformationSupport}), so this adds nothing then. + */ +public final class ScaffoldStructureViewExtension implements StructureViewExtension { + + @Override + public Class<? extends PsiElement> getType() { + return GrTypeDefinition.class; + } + + @Override + public StructureViewTreeElement[] getChildren(PsiElement parent) { + if (!(parent instanceof GrTypeDefinition clazz)) return StructureViewTreeElement.EMPTY_ARRAY; + if (StructureViewFactoryEx.getInstanceEx(clazz.getProject()).isActionActive(InheritedMembersNodeProvider.ID)) { + return StructureViewTreeElement.EMPTY_ARRAY; + } + Scaffolding.ScaffoldInfo info = Scaffolding.resolve(clazz); + if (info == null) return StructureViewTreeElement.EMPTY_ARRAY; + + List<PsiMethod> members = Scaffolding.inheritedMembers(clazz, info); + StructureViewTreeElement[] result = new StructureViewTreeElement[members.size()]; + for (int i = 0; i < result.length; i++) { + result[i] = new ScaffoldedMethodElement(members.get(i), info); + } + return result; + } + + @Override + public @Nullable Object getCurrentEditorElement(Editor editor, PsiElement parent) { + return null; + } + + /** A scaffolded method: shown greyed, located in the base that declares it, navigating there. */ + static final class ScaffoldedMethodElement implements StructureViewTreeElement { + private final PsiMethod myMethod; + private final Scaffolding.ScaffoldInfo myInfo; + + ScaffoldedMethodElement(@NotNull PsiMethod method, @NotNull Scaffolding.ScaffoldInfo info) { + myMethod = method; + myInfo = info; + } + + @Override + public PsiMethod getValue() { + return myMethod; + } + + @Override + public @NotNull ItemPresentation getPresentation() { + PresentationData presentation = new PresentationData(); + presentation.addText(Scaffolding.signature(myMethod, myInfo), SimpleTextAttributes.GRAYED_ATTRIBUTES); + presentation.setPresentableText(Scaffolding.signature(myMethod, myInfo)); + presentation.setIcon(AllIcons.Nodes.Method); + PsiElement containingClass = myMethod.getContainingClass(); + if (containingClass instanceof com.intellij.psi.PsiClass psiClass) { + presentation.setLocationString(psiClass.getName()); + } + return presentation; + } + + @Override + public TreeElement @NotNull [] getChildren() { + return TreeElement.EMPTY_ARRAY; + } + + @Override + public void navigate(boolean requestFocus) { + myMethod.navigate(requestFocus); + } + + @Override + public boolean canNavigate() { + return myMethod.canNavigate(); + } + + @Override + public boolean canNavigateToSource() { + return myMethod.canNavigateToSource(); + } + } +} 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..95d99c3 --- /dev/null +++ b/plugin/src/main/java/org/apache/grails/intellij/plugin/feature/scaffold/Scaffolding.java @@ -0,0 +1,249 @@ +/* + * 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.PsiSubstitutor; +import com.intellij.psi.util.PropertyUtilBase; +import com.intellij.psi.util.PsiFormatUtil; +import com.intellij.psi.util.PsiFormatUtilBase; +import com.intellij.psi.util.TypeConversionUtil; +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; + } + + /** + * The method as the scaffolded class sees it, Groovy style: {@code def index(Integer max)}, + * {@code Quest get(Serializable id)} - the base's type parameter already replaced by the domain. + */ + public static @NotNull String signature(@NotNull PsiMethod method, @NotNull ScaffoldInfo info) { + PsiClass declaring = method.getContainingClass(); + PsiSubstitutor substitutor = declaring == null + ? PsiSubstitutor.EMPTY + : TypeConversionUtil.getSuperClassSubstitutor(declaring, info.baseType()); + PsiType returnType = substitutor.substitute(method.getReturnType()); + String prefix = returnType == null || returnType.equalsToText(CommonClassNames.JAVA_LANG_OBJECT) + ? "def" + : returnType.getPresentableText(); + String parameters = PsiFormatUtil.formatMethod(method, substitutor, + PsiFormatUtilBase.SHOW_NAME | PsiFormatUtilBase.SHOW_PARAMETERS, + PsiFormatUtilBase.SHOW_TYPE | PsiFormatUtilBase.SHOW_NAME); + return prefix + " " + parameters; + } + + 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..3c6e605 100644 --- a/plugin/src/main/resources/META-INF/plugin.xml +++ b/plugin/src/main/resources/META-INF/plugin.xml @@ -185,11 +185,25 @@ <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"/> + <lang.structureViewExtension implementation="org.apache.grails.intellij.plugin.feature.scaffold.ScaffoldStructureViewExtension"/> + <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..30ac9e8 100644 --- a/plugin/src/main/resources/messages/GrailsBundle.properties +++ b/plugin/src/main/resources/messages/GrailsBundle.properties @@ -341,3 +341,10 @@ 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 methods it inherits from it as greyed lines at the end of the class. +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. +inlay.scaffold.members.comment={0} - inherited from {1} +inlay.scaffold.members.comment.tooltip=Go to the annotation that scaffolds this class 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..a177d75 --- /dev/null +++ b/plugin/src/test/java/org/apache/grails/intellij/plugin/feature/scaffold/ScaffoldInlayHintsProviderTest.java @@ -0,0 +1,258 @@ +/* + * 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.AboveLineIndentedPosition; +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 +} +"""); + } + + /** The body hints come in threes per method - blank line, comment, method - after the inline "extends" hint. */ + private static @NotNull List<String> bodyLines(@NotNull List<Hint> hints) { + return every(hints, 3); + } + + private static @NotNull List<String> commentLines(@NotNull List<Hint> hints) { + return every(hints, 2); + } + + private static @NotNull List<String> blankLines(@NotNull List<Hint> hints) { + return every(hints, 1); + } + + private static @NotNull List<String> every(@NotNull List<Hint> hints, int first) { + List<String> lines = new ArrayList<>(); + for (int i = first; i < hints.size(); i += 3) lines.add(hints.get(i).text().strip()); + return lines; + } + + 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); + GrTypeDefinition clazz = ((GroovyFile)myFixture.getFile()).getTypeDefinitions()[0]; + + Hint base = hints.get(0); + assertEquals(" extends RestfulController<Quest>", base.text()); + assertEquals(clazz.getNameIdentifierGroovy().getTextRange().getEndOffset(), ((InlineInlayPosition)base.position()).getOffset()); + assertEquals("grails.rest.RestfulController", ((com.intellij.psi.PsiClass)base.targets().get(0)).getQualifiedName()); + + // show is declared in the class (and overrides); getResource, render and the static getter are not actions + assertEquals(List.of("def index(Integer max)", "def create()", "def save()", "def edit()", + "def patch()", "def update()", "def delete()"), + bodyLines(hints)); + + // Above every method, a comment naming the annotation that put it there, linking back to it, + // and a blank line separating it from what precedes + assertEquals(7, commentLines(hints).size()); + assertEquals("// @Scaffold(Quest) - inherited from RestfulController<Quest>", commentLines(hints).get(0)); + assertEquals("@Scaffold(Quest)", hints.get(2).targets().get(0).getText()); + assertEquals(List.of("", "", "", "", "", "", ""), blankLines(hints)); + + // Blank/comment/method triples above the closing brace, in declaration order, indented like the class's own members + int rBrace = clazz.getBody().getRBrace().getTextRange().getStartOffset(); + assertEquals(1 + 3 * 7, hints.size()); + for (int i = 1; i < hints.size(); i++) { + AboveLineIndentedPosition position = (AboveLineIndentedPosition)hints.get(i).position(); + assertEquals(rBrace, position.getOffset()); + assertEquals(i - 1, position.getVerticalPriority()); + String expectedStart = switch (i % 3) { + case 1 -> " "; + case 2 -> " // "; + default -> " def "; + }; + assertTrue(hints.get(i).text(), hints.get(i).text().startsWith(expectedStart)); + } + PsiMethod index = (PsiMethod)hints.get(3).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("// @Scaffold(RestfulServiceController<Quest>) - inherited from RestfulServiceController<Quest>", + commentLines(hints).get(0)); + assertEquals(List.of("def index(Integer max)", "def show()", "def create()", "def save()", "def edit()", + "def patch()", "def update()", "def delete()"), + bodyLines(hints)); + } + + /** The base's type parameter is shown as the domain, the way the scaffolded class sees it. */ + public void testServiceShowsGormServiceMembersWithTheDomainSubstituted() { + 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()); + // isReadOnly is a property accessor + assertEquals(List.of("Quest get(Serializable id)", "List<Quest> list(Map args)", "Long count(Map args)", + "void delete(Serializable id)", "Quest save(Quest instance)"), + bodyLines(hints)); + } + + 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/ScaffoldStructureViewExtensionTest.java b/plugin/src/test/java/org/apache/grails/intellij/plugin/feature/scaffold/ScaffoldStructureViewExtensionTest.java new file mode 100644 index 0000000..a336162 --- /dev/null +++ b/plugin/src/test/java/org/apache/grails/intellij/plugin/feature/scaffold/ScaffoldStructureViewExtensionTest.java @@ -0,0 +1,121 @@ +/* + * 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.ide.projectView.PresentationData; +import com.intellij.ide.structureView.StructureViewFactoryEx; +import com.intellij.ide.structureView.StructureViewTreeElement; +import com.intellij.ide.util.InheritedMembersNodeProvider; +import com.intellij.psi.PsiFile; +import com.intellij.psi.PsiMethod; +import com.intellij.ui.SimpleTextAttributes; +import org.apache.grails.intellij.lib.testFramework.GrailsTestCase; +import org.jetbrains.annotations.NotNull; +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 Structure view lists the methods {@code @Scaffold} gives a class under its node, greyed and + * located in the base, without "Show Inherited" - and steps aside when that toggle is on. + */ +public class ScaffoldStructureViewExtensionTest extends GrailsTestCase { + + private final ScaffoldStructureViewExtension myExtension = new ScaffoldStructureViewExtension(); + + private @NotNull StructureViewTreeElement[] childrenOf(@NotNull PsiFile file) { + GrTypeDefinition clazz = ((GroovyFile)file).getTypeDefinitions()[0]; + assertSame(GrTypeDefinition.class, myExtension.getType()); + return myExtension.getChildren(clazz); + } + + private static @NotNull List<String> texts(StructureViewTreeElement @NotNull [] elements) { + List<String> texts = new ArrayList<>(); + for (StructureViewTreeElement element : elements) texts.add(element.getPresentation().getPresentableText()); + return texts; + } + + private @NotNull PsiFile addScaffoldedController() { + ScaffoldingStubs.addTo(myFixture); + addDomain(""" + +package com.kousenit + +class Quest { + String name +} +"""); + return addController(""" + +package com.kousenit + +import grails.plugin.scaffolding.annotation.Scaffold + +@Scaffold(Quest) +class QuestController { + def show() {} +} +"""); + } + + public void testScaffoldedMethodsAreListedGreyedUnderTheClass() { + StructureViewTreeElement[] children = childrenOf(addScaffoldedController()); + + assertEquals(List.of("def index(Integer max)", "def create()", "def save()", "def edit()", + "def patch()", "def update()", "def delete()"), + texts(children)); + + StructureViewTreeElement index = children[0]; + PresentationData presentation = (PresentationData)index.getPresentation(); + assertEquals("RestfulController", presentation.getLocationString()); + assertEquals(SimpleTextAttributes.GRAYED_ATTRIBUTES, presentation.getColoredText().get(0).getAttributes()); + assertEquals("index", ((PsiMethod)index.getValue()).getName()); + assertTrue(index.canNavigate()); + } + + /** With "Show Inherited" on, the platform lists them already (the superclass is set), so nothing is added twice. */ + public void testStepsAsideWhenShowInheritedIsOn() { + PsiFile controller = addScaffoldedController(); + StructureViewFactoryEx factory = StructureViewFactoryEx.getInstanceEx(getProject()); + factory.setActiveAction(InheritedMembersNodeProvider.ID, true); + try { + assertEmpty(childrenOf(controller)); + } + finally { + factory.setActiveAction(InheritedMembersNodeProvider.ID, false); + } + assertSize(7, childrenOf(controller)); + } + + public void testPlainControllerAddsNothing() { + ScaffoldingStubs.addTo(myFixture); + PsiFile controller = addController(""" + +package com.kousenit + +class QuestController { + def index() {} +} +"""); + + assertEmpty(childrenOf(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; } + } + """); + } +}
