Search code examples
javaparsingintellij-ideapluginsintellij-plugin

How to iterate through all files in IntelliJ plugin project?


I'm trying to create an IntelliJ plugin that iterates over all files in the project folder and parses all the .java files and then makes some changes in them. The problem is that after reading the documentation I don't have a clear idea how to iterate files over the whole project folder, I think I may use PSI files but I am not sure. Does anyone know or has an idea on how to accomplish this?


Solution

  • A possible way is to use AllClassesGetter, like this:

    Processor<PsiClass> processor = new Processor<PsiClass>() {
        @Override
        public boolean process(PsiClass psiClass) {
            // do your actual work here
            return true;
        }
    };
    
    AllClassesGetter.processJavaClasses(
            new PlainPrefixMatcher(""),
            project,
            GlobalSearchScope.projectScope(project),
            processor
    );
    

    processJavaClasses() will look for classes matching a given prefix in a given scope. By using an empty prefix and GlobalSearchScope.projectScope(), you should be able to iterate all classes declared in your project, and process them in processor. Note that the processor handles instances of PsiClass, which means you won't have to parse files manually. To modify classes, you just have to change the tree represented by these PsiClasses.