fun registerSdkIfNeeded()

in gdscript/src/main/kotlin/gdscript/library/GdLibraryManager.kt [27:80]


    fun registerSdkIfNeeded(path: Path, project: Project) {
        val sourceRoot = LocalFileSystem.getInstance().refreshAndFindFileByPath(path.pathString)

        if (sourceRoot == null) {
            throw Exception("Cannot find SDK at $path")
        }

        val module = ModuleManager.getInstance(project).modules.first()

        val libraryTable = LibraryTablesRegistrar.getInstance().getLibraryTable(project)
        libraryTable.getLibraryByName(LIBRARY_NAME)?.let { lib->
            // I see this doesn't work on the dev build
            // different casing of letters
            // /Users/ivan.shakhov/Work/ultimate/out/dev-run/Rider
            // vs
            // /Users/ivan.shakhov/Work/ultimate/out/dev-run/rider
            if (lib.isValid(sourceRoot.url, OrderRootType.SOURCES)
                && libraryTable.libraries.count { library -> library.name?.startsWith(LIBRARY_NAME) == true } == 1
                && ModuleRootManager.getInstance(module)
                    .orderEntries
                    .filterIsInstance<LibraryOrderEntry>()
                    .any { it.library == lib }) { // check that module has dependency on this library
                return@registerSdkIfNeeded
            }
        }

        var tableModel = libraryTable.modifiableModel
        val libraries = tableModel.libraries.filter { library -> library.name?.startsWith(LIBRARY_NAME) == true }

        if (libraries.any()) {
            for (library in libraries) {
                tableModel.removeLibrary(library)
            }

            ApplicationManager.getApplication().invokeAndWait {
                ApplicationManager.getApplication().runWriteAction(Runnable {
                    tableModel.commit()
                })
            }
        }

        tableModel = libraryTable.modifiableModel
        val library = tableModel.createLibrary(LIBRARY_NAME, GdLibraryKind)
        val libraryModel = library.modifiableModel
        libraryModel.addRoot(sourceRoot, OrderRootType.SOURCES)

        ApplicationManager.getApplication().invokeAndWait {
            ApplicationManager.getApplication().runWriteAction(Runnable {
                libraryModel.commit()
                tableModel.commit()
            })
            ModuleRootModificationUtil.addDependency(module, library)
        }
    }