|
| 1 | +// Copyright (c) Microsoft Corporation. |
| 2 | +// Licensed under the MIT License. |
| 3 | + |
| 4 | +package pkggraph |
| 5 | + |
| 6 | +import ( |
| 7 | + "fmt" |
| 8 | + "io" |
| 9 | + "strings" |
| 10 | + |
| 11 | + "github.com/ddddddO/gtree" |
| 12 | + "github.com/microsoft/azurelinux/toolkit/tools/internal/logger" |
| 13 | + "github.com/sirupsen/logrus" |
| 14 | +) |
| 15 | + |
| 16 | +const seenNodeSuffix = "... [SEEN]" |
| 17 | + |
| 18 | +// GraphPrinter is a type meant to print a graph in a human-readable format. |
| 19 | +// It uses a depth-first search (DFS) algorithm to traverse the graph and print each node. |
| 20 | +// The printer ignores any cycles in the graph and thus turns the graph into a tree. |
| 21 | +// We use the gtree package to print the tree structure. |
| 22 | +// See NewGraphPrinter for more details on how to customize the printer. |
| 23 | +// |
| 24 | +// Example: |
| 25 | +// |
| 26 | +// Graph structure: |
| 27 | +// |
| 28 | +// A -> B |
| 29 | +// A -> E |
| 30 | +// B -> C |
| 31 | +// B -> D |
| 32 | +// D -> A (loop) |
| 33 | +// |
| 34 | +// Output starting from 'A': |
| 35 | +// A |
| 36 | +// ├── B |
| 37 | +// │ ├── C |
| 38 | +// │ └── D |
| 39 | +// └── E |
| 40 | +type GraphPrinter struct { |
| 41 | + output io.Writer |
| 42 | + printNodesOnce bool |
| 43 | +} |
| 44 | + |
| 45 | +type graphPrinterModifier func(*GraphPrinter) |
| 46 | + |
| 47 | +// loggerOutputWrapper is a wrapper around logrus.Logger to implement the io.Writer interface. |
| 48 | +type loggerOutputWrapper struct { |
| 49 | + logLevel logrus.Level |
| 50 | +} |
| 51 | + |
| 52 | +// gTreeBuilder helps build a 'gtree' package's tree from a graph. |
| 53 | +type gTreeBuilder struct { |
| 54 | + treeRoot *gtree.Node |
| 55 | + seenNodes map[*PkgNode]bool |
| 56 | + printNodesOnce bool |
| 57 | +} |
| 58 | + |
| 59 | +// NewGraphPrinter creates a new GraphPrinter. |
| 60 | +// It accepts a variadic number of 'GraphPrinter*' modifiers to customize the printer's behavior. |
| 61 | +// The default settings are: |
| 62 | +// - output: logrus logger on debug level |
| 63 | +// - printNodesOnce: false |
| 64 | +func NewGraphPrinter(modifiers ...graphPrinterModifier) GraphPrinter { |
| 65 | + printer := GraphPrinter{ |
| 66 | + output: loggerOutputWrapper{ |
| 67 | + logLevel: logrus.DebugLevel, |
| 68 | + }, |
| 69 | + printNodesOnce: false, |
| 70 | + } |
| 71 | + |
| 72 | + for _, modifier := range modifiers { |
| 73 | + if modifier != nil { |
| 74 | + modifier(&printer) |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + return printer |
| 79 | +} |
| 80 | + |
| 81 | +// GraphPrinterOutput is a config modifier passed to the graph printer's constructor |
| 82 | +// to define the output writer for the graph printer. |
| 83 | +func GraphPrinterOutput(output io.Writer) graphPrinterModifier { |
| 84 | + return func(g *GraphPrinter) { |
| 85 | + g.output = output |
| 86 | + } |
| 87 | +} |
| 88 | + |
| 89 | +// GraphPrinterLogOutput is a config modifier passed to the graph printer's constructor |
| 90 | +// making the printer's output be logged at the specified log level. |
| 91 | +func GraphPrinterLogOutput(logLevel logrus.Level) graphPrinterModifier { |
| 92 | + return func(g *GraphPrinter) { |
| 93 | + g.output = loggerOutputWrapper{ |
| 94 | + logLevel: logLevel, |
| 95 | + } |
| 96 | + } |
| 97 | +} |
| 98 | + |
| 99 | +// GraphPrinterPrintOnce is a config modifier passed to the graph printer's constructor |
| 100 | +// to define whether the printer should print each node only once. |
| 101 | +func GraphPrinterPrintNodesOnce() graphPrinterModifier { |
| 102 | + return func(g *GraphPrinter) { |
| 103 | + g.printNodesOnce = true |
| 104 | + } |
| 105 | +} |
| 106 | + |
| 107 | +// Print prints the graph. It ignores any cycles in the graph turning the graph into a tree. |
| 108 | +// It then uses the 'gtree' package to print the tree structure. |
| 109 | +func (g GraphPrinter) Print(graph *PkgGraph, rootNode *PkgNode) error { |
| 110 | + if graph == nil { |
| 111 | + return fmt.Errorf("graph is nil") |
| 112 | + } |
| 113 | + |
| 114 | + if rootNode == nil { |
| 115 | + return fmt.Errorf("root node is nil") |
| 116 | + } |
| 117 | + |
| 118 | + if !graph.HasNode(rootNode) { |
| 119 | + return fmt.Errorf("root node '%s' not found in the graph", rootNode.FriendlyName()) |
| 120 | + } |
| 121 | + |
| 122 | + treeBuilder := newGTreeBuilder(g.printNodesOnce) |
| 123 | + treeRoot, err := treeBuilder.buildTree(graph, rootNode) |
| 124 | + if err != nil { |
| 125 | + return fmt.Errorf("failed to build tree:\n%w", err) |
| 126 | + } |
| 127 | + |
| 128 | + err = gtree.OutputProgrammably(g.output, treeRoot) |
| 129 | + if err != nil { |
| 130 | + return fmt.Errorf("failed to print tree:\n%w", err) |
| 131 | + } |
| 132 | + |
| 133 | + return nil |
| 134 | +} |
| 135 | + |
| 136 | +// Write implements the io.Writer interface. |
| 137 | +func (l loggerOutputWrapper) Write(bytes []byte) (int, error) { |
| 138 | + // Remove the trailing newline character from the log message, |
| 139 | + // as it's unnecessary when logging. |
| 140 | + line := strings.TrimSuffix(string(bytes), "\n") |
| 141 | + logger.Log.Log(l.logLevel, line) |
| 142 | + return len(bytes), nil |
| 143 | +} |
| 144 | + |
| 145 | +// newGTreeBuilder creates a new gTreeBuilder instance with the specified |
| 146 | +// configuration for printing nodes once. |
| 147 | +func newGTreeBuilder(printNodesOnce bool) *gTreeBuilder { |
| 148 | + result := &gTreeBuilder{ |
| 149 | + printNodesOnce: printNodesOnce, |
| 150 | + } |
| 151 | + result.resetState() |
| 152 | + return result |
| 153 | +} |
| 154 | + |
| 155 | +// buildTree traverses the graph and constructs a tree representation. |
| 156 | +func (t *gTreeBuilder) buildTree(graph *PkgGraph, rootNode *PkgNode) (*gtree.Node, error) { |
| 157 | + if graph == nil { |
| 158 | + return nil, fmt.Errorf("graph is nil") |
| 159 | + } |
| 160 | + |
| 161 | + if rootNode == nil { |
| 162 | + return nil, fmt.Errorf("root node is nil") |
| 163 | + } |
| 164 | + |
| 165 | + t.resetState() |
| 166 | + t.buildTreeWithDFS(nil, rootNode, graph) |
| 167 | + |
| 168 | + return t.treeRoot, nil |
| 169 | +} |
| 170 | + |
| 171 | +func (tb *gTreeBuilder) resetState() { |
| 172 | + tb.seenNodes = make(map[*PkgNode]bool) |
| 173 | + tb.treeRoot = nil |
| 174 | +} |
| 175 | + |
| 176 | +// buildTreeWithDFS builds the tree using depth-first search. |
| 177 | +// It converts a general graph into a tree structure. |
| 178 | +// It uses a map to keep track of seen nodes to avoid cycles. |
| 179 | +func (t *gTreeBuilder) buildTreeWithDFS(treeParent *gtree.Node, pkgNode *PkgNode, graph *PkgGraph) { |
| 180 | + if pkgNode == nil { |
| 181 | + return |
| 182 | + } |
| 183 | + |
| 184 | + // We add a node before the "seen" check because we always |
| 185 | + // want to add the node to the tree. If it's been seen before, |
| 186 | + // we just mark it as seen as part of the text displayed for the node. |
| 187 | + treeNode := t.buildTreeNode(treeParent, pkgNode) |
| 188 | + |
| 189 | + if t.seenNodes[pkgNode] { |
| 190 | + return |
| 191 | + } |
| 192 | + |
| 193 | + t.seenNodes[pkgNode] = true |
| 194 | + |
| 195 | + children := graph.From(pkgNode.ID()) |
| 196 | + for children.Next() { |
| 197 | + t.buildTreeWithDFS(treeNode, children.Node().(*PkgNode), graph) |
| 198 | + } |
| 199 | + |
| 200 | + // As we traverse the graph back up, setting the node as unseen |
| 201 | + // allows us to print it again if we encounter it later |
| 202 | + // in a DIFFERENT branch of the tree. |
| 203 | + if !t.printNodesOnce { |
| 204 | + t.seenNodes[pkgNode] = false |
| 205 | + } |
| 206 | +} |
| 207 | + |
| 208 | +// buildTreeNode creates a new tree node and adds it to the parent |
| 209 | +// or sets it as the root if the parent is nil. |
| 210 | +func (t *gTreeBuilder) buildTreeNode(treeParent *gtree.Node, pkgNode *PkgNode) *gtree.Node { |
| 211 | + nodeText := t.buildNodeText(pkgNode) |
| 212 | + if treeParent == nil { |
| 213 | + t.treeRoot = gtree.NewRoot(nodeText) |
| 214 | + return t.treeRoot |
| 215 | + } |
| 216 | + return treeParent.Add(nodeText) |
| 217 | +} |
| 218 | + |
| 219 | +// buildNodeText formats the node text based on whether it's been seen before. |
| 220 | +func (t *gTreeBuilder) buildNodeText(pkgNode *PkgNode) string { |
| 221 | + if t.seenNodes[pkgNode] { |
| 222 | + return pkgNode.FriendlyName() + seenNodeSuffix |
| 223 | + } |
| 224 | + return pkgNode.FriendlyName() |
| 225 | +} |
0 commit comments