intellij plugin: add Jar library on module

Viewed 60

I am creating a framework and in the addSupport method I am trying to add a dependency on my jar library. But my current solution does not work :( A dependency does appear in the table, but it does not give access to classes, it is additionally highlighted in yellow in the library inspector.

WriteAction.run<RuntimeException> {
  val myLib : VirtualFile = VirtualFileManager.getInstance()
      .findFileByNioPath(Path.of("....jar"))!!
      .copy(...)

  val libraryTable = model.moduleLibraryTable
  val library = libraryTable.createLibrary(myLib.name)
  val libraryModel = library.modifiableModel
  libraryModel.addRoot(myLib, OrderRootType.CLASSES)
  libraryModel.commit()
}

How to correctly add a library dependency to a module?

1 Answers

I found a way to do this, you need to additionally indicate that the jar file system is used. Also no WriteAction wrapper needed.

val myLib : VirtualFile = VirtualFileManager.getInstance()
      .findFileByNioPath(Path.of("....jar"))!!
      .copy(...)

val libraryTable = model.moduleLibraryTable
val library = libraryTable.createLibrary(myLib.name)
val libraryModel = library.modifiableModel
libraryModel.addRoot(
  JarFileSystem.getInstance().getJarRootForLocalFile(myLib)!!,
  OrderRootType.CLASSES)
libraryModel.commit()
Related