@Nullable
 @Override
 public CommonProblemDescriptor[] checkElement(
     @NotNull RefEntity refEntity,
     @NotNull AnalysisScope scope,
     @NotNull InspectionManager manager,
     @NotNull GlobalInspectionContext globalContext) {
   if (!(refEntity instanceof RefPackage)) {
     return null;
   }
   final RefPackage refPackage = (RefPackage) refEntity;
   final String packageName = refPackage.getQualifiedName();
   final Project project = globalContext.getProject();
   final PsiPackage aPackage = JavaPsiFacade.getInstance(project).findPackage(packageName);
   if (aPackage == null) {
     return null;
   }
   final List<RefEntity> children = refPackage.getChildren();
   boolean hasClasses = false;
   for (RefEntity child : children) {
     if (child instanceof RefClass) {
       hasClasses = true;
       break;
     }
   }
   if (!hasClasses) {
     return null;
   }
   final PsiDirectory[] directories = aPackage.getDirectories();
   for (PsiDirectory directory : directories) {
     final boolean packageInfoFound = directory.findFile(PsiPackage.PACKAGE_INFO_FILE) != null;
     final boolean packageDotHtmlFound = directory.findFile("package.html") != null;
     if (packageInfoFound || packageDotHtmlFound) {
       return null;
     }
   }
   if (PsiUtil.isLanguageLevel5OrHigher(aPackage)) {
     return new CommonProblemDescriptor[] {
       manager.createProblemDescriptor(
           InspectionGadgetsBundle.message("missing.package.info.problem.descriptor", packageName))
     };
   } else {
     return new CommonProblemDescriptor[] {
       manager.createProblemDescriptor(
           InspectionGadgetsBundle.message("missing.package.html.problem.descriptor", packageName))
     };
   }
 }
  @Nullable
  private XmlFile createAnnotationsXml(
      @NotNull VirtualFile root, @NonNls @NotNull String packageName) {
    final String[] dirs = packageName.split("[\\.]");
    for (String dir : dirs) {
      if (dir.isEmpty()) break;
      VirtualFile subdir = root.findChild(dir);
      if (subdir == null) {
        try {
          subdir = root.createChildDirectory(null, dir);
        } catch (IOException e) {
          LOG.error(e);
        }
      }
      root = subdir;
    }
    final PsiDirectory directory = myPsiManager.findDirectory(root);
    if (directory == null) return null;

    final PsiFile psiFile = directory.findFile(ANNOTATIONS_XML);
    if (psiFile instanceof XmlFile) {
      return (XmlFile) psiFile;
    }

    try {
      final PsiFileFactory factory = PsiFileFactory.getInstance(myPsiManager.getProject());
      return (XmlFile)
          directory.add(
              factory.createFileFromText(ANNOTATIONS_XML, XmlFileType.INSTANCE, "<root></root>"));
    } catch (IncorrectOperationException e) {
      LOG.error(e);
    }
    return null;
  }
Esempio n. 3
0
    @Override
    public Result<PsiModifierList> compute() {
      List<PsiModifierList> list = new ArrayList<PsiModifierList>();
      for (PsiDirectory directory : getDirectories()) {
        PsiFile file = directory.findFile(PACKAGE_INFO_FILE);
        if (file != null) {
          PsiPackageStatement stmt = PsiTreeUtil.getChildOfType(file, PsiPackageStatement.class);
          if (stmt != null) {
            final PsiModifierList modifierList = stmt.getAnnotationList();
            if (modifierList != null) {
              list.add(modifierList);
            }
          }
        }
      }

      final JavaPsiFacade facade = getFacade();
      final GlobalSearchScope scope = allScope();
      for (PsiClass aClass : facade.findClasses(getQualifiedName() + ".package-info", scope)) {
        ContainerUtil.addIfNotNull(aClass.getModifierList(), list);
      }

      return new Result<PsiModifierList>(
          list.isEmpty() ? null : new PsiCompositeModifierList(getManager(), list),
          OOCB_DEPENDENCY);
    }
  @NotNull
  private static List<RatedResolveResult> resolveInDirectory(
      @NotNull final String referencedName,
      @Nullable final PsiFile containingFile,
      final PsiDirectory dir,
      boolean isFileOnly,
      boolean checkForPackage) {
    final PsiDirectory subdir = dir.findSubdirectory(referencedName);
    if (subdir != null && (!checkForPackage || PyUtil.isPackage(subdir, containingFile))) {
      return ResolveResultList.to(subdir);
    }

    final PsiFile module = findPyFileInDir(dir, referencedName);
    if (module != null) {
      return ResolveResultList.to(module);
    }

    if (!isFileOnly) {
      // not a subdir, not a file; could be a name in parent/__init__.py
      final PsiFile initPy = dir.findFile(PyNames.INIT_DOT_PY);
      if (initPy == containingFile) {
        return Collections.emptyList(); // don't dive into the file we're in
      }
      if (initPy instanceof PyFile) {
        return ((PyFile) initPy).multiResolveName(referencedName);
      }
    }
    return Collections.emptyList();
  }
 @Nullable
 private static PsiFile findPyFileInDir(PsiDirectory dir, String referencedName) {
   PsiFile file = dir.findFile(referencedName + PyNames.DOT_PY);
   if (file == null) {
     final List<FileNameMatcher> associations =
         FileTypeManager.getInstance().getAssociations(PythonFileType.INSTANCE);
     for (FileNameMatcher association : associations) {
       if (association instanceof ExtensionFileNameMatcher) {
         file =
             dir.findFile(
                 referencedName + "." + ((ExtensionFileNameMatcher) association).getExtension());
         if (file != null) break;
       }
     }
   }
   if (file != null && FileUtil.getNameWithoutExtension(file.getName()).equals(referencedName)) {
     return file;
   }
   return null;
 }
  public void testResourceBundleManagerUpdatesProperlyWhileDirMove() {
    final PropertiesFile propFile1 =
        PropertiesImplUtil.getPropertiesFile(myFixture.addFileToProject("qwe/p.properties", ""));
    final PropertiesFile propFile2 =
        PropertiesImplUtil.getPropertiesFile(
            myFixture.addFileToProject("qwe/p_abc.properties", ""));
    assertNotNull(propFile1);
    assertNotNull(propFile2);
    myFixture.addFileToProject("qwe/q.properties", "");
    final PropertiesFile propertiesFile =
        PropertiesImplUtil.getPropertiesFile(myFixture.addFileToProject("qwe/q_fr.properties", ""));
    assertNotNull(propertiesFile);
    assertSize(2, propertiesFile.getResourceBundle().getPropertiesFiles());

    final ResourceBundleManager resourceBundleManager =
        ResourceBundleManager.getInstance(getProject());
    resourceBundleManager.combineToResourceBundle(
        ContainerUtil.newArrayList(propFile1, propFile2), "p");
    resourceBundleManager.dissociateResourceBundle(propertiesFile.getResourceBundle());
    assertSize(1, propertiesFile.getResourceBundle().getPropertiesFiles());
    assertSize(2, propFile2.getResourceBundle().getPropertiesFiles());

    final PsiDirectory toMove = myFixture.addFileToProject("asd/temp.txt", "").getParent();
    assertNotNull(toMove);
    ApplicationManager.getApplication()
        .runWriteAction(
            () -> MoveFilesOrDirectoriesUtil.doMoveDirectory(propFile1.getParent(), toMove));

    final PsiDirectory movedDir = toMove.findSubdirectory("qwe");
    assertNotNull(movedDir);

    final PropertiesFile newPropFile1 =
        PropertiesImplUtil.getPropertiesFile(movedDir.findFile("p.properties"));
    assertNotNull(newPropFile1);
    assertSize(2, newPropFile1.getResourceBundle().getPropertiesFiles());

    final PropertiesFile newPropertiesFile =
        PropertiesImplUtil.getPropertiesFile(movedDir.findFile("q_fr.properties"));
    assertNotNull(newPropertiesFile);
    assertSize(1, newPropertiesFile.getResourceBundle().getPropertiesFiles());
  }
  @Override
  public ProblemDescriptor[] checkClass(
      @NotNull PsiClass aClass, @NotNull InspectionManager manager, boolean isOnTheFly) {
    final Project project = aClass.getProject();
    final PsiIdentifier nameIdentifier = aClass.getNameIdentifier();
    final Module module = ModuleUtil.findModuleForPsiElement(aClass);

    if (nameIdentifier == null || module == null || !PsiUtil.isInstanciatable(aClass)) return null;

    final PsiClass base =
        JavaPsiFacade.getInstance(project)
            .findClass(INTENTION, GlobalSearchScope.allScope(project));

    if (base == null || !aClass.isInheritor(base, true)) return null;

    String descriptionDir = getDescriptionDirName(aClass);
    if (StringUtil.isEmptyOrSpaces(descriptionDir)) {
      return null;
    }

    for (PsiDirectory description : getIntentionDescriptionsDirs(module)) {
      PsiDirectory dir = description.findSubdirectory(descriptionDir);
      if (dir == null) continue;
      final PsiFile descr = dir.findFile("description.html");
      if (descr != null) {
        if (!hasBeforeAndAfterTemplate(dir.getVirtualFile())) {
          PsiElement problem = aClass.getNameIdentifier();
          ProblemDescriptor problemDescriptor =
              manager.createProblemDescriptor(
                  problem == null ? nameIdentifier : problem,
                  "Intention must have 'before.*.template' and 'after.*.template' beside 'description.html'",
                  isOnTheFly,
                  ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
          return new ProblemDescriptor[] {problemDescriptor};
        }

        return null;
      }
    }

    final PsiElement problem = aClass.getNameIdentifier();
    final ProblemDescriptor problemDescriptor =
        manager.createProblemDescriptor(
            problem == null ? nameIdentifier : problem,
            "Intention does not have a description",
            isOnTheFly,
            new LocalQuickFix[] {new CreateHtmlDescriptionFix(descriptionDir, module, true)},
            ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
    return new ProblemDescriptor[] {problemDescriptor};
  }
  @Override
  public ProblemDescriptor[] checkClass(
      @NotNull PsiClass aClass, @NotNull InspectionManager manager, boolean isOnTheFly) {
    final Project project = aClass.getProject();
    final PsiIdentifier nameIdentifier = aClass.getNameIdentifier();
    final Module module = ModuleUtilCore.findModuleForPsiElement(aClass);

    if (nameIdentifier == null || module == null || !PsiUtil.isInstantiable(aClass)) return null;

    final PsiClass base =
        JavaPsiFacade.getInstance(project).findClass(getClassName(), aClass.getResolveScope());
    if (base == null || !aClass.isInheritor(base, true)) return null;

    String descriptionDir = DescriptionCheckerUtil.getDescriptionDirName(aClass);
    if (StringUtil.isEmptyOrSpaces(descriptionDir)) {
      return null;
    }

    for (PsiDirectory description : getDescriptionsDirs(module)) {
      PsiDirectory dir = description.findSubdirectory(descriptionDir);
      if (dir == null) continue;
      final PsiFile descr = dir.findFile("description.html");
      if (descr != null) {
        if (!hasBeforeAndAfterTemplate(dir.getVirtualFile())) {
          PsiElement problem = aClass.getNameIdentifier();
          ProblemDescriptor problemDescriptor =
              manager.createProblemDescriptor(
                  problem == null ? nameIdentifier : problem,
                  getHasNotBeforeAfterError(),
                  isOnTheFly,
                  ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
                  false);
          return new ProblemDescriptor[] {problemDescriptor};
        }

        return null;
      }
    }

    final PsiElement problem = aClass.getNameIdentifier();
    final ProblemDescriptor problemDescriptor =
        manager.createProblemDescriptor(
            problem == null ? nameIdentifier : problem,
            getHasNotDescriptionError(),
            isOnTheFly,
            new LocalQuickFix[] {getFix(module, descriptionDir)},
            ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
    return new ProblemDescriptor[] {problemDescriptor};
  }
    @Nullable
    @Override
    protected ValidationInfo doValidate() {
      for (String fileName : myComponent.getFileNamesToCreate()) {
        if (!PathUtil.isValidFileName(fileName)) {
          return new ValidationInfo(
              String.format("File name for properties file '%s' is invalid", fileName));
        } else {
          if (myDirectory.findFile(fileName) != null) {
            return new ValidationInfo(String.format("File with name '%s' already exist", fileName));
          }
        }
      }

      return null;
    }
  public static boolean checkFileExist(
      @Nullable PsiDirectory targetDirectory,
      int[] choice,
      PsiFile file,
      String name,
      String title) {
    if (targetDirectory == null) return false;
    final PsiFile existing = targetDirectory.findFile(name);
    if (existing != null && !existing.equals(file)) {
      int selection;
      if (choice == null || choice[0] == -1) {
        String message =
            String.format(
                "File '%s' already exists in directory '%s'",
                name, targetDirectory.getVirtualFile().getPath());
        String[] options =
            choice == null
                ? new String[] {"Overwrite", "Skip"}
                : new String[] {"Overwrite", "Skip", "Overwrite for all", "Skip for all"};
        selection = Messages.showDialog(message, title, options, 0, Messages.getQuestionIcon());
      } else {
        selection = choice[0];
      }

      if (choice != null && selection > 1) {
        choice[0] = selection % 2;
        selection = choice[0];
      }

      if (selection == 0 && file != existing) {
        existing.delete();
      } else {
        return true;
      }
    }

    return false;
  }
 @Nullable
 public static PyType getTypeFromTarget(
     @NotNull final PsiElement target,
     final TypeEvalContext context,
     PyReferenceExpression anchor) {
   if (!(target
       instanceof PyTargetExpression)) { // PyTargetExpression will ask about its type itself
     final PyType pyType = getReferenceTypeFromProviders(target, context, anchor);
     if (pyType != null) {
       return pyType;
     }
   }
   if (target instanceof PyTargetExpression) {
     final String name = ((PyTargetExpression) target).getName();
     if (PyNames.NONE.equals(name)) {
       return PyNoneType.INSTANCE;
     }
     if (PyNames.TRUE.equals(name) || PyNames.FALSE.equals(name)) {
       return PyBuiltinCache.getInstance(target).getBoolType();
     }
   }
   if (target instanceof PyFile) {
     return new PyModuleType((PyFile) target);
   }
   if (target instanceof PyImportedModule) {
     return new PyImportedModuleType((PyImportedModule) target);
   }
   if ((target instanceof PyTargetExpression || target instanceof PyNamedParameter)
       && anchor != null
       && context.allowDataFlow(anchor)) {
     final ScopeOwner scopeOwner = PsiTreeUtil.getStubOrPsiParentOfType(anchor, ScopeOwner.class);
     if (scopeOwner != null
         && scopeOwner == PsiTreeUtil.getStubOrPsiParentOfType(target, ScopeOwner.class)) {
       final String name = ((PyElement) target).getName();
       if (name != null) {
         final PyType type = getTypeByControlFlow(name, context, anchor, scopeOwner);
         if (type != null) {
           return type;
         }
       }
     }
   }
   if (target instanceof PyFunction) {
     final PyDecoratorList decoratorList = ((PyFunction) target).getDecoratorList();
     if (decoratorList != null) {
       final PyDecorator propertyDecorator = decoratorList.findDecorator(PyNames.PROPERTY);
       if (propertyDecorator != null) {
         return PyBuiltinCache.getInstance(target).getObjectType(PyNames.PROPERTY);
       }
       for (PyDecorator decorator : decoratorList.getDecorators()) {
         final QualifiedName qName = decorator.getQualifiedName();
         if (qName != null
             && (qName.endsWith(PyNames.SETTER)
                 || qName.endsWith(PyNames.DELETER)
                 || qName.endsWith(PyNames.GETTER))) {
           return PyBuiltinCache.getInstance(target).getObjectType(PyNames.PROPERTY);
         }
       }
     }
   }
   if (target instanceof PyTypedElement) {
     return context.getType((PyTypedElement) target);
   }
   if (target instanceof PsiDirectory) {
     final PsiDirectory dir = (PsiDirectory) target;
     PsiFile file = dir.findFile(PyNames.INIT_DOT_PY);
     if (file != null) {
       return getTypeFromTarget(file, context, anchor);
     }
     if (PyUtil.isPackage(dir, anchor)) {
       final PsiFile containingFile = anchor.getContainingFile();
       if (containingFile instanceof PyFile) {
         final QualifiedName qualifiedName = QualifiedNameFinder.findShortestImportableQName(dir);
         if (qualifiedName != null) {
           final PyImportedModule module =
               new PyImportedModule(null, (PyFile) containingFile, qualifiedName);
           return new PyImportedModuleType(module);
         }
       }
     }
   }
   return null;
 }