|
| 1 | +/* |
| 2 | + * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package com.goide.inspections; |
| 18 | + |
| 19 | +import com.goide.psi.GoFile; |
| 20 | +import com.goide.psi.GoImportSpec; |
| 21 | +import com.goide.runconfig.testing.GoTestFinder; |
| 22 | +import com.intellij.codeInspection.LocalQuickFixBase; |
| 23 | +import com.intellij.codeInspection.ProblemDescriptor; |
| 24 | +import com.intellij.codeInspection.ProblemsHolder; |
| 25 | +import com.intellij.openapi.command.WriteCommandAction; |
| 26 | +import com.intellij.openapi.project.Project; |
| 27 | +import com.intellij.psi.PsiElement; |
| 28 | +import com.intellij.psi.PsiFile; |
| 29 | +import org.jetbrains.annotations.NotNull; |
| 30 | + |
| 31 | +public class GoSelfImportInspection extends GoInspectionBase { |
| 32 | + @Override |
| 33 | + protected void checkFile(@NotNull GoFile file, @NotNull ProblemsHolder problemsHolder) { |
| 34 | + if (GoTestFinder.getTestTargetPackage(file) != null) return; |
| 35 | + |
| 36 | + String fileImportPath = file.getImportPath(); |
| 37 | + for (GoImportSpec importSpec : file.getImports()) { |
| 38 | + String path = importSpec.getPath(); |
| 39 | + if (path.equals(fileImportPath) || path.equals(".")) { |
| 40 | + problemsHolder.registerProblem(importSpec, "Self import is not allowed", new GoSelfImportQuickFix()); |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + public static class GoSelfImportQuickFix extends LocalQuickFixBase { |
| 46 | + protected GoSelfImportQuickFix() { |
| 47 | + super("Remove self import"); |
| 48 | + } |
| 49 | + @Override |
| 50 | + public void applyFix(@NotNull final Project project, @NotNull ProblemDescriptor descriptor) { |
| 51 | + final PsiElement element = descriptor.getPsiElement(); |
| 52 | + final PsiFile file = element != null ? element.getContainingFile() : null; |
| 53 | + if (!(element instanceof GoImportSpec && file instanceof GoFile)) return; |
| 54 | + |
| 55 | + WriteCommandAction.runWriteCommandAction(project, new Runnable() { |
| 56 | + @Override |
| 57 | + public void run() { |
| 58 | + ((GoFile)file).deleteImport((GoImportSpec)element); |
| 59 | + } |
| 60 | + }); |
| 61 | + } |
| 62 | + } |
| 63 | +} |
0 commit comments