diff --git a/Sources/PNDependencyGraph/PNCompilationError.swift b/Sources/PNDependencyGraph/PNCompilationError.swift new file mode 100644 index 0000000..d7306fe --- /dev/null +++ b/Sources/PNDependencyGraph/PNCompilationError.swift @@ -0,0 +1,6 @@ +import Foundation + +public enum PNCompilationError: Error { + /// Indicates that the graph contains a cycle and cannot be compiled. + case cycle +} diff --git a/Sources/PNDependencyGraph/PNCompiledGraph.swift b/Sources/PNDependencyGraph/PNCompiledGraph.swift index cba97c6..4814188 100644 --- a/Sources/PNDependencyGraph/PNCompiledGraph.swift +++ b/Sources/PNDependencyGraph/PNCompiledGraph.swift @@ -1,5 +1,6 @@ import Foundation +/// A compiled dependency graph. public final class PNCompiledGraph { let nodes: [PNNode] init(nodes newNodes: [PNNode]) { diff --git a/Sources/PNDependencyGraph/PNDependencyGraph.swift b/Sources/PNDependencyGraph/PNDependencyGraph.swift index d24b5f8..09e082f 100644 --- a/Sources/PNDependencyGraph/PNDependencyGraph.swift +++ b/Sources/PNDependencyGraph/PNDependencyGraph.swift @@ -1,12 +1,19 @@ import Foundation -public enum PNCompilationError: Error { - case cycle -} - +/// The main class for building and compiling dependency graphs. +/// +/// This class provides methods to add nodes, define dependencies between them, +/// and compile the graph into a topologically sorted order. public final class PNGraph { + /// A dictionary of all nodes in the graph, keyed by their identifiers. private var nodes: [String: PNNode] = [:] + /// Adds a new node to the graph with the specified identifier. + /// + /// If a node with this identifier already exists, it is returned instead of creating a new one. + /// + /// - Parameter identifier: A unique identifier for the node. + /// - Returns: The node associated with the provided identifier. public func add(identifier: String) -> PNNode { if let existing = nodes[identifier] { return existing } let node = PNNode(identifier: identifier) @@ -14,14 +21,26 @@ public final class PNGraph { return node } + /// Initializes an empty dependency graph. public init() { } + /// Retrieves a node from the graph by its identifier. + /// + /// - Parameter identifier: The identifier of the node to retrieve. + /// - Returns: The node with the specified identifier, or `nil` if not found. public func get(identifier: String) -> PNNode? { nodes[identifier] } + /// Compiles the dependency graph into a topologically sorted order. + /// + /// This method performs a depth-first search to detect cycles and generate an execution order. + /// If a cycle is detected, it throws `PNCompilationError.cycle`. + /// + /// - Returns: A compiled graph containing nodes in topological order. + /// - Throws: `PNCompilationError.cycle` if the graph contains a cycle. public func compile() throws -> PNCompiledGraph { var visited: Set = [] var visiting: Set = []