All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.leandroborgesferreira.dagcommand.logic.Graph.kt Maven / Gradle / Ivy

There is a newer version: 1.7.0
Show newest version
package com.github.leandroborgesferreira.dagcommand.logic

import com.github.leandroborgesferreira.dagcommand.domain.AdjacencyList
import com.github.leandroborgesferreira.dagcommand.domain.ModuleBuildStage
import java.util.*

fun affectedModules(adjacencyList: AdjacencyList, changedFolders: List): Set {
    val resultSet: MutableSet = mutableSetOf()

    changedFolders
        .filter { folder -> adjacencyList.keys.contains(folder) }
        .forEach { module ->
            traverseGraph(adjacencyList, module, resultSet)
        }

    return resultSet
}

private fun traverseGraph(adjacencyList: AdjacencyList, module: String, resultSet: MutableSet) {
    resultSet.add(module)

    adjacencyList[module]?.forEach { dependentModule ->
        traverseGraph(adjacencyList, dependentModule, resultSet)
    }
}

fun findRootNodes(adjacencyList: AdjacencyList) = adjacencyList.keys - adjacencyList.values.flatten()

fun buildOrder(adjacencyList: AdjacencyList): Map> {
    val modulesQueue: Queue = LinkedList().apply {
        addAll(findRootNodes(adjacencyList))
    }

    var currentStage = 0
    val moduleWithStage: List = adjacencyList.keys.map { module -> ModuleBuildStage(module) }

    while (modulesQueue.isNotEmpty()) {
        moduleWithStage.filter { (module, _) ->
            modulesQueue.contains(module)
        }.forEach { moduleBuildStage ->
            moduleBuildStage.stage = currentStage
        }

        val modulesOfNextLevel = modulesQueue.mapNotNull { module ->
            adjacencyList[module]
        }.reduce { acc, set -> acc + set }

        modulesQueue.clear()
        modulesQueue.addAll(modulesOfNextLevel)
        currentStage++
    }

    return moduleWithStage.groupBy { buildStage ->
        buildStage.stage
    }.mapValues { (_, stageList) ->
        stageList.map { it.module }
    }.toSortedMap()
}






© 2015 - 2024 Weber Informatics LLC | Privacy Policy