fun hasCircularDependencies()

in aspoet/src/main/kotlin/com/google/androidstudiopoet/models/ProjectBlueprint.kt [88:119]


    fun hasCircularDependencies(): Boolean {
        // Try to find a topological order (it will be stored in topologicalOrder)
        val dependencyCounter: MutableMap<String, Int> = mutableMapOf()
        for (moduleName in allModulesNames) {
            dependencyCounter[moduleName] = 0
        }
        // Count how many modules depend on each
        for ((_, dependencies) in allDependencies) {
            for (dependency in dependencies) {
                dependencyCounter.increase(dependency.name)
            }
        }
        // Try to generate a topological order
        val topologicalOrder = dependencyCounter.filter { (_, counter) -> counter == 0 }.map { it -> it.key }.toMutableList()
        var index = 0
        while (index < topologicalOrder.size && topologicalOrder.size < allModulesNames.size) {
            val from = topologicalOrder[index]
            for (dependency in allDependencies[from]!!) {
                val count = dependencyCounter.decrease(dependency.name)
                if (count == 0) {
                    topologicalOrder.add(dependency.name)
                }
            }
            index++
        }
        // No circular dependencies if and only if all modules can be sorted
        if (topologicalOrder.size != allModulesNames.size) {
            println("Found circular dependencies that affect modules ${dependencyCounter.filter { counter -> counter.value > 0 }.keys}")
            return true
        }
        return false
    }