private static Library addProjectLibrary(
      Module module,
      ModifiableRootModel model,
      String libName,
      List<VirtualFile> classesRoots,
      List<VirtualFile> sourceRoots) {
    LibraryTable libraryTable = ProjectLibraryTable.getInstance(module.getProject());
    RunResult<Library> result =
        new WriteAction<Library>() {
          @Override
          protected void run(@NotNull Result<Library> result) throws Throwable {
            Library library = libraryTable.createLibrary(libName);
            Library.ModifiableModel libraryModel = library.getModifiableModel();
            try {
              for (VirtualFile root : classesRoots) {
                libraryModel.addRoot(root, OrderRootType.CLASSES);
              }
              for (VirtualFile root : sourceRoots) {
                libraryModel.addRoot(root, OrderRootType.SOURCES);
              }
              libraryModel.commit();
            } catch (Throwable t) {
              //noinspection SSBasedInspection
              libraryModel.dispose();
              throw t;
            }

            model.addLibraryEntry(library);
            OrderEntry[] orderEntries = model.getOrderEntries();
            OrderEntry last = orderEntries[orderEntries.length - 1];
            System.arraycopy(orderEntries, 0, orderEntries, 1, orderEntries.length - 1);
            orderEntries[0] = last;
            model.rearrangeOrderEntries(orderEntries);
            result.setResult(library);
          }
        }.execute();
    result.throwException();
    return result.getResultObject();
  }