Search in sources :

Example 51 with GroovyFile

use of org.jetbrains.plugins.groovy.lang.psi.GroovyFile in project android by JetBrains.

the class GradleDslElement method create.

/**
   * Creates the {@link GroovyPsiElement} by adding this element to the .gradle file.
   *
   * <p>It creates a new {@link GroovyPsiElement} only when {@link #getPsiElement()} return {@code null}.
   *
   * <p>Returns the final {@link GroovyPsiElement} corresponds to this element or {@code null} when failed to create the
   * {@link GroovyPsiElement}.
   */
@Nullable
public GroovyPsiElement create() {
    GroovyPsiElement psiElement = getPsiElement();
    if (psiElement != null) {
        return psiElement;
    }
    if (myParent == null) {
        return null;
    }
    GroovyPsiElement parentPsiElement = myParent.create();
    if (parentPsiElement == null) {
        return null;
    }
    Project project = parentPsiElement.getProject();
    GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(project);
    if (isNewEmptyBlockElement()) {
        // Avoid creation of an empty block statement.
        return null;
    }
    String statementText = myName + (isBlockElement() ? " {\n}\n" : " \"abc\", \"xyz\"");
    GrStatement statement = factory.createStatementFromText(statementText);
    if (statement instanceof GrApplicationStatement) {
        // Workaround to create an application statement.
        ((GrApplicationStatement) statement).getArgumentList().delete();
    }
    PsiElement lineTerminator = factory.createLineTerminator(1);
    PsiElement addedElement;
    if (parentPsiElement instanceof GroovyFile) {
        addedElement = parentPsiElement.addAfter(statement, parentPsiElement.getLastChild());
        parentPsiElement.addBefore(lineTerminator, addedElement);
    } else {
        addedElement = parentPsiElement.addBefore(statement, parentPsiElement.getLastChild());
        parentPsiElement.addAfter(lineTerminator, addedElement);
    }
    if (isBlockElement()) {
        GrClosableBlock closableBlock = getClosableBlock(addedElement);
        if (closableBlock != null) {
            setPsiElement(closableBlock);
        }
    } else {
        if (addedElement instanceof GrApplicationStatement) {
            setPsiElement((GrApplicationStatement) addedElement);
        }
    }
    return getPsiElement();
}
Also used : GroovyPsiElementFactory(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory) Project(com.intellij.openapi.project.Project) GroovyPsiElement(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement) GrClosableBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock) GrApplicationStatement(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrApplicationStatement) PsiElement(com.intellij.psi.PsiElement) GroovyPsiElement(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement) GroovyFile(org.jetbrains.plugins.groovy.lang.psi.GroovyFile) GrStatement(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement) Nullable(org.jetbrains.annotations.Nullable)

Example 52 with GroovyFile

use of org.jetbrains.plugins.groovy.lang.psi.GroovyFile in project freeline by alibaba.

the class FreelineUtil method installFreeline.

private static void installFreeline(final Project project, final FreelineStatus status, final PsiFile psiFile, final GradleDependencyEntity dependencyEntity) {
    needReformatCode = false;
    CommandProcessor.getInstance().runUndoTransparentAction(new Runnable() {

        @Override
        public void run() {
            ApplicationManager.getApplication().runWriteAction(new Runnable() {

                @Override
                public void run() {
                    if (!status.isExistClasspath()) {
                        Collection<VirtualFile> collection = status.getGradleBuildFiles();
                        if (dependencyEntity != null) {
                            for (VirtualFile file : collection) {
                                GradleBuildModel model = GradleBuildModel.parseBuildFile(file, project);
                                List<ArtifactDependencyModel> artifactDependencyModels = model.buildscript().dependencies().artifacts();
                                for (ArtifactDependencyModel model1 : artifactDependencyModels) {
                                    ArtifactDependencyModelWrapper wrapper = new ArtifactDependencyModelWrapper(model1);
                                    if (wrapper.group().equals(Constant.ANDROID_GRADLE_TOOL_GROUP_NAME)) {
                                        ArtifactDependencySpec spec = new ArtifactDependencySpec(dependencyEntity.getArtifactId(), dependencyEntity.getGroupId(), dependencyEntity.getNewestReleaseVersion());
                                        model.buildscript().dependencies().addArtifact("classpath", spec);
                                        model.applyChanges();
                                        needReformatCode = true;
                                        status.setClasspathFile(file);
                                        break;
                                    }
                                }
                                if (status.isExistClasspath()) {
                                    break;
                                }
                            }
                        }
                    }
                    if (!status.isExistPlugin()) {
                        if (psiFile != null && psiFile instanceof GroovyFile) {
                            GradleUtil.applyPlugin(project, (GroovyFile) psiFile, Constant.FREELINE_PLUGIN_ID);
                        }
                    }
                }
            });
        }
    });
    if (needReformatCode && status.getClasspathFile() != null) {
        DocumentUtil.reformatCode(project, status.getClasspathFile());
    }
    LogUtil.d("Sync Project Finish, start download freeline.zip.");
    initFreeline(project);
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) GradleBuildModel(com.android.tools.idea.gradle.dsl.model.GradleBuildModel) ArtifactDependencyModel(com.android.tools.idea.gradle.dsl.model.dependencies.ArtifactDependencyModel) GroovyFile(org.jetbrains.plugins.groovy.lang.psi.GroovyFile) ArtifactDependencySpec(com.android.tools.idea.gradle.dsl.model.dependencies.ArtifactDependencySpec)

Example 53 with GroovyFile

use of org.jetbrains.plugins.groovy.lang.psi.GroovyFile in project android by JetBrains.

the class SuppressLintIntentionAction method invoke.

@Override
public void invoke(@NotNull Project project, @Nullable Editor editor, @NotNull PsiFile file) throws IncorrectOperationException {
    if (file instanceof XmlFile) {
        final XmlTag element = PsiTreeUtil.getParentOfType(myElement, XmlTag.class);
        if (element == null) {
            return;
        }
        String lintId = getLintId(myId);
        addSuppressAttribute(project, (XmlFile) file, element, lintId);
    } else if (file instanceof PsiJavaFile) {
        final PsiModifierListOwner container = PsiTreeUtil.getParentOfType(myElement, PsiModifierListOwner.class);
        if (container == null) {
            return;
        }
        final PsiModifierList modifierList = container.getModifierList();
        if (modifierList != null) {
            String lintId = getLintId(myId);
            addSuppressAnnotation(project, container, container, lintId);
        }
    } else if (file instanceof GroovyFile) {
        Document document = PsiDocumentManager.getInstance(myElement.getProject()).getDocument(file);
        if (document != null) {
            int offset = myElement.getTextOffset();
            int line = document.getLineNumber(offset);
            int lineStart = document.getLineStartOffset(line);
            if (lineStart > 0) {
                int prevLineStart = document.getLineStartOffset(line - 1);
                int prevLineEnd = document.getLineEndOffset(line - 1);
                String prevLine = document.getText(new TextRange(prevLineStart, prevLineEnd));
                int index = prevLine.indexOf(NO_INSPECTION_PREFIX);
                if (index != -1) {
                    document.insertString(prevLineStart + index + NO_INSPECTION_PREFIX.length(), getLintId(myId) + ",");
                    return;
                }
            }
            String linePrefix = document.getText(new TextRange(lineStart, offset));
            int nonSpace = 0;
            for (; nonSpace < linePrefix.length(); nonSpace++) {
                if (!Character.isWhitespace(linePrefix.charAt(nonSpace))) {
                    break;
                }
            }
            ApplicationManager.getApplication().assertWriteAccessAllowed();
            document.insertString(lineStart + nonSpace, NO_INSPECTION_PREFIX + getLintId(myId) + "\n" + linePrefix.substring(0, nonSpace));
        }
    } else if (file instanceof PsiBinaryFile) {
        VirtualFile virtualFile = file.getVirtualFile();
        if (virtualFile != null) {
            File binaryFile = VfsUtilCore.virtualToIoFile(virtualFile);
            // Can't suppress lint checks inside a binary file (typically an icon): use
            // the lint XML facility instead
            Module module = ModuleUtilCore.findModuleForPsiElement(file);
            if (module != null) {
                //LintIdeRequest
                File dir = LintIdeProject.getLintProjectDirectory(module, AndroidFacet.getInstance(module));
                if (dir != null) {
                    LintIdeClient client = new LintIdeClient(project);
                    com.android.tools.lint.detector.api.Project lintProject = client.getProject(dir, dir);
                    Configuration configuration = client.getConfiguration(lintProject, null);
                    Issue issue = getIssue();
                    if (issue != null) {
                        configuration.ignore(issue, binaryFile);
                    }
                }
            }
        }
    }
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) Issue(com.android.tools.lint.detector.api.Issue) XmlFile(com.intellij.psi.xml.XmlFile) Configuration(com.android.tools.lint.client.api.Configuration) TextRange(com.intellij.openapi.util.TextRange) Document(com.intellij.openapi.editor.Document) Project(com.intellij.openapi.project.Project) Module(com.intellij.openapi.module.Module) XmlFile(com.intellij.psi.xml.XmlFile) VirtualFile(com.intellij.openapi.vfs.VirtualFile) GroovyFile(org.jetbrains.plugins.groovy.lang.psi.GroovyFile) File(java.io.File) GroovyFile(org.jetbrains.plugins.groovy.lang.psi.GroovyFile) XmlTag(com.intellij.psi.xml.XmlTag)

Example 54 with GroovyFile

use of org.jetbrains.plugins.groovy.lang.psi.GroovyFile in project android by JetBrains.

the class LintIdeGradleDetector method visitBuildScript.

@Override
public void visitBuildScript(@NonNull final Context context, Map<String, Object> sharedData) {
    ApplicationManager.getApplication().runReadAction(new Runnable() {

        @Override
        public void run() {
            final PsiFile psiFile = LintIdeUtils.getPsiFile(context);
            if (!(psiFile instanceof GroovyFile)) {
                return;
            }
            GroovyFile groovyFile = (GroovyFile) psiFile;
            groovyFile.accept(new GroovyRecursiveElementVisitor() {

                @Override
                public void visitClosure(GrClosableBlock closure) {
                    String parentName = getClosureName(closure);
                    String parentParentName = null;
                    if (parentName != null) {
                        GrClosableBlock block = PsiTreeUtil.getParentOfType(closure, GrClosableBlock.class, true);
                        if (block != null) {
                            parentParentName = getClosureName(block);
                        }
                    }
                    if (parentName != null && isInterestingBlock(parentName, parentParentName)) {
                        for (PsiElement element : closure.getChildren()) {
                            if (element instanceof GrApplicationStatement) {
                                GrApplicationStatement call = (GrApplicationStatement) element;
                                GrExpression propertyExpression = call.getInvokedExpression();
                                GrCommandArgumentList argumentList = call.getArgumentList();
                                if (propertyExpression instanceof GrReferenceExpression) {
                                    GrReferenceExpression propertyRef = (GrReferenceExpression) propertyExpression;
                                    String property = propertyRef.getReferenceName();
                                    //noinspection ConstantConditions
                                    if (property != null && isInterestingProperty(property, parentName, parentParentName) && argumentList != null) {
                                        String value = argumentList.getText();
                                        checkDslPropertyAssignment(context, property, value, parentName, parentParentName, argumentList, call);
                                    }
                                }
                            } else if (element instanceof GrAssignmentExpression) {
                                GrAssignmentExpression assignment = (GrAssignmentExpression) element;
                                GrExpression lValue = assignment.getLValue();
                                if (lValue instanceof GrReferenceExpression) {
                                    GrReferenceExpression propertyRef = (GrReferenceExpression) lValue;
                                    String property = propertyRef.getReferenceName();
                                    if (property != null && isInterestingProperty(property, parentName, parentParentName)) {
                                        GrExpression rValue = assignment.getRValue();
                                        if (rValue != null) {
                                            String value = rValue.getText();
                                            checkDslPropertyAssignment(context, property, value, parentName, parentParentName, rValue, assignment);
                                            // handle it here.
                                            if (property.equals(ATTR_MIN_SDK_VERSION) || property.equals(ATTR_TARGET_SDK_VERSION)) {
                                                int lValueEnd = lValue.getTextRange().getEndOffset();
                                                int rValueStart = rValue.getTextRange().getStartOffset();
                                                assert lValueEnd <= rValueStart;
                                                DefaultPosition startPosition = new DefaultPosition(-1, -1, lValueEnd);
                                                DefaultPosition endPosition = new DefaultPosition(-1, -1, rValueStart);
                                                Location location = Location.create(context.file, startPosition, endPosition);
                                                String message = String.format("Do not use assignment with the %1$s property (remove the '=')", property);
                                                context.report(GradleDetector.IDE_SUPPORT, location, message, null);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    super.visitClosure(closure);
                }

                @Override
                public void visitApplicationStatement(GrApplicationStatement applicationStatement) {
                    GrClosableBlock block = PsiTreeUtil.getParentOfType(applicationStatement, GrClosableBlock.class, true);
                    String parentName = block != null ? getClosureName(block) : null;
                    String statementName = applicationStatement.getInvokedExpression().getText();
                    if (isInterestingStatement(statementName, parentName)) {
                        GrCommandArgumentList argumentList = applicationStatement.getArgumentList();
                        Map<String, String> namedArguments = Maps.newHashMap();
                        List<String> unnamedArguments = Lists.newArrayList();
                        for (GroovyPsiElement groovyPsiElement : argumentList.getAllArguments()) {
                            if (groovyPsiElement instanceof GrNamedArgument) {
                                GrNamedArgument namedArgument = (GrNamedArgument) groovyPsiElement;
                                GrExpression expression = namedArgument.getExpression();
                                if (expression == null || !(expression instanceof GrLiteral)) {
                                    continue;
                                }
                                Object value = ((GrLiteral) expression).getValue();
                                if (value == null) {
                                    continue;
                                }
                                namedArguments.put(namedArgument.getLabelName(), value.toString());
                            } else if (groovyPsiElement instanceof GrExpression) {
                                unnamedArguments.add(groovyPsiElement.getText());
                            }
                        }
                        checkMethodCall(context, statementName, parentName, namedArguments, unnamedArguments, applicationStatement);
                    }
                    super.visitApplicationStatement(applicationStatement);
                }
            });
        }
    });
}
Also used : GroovyPsiElement(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement) GrNamedArgument(org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrNamedArgument) GrClosableBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock) GroovyRecursiveElementVisitor(org.jetbrains.plugins.groovy.lang.psi.GroovyRecursiveElementVisitor) PsiFile(com.intellij.psi.PsiFile) GrLiteral(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral) GroovyFile(org.jetbrains.plugins.groovy.lang.psi.GroovyFile) PsiElement(com.intellij.psi.PsiElement) GroovyPsiElement(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement)

Example 55 with GroovyFile

use of org.jetbrains.plugins.groovy.lang.psi.GroovyFile in project android by JetBrains.

the class UnusedResourcesProcessor method computeUnusedDeclarationElements.

@NotNull
private List<PsiElement> computeUnusedDeclarationElements(Map<Issue, Map<File, List<ProblemData>>> map) {
    final List<PsiElement> elements = Lists.newArrayList();
    // Make sure lint didn't put extra issues into the map
    for (Issue issue : Lists.newArrayList(map.keySet())) {
        if (issue != UnusedResourceDetector.ISSUE && issue != UnusedResourceDetector.ISSUE_IDS) {
            map.remove(issue);
        }
    }
    ApplicationManager.getApplication().assertReadAccessAllowed();
    PsiManager manager = PsiManager.getInstance(myProject);
    for (Issue issue : new Issue[] { UnusedResourceDetector.ISSUE, UnusedResourceDetector.ISSUE_IDS }) {
        Map<File, List<ProblemData>> fileListMap = map.get(issue);
        if (fileListMap != null && !fileListMap.isEmpty()) {
            Map<File, PsiFile> files = Maps.newHashMap();
            for (File file : fileListMap.keySet()) {
                VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByIoFile(file);
                if (virtualFile != null) {
                    if (!virtualFile.isDirectory()) {
                        // Gradle model errors currently don't have source positions
                        PsiFile psiFile = manager.findFile(virtualFile);
                        if (psiFile != null) {
                            files.put(file, psiFile);
                        }
                    }
                }
            }
            if (!files.isEmpty()) {
                for (File file : files.keySet()) {
                    PsiFile psiFile = files.get(file);
                    if (psiFile == null) {
                        // where we only had the project directory as the location from the Gradle model
                        continue;
                    }
                    if (!CommonRefactoringUtil.checkReadOnlyStatus(myProject, psiFile)) {
                        continue;
                    }
                    List<ProblemData> problems = fileListMap.get(file);
                    if (psiFile.getFileType().isBinary()) {
                        // Delete the whole file
                        if (matchesFilter(fileListMap, file)) {
                            elements.add(psiFile);
                        }
                    } else {
                        ResourceFolderType folderType = ResourceHelper.getFolderType(psiFile);
                        if (folderType == null) {
                            // file; see for example http://b.android.com/220069.)
                            if (psiFile.getFileType() == GroovyFileType.GROOVY_FILE_TYPE && psiFile instanceof GroovyFile) {
                                ((GroovyFile) psiFile).accept(new GroovyRecursiveElementVisitor() {

                                    @Override
                                    public void visitApplicationStatement(GrApplicationStatement applicationStatement) {
                                        super.visitApplicationStatement(applicationStatement);
                                        PsiMethod method = applicationStatement.resolveMethod();
                                        if (method != null && method.getName().equals("resValue")) {
                                            GrExpression[] args = applicationStatement.getArgumentList().getExpressionArguments();
                                            if (args.length >= 3) {
                                                Object typeString = GroovyConstantExpressionEvaluator.evaluate(args[0]);
                                                Object nameString = GroovyConstantExpressionEvaluator.evaluate(args[1]);
                                                // See if this is one of the unused resources
                                                if (typeString != null && nameString != null) {
                                                    List<ProblemData> problems = fileListMap.get(VfsUtilCore.virtualToIoFile(psiFile.getVirtualFile()));
                                                    if (problems != null) {
                                                        for (ProblemData problem : problems) {
                                                            String unusedResource = UnusedResourceDetector.getUnusedResource(problem.getMessage(), TextFormat.RAW);
                                                            if (unusedResource != null && unusedResource.equals(SdkConstants.R_PREFIX + typeString + '.' + nameString)) {
                                                                elements.add(applicationStatement);
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                });
                            }
                            continue;
                        }
                        if (folderType != ResourceFolderType.VALUES) {
                            // also being deleted as unused
                            if (issue == UnusedResourceDetector.ISSUE_IDS) {
                                Map<File, List<ProblemData>> m = map.get(UnusedResourceDetector.ISSUE);
                                if (m != null && m.containsKey(file)) {
                                    // Yes - skip
                                    continue;
                                }
                                // Delete ranges within the file
                                addElementsInFile(elements, psiFile, problems);
                            } else {
                                // Unused non-value resource file: Delete the whole file
                                if (matchesFilter(fileListMap, file)) {
                                    elements.add(psiFile);
                                }
                            }
                        } else {
                            addElementsInFile(elements, psiFile, problems);
                        }
                    }
                }
            }
        }
    }
    return elements;
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) Issue(com.android.tools.lint.detector.api.Issue) GroovyRecursiveElementVisitor(org.jetbrains.plugins.groovy.lang.psi.GroovyRecursiveElementVisitor) GrApplicationStatement(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrApplicationStatement) ProblemData(org.jetbrains.android.inspections.lint.ProblemData) ResourceFolderType(com.android.resources.ResourceFolderType) List(java.util.List) XmlFile(com.intellij.psi.xml.XmlFile) VirtualFile(com.intellij.openapi.vfs.VirtualFile) GroovyFile(org.jetbrains.plugins.groovy.lang.psi.GroovyFile) File(java.io.File) GroovyFile(org.jetbrains.plugins.groovy.lang.psi.GroovyFile) NotNull(org.jetbrains.annotations.NotNull)

Aggregations

GroovyFile (org.jetbrains.plugins.groovy.lang.psi.GroovyFile)91 PsiFile (com.intellij.psi.PsiFile)26 PsiElement (com.intellij.psi.PsiElement)21 NotNull (org.jetbrains.annotations.NotNull)17 GrImportStatement (org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement)17 VirtualFile (com.intellij.openapi.vfs.VirtualFile)13 Project (com.intellij.openapi.project.Project)10 GrTypeDefinition (org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition)10 PsiClass (com.intellij.psi.PsiClass)9 GrClosableBlock (org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock)9 Nullable (org.jetbrains.annotations.Nullable)8 GroovyPsiElement (org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement)8 GroovyScriptClass (org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GroovyScriptClass)8 GroovyPsiElementFactory (org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory)7 Module (com.intellij.openapi.module.Module)6 IncorrectOperationException (com.intellij.util.IncorrectOperationException)6 GrReferenceElement (org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement)6 GrReferenceExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression)6 GrParameter (org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter)6 ASTNode (com.intellij.lang.ASTNode)5