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();
}
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);
}
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);
}
}
}
}
}
}
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);
}
});
}
});
}
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;
}
Aggregations