create module in a project programmatically

I want to create a module in an existing project. In this module i am just going to create a couple of folders and a few xml files.
The project name -- Testing, Module i want to create -- MODULE_NAME (constant)
Inside Testing, i want to create module with name as in MODULE_NAME. Then create a folder inside MODULE_NAME called resources. Below is my code.

final Project currentPrj = ProjectManager.getInstance().getOpenProjects()[0];
Module[] modules = ModuleManager.getInstance(currentPrj).getModules();
Module myModule = null;
    for (Module module : modules) {
        if (MODULE_NAME.equalsIgnoreCase(module.getName())) {
            myModule = module;
            break;
        }
    }

if (myModule == null) {
        myModule = ModuleManager.getInstance(currentPrj).newModule( MODULE_NAME, EmptyModuleType.EMPTY_MODULE);
//myModule = ModuleManager.getInstance(currentPrj).newModule(currentPrj.getBasePath() + FORWARD_SLASH + MODULE_NAME, EmptyModuleType.EMPTY_MODULE);  // -- this also does not work
    }


//code to create folder inside the module

final Module newMod = myModule;
final PsiFile[] file = new PsiFile[1];
    ApplicationManager.getApplication().runWriteAction(new Runnable() {
        @Override
        public void run() {
            PsiDirectory dir = PsiManager.getInstance(currentPrj).findDirectory(fcMod.getModuleFile());//.findDirectory(currentPrj);
            PsiDirectory rscDir = dir.findSubdirectory("resources");
            if (rscDir == null) {
                rscDir = dir.createSubdirectory("resources");
            }
            PsiDirectory templateDir = rscDir.findSubdirectory(folderName);
            if (templateDir == null) {
                templateDir = rscDir.createSubdirectory(folderName);
            }
            file[0] = templateDir.findFile(fileName);
            if (file[0] == null) {
                file[0] = templateDir.createFile(fileName);
            }
        }
    });
    return file[0];

1.) how to create a module inside a project
2.) how to get PsiDirectory of this module
3.) what is the module type i need to use.

1 comment
Comment actions Permalink

Creating a module is indeed done through ModuleManager.newModule().

There is no such thing as "the PsiDirectory of a module". A module can have multiple content roots, or no content roots at all (which will be the case for the new module created by your code). You need to explicitly create and configure a content root using ModifiableRootModel.addContentEntry().

For the module type, you can use either EmptyModuleType or WebModuleType.

0

Please sign in to leave a comment.