// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. /* The digraph command performs queries over unlabelled directed graphs represented in text form. It is intended to integrate nicely with typical UNIX command pipelines. Usage: your-application | digraph [command] The support commands are: nodes the set of all nodes degree the in-degree and out-degree of each node transpose the reverse of the input edges preds ... the set of immediate predecessors of the specified nodes succs ... the set of immediate successors of the specified nodes forward ... the set of nodes transitively reachable from the specified nodes reverse ... the set of nodes that transitively reach the specified nodes somepath the list of nodes on some arbitrary path from the first node to the second allpaths the set of nodes on all paths from the first node to the second sccs all strongly connected components (one per line) scc the set of nodes nodes strongly connected to the specified one Input format: Each line contains zero or more words. Words are separated by unquoted whitespace; words may contain Go-style double-quoted portions, allowing spaces and other characters to be expressed. Each word declares a node, and if there are more than one, an edge from the first to each subsequent one. The graph is provided on the standard input. For instance, the following (acyclic) graph specifies a partial order among the subtasks of getting dressed: $ cat clothes.txt socks shoes "boxer shorts" pants pants belt shoes shirt tie sweater sweater jacket hat The line "shirt tie sweater" indicates the two edges shirt -> tie and shirt -> sweater, not shirt -> tie -> sweater. Example usage: Using digraph with existing Go tools: $ go mod graph | digraph nodes # Operate on the Go module graph. $ go list -m all | digraph nodes # Operate on the Go package graph. Show the transitive closure of imports of the digraph tool itself: $ go list -f '{{.ImportPath}} {{join .Imports " "}}' ... | digraph forward golang.org/x/tools/cmd/digraph Show which clothes (see above) must be donned before a jacket: $ digraph reverse jacket */ package main // import "golang.org/x/tools/cmd/digraph" // TODO(adonovan): // - support input files other than stdin // - support alternative formats (AT&T GraphViz, CSV, etc), // a comment syntax, etc. // - allow queries to nest, like Blaze query language. import ( "bufio" "bytes" "errors" "flag" "fmt" "io" "os" "sort" "strconv" "unicode" "unicode/utf8" ) func usage() { fmt.Fprintf(os.Stderr, `Usage: your-application | digraph [command] The support commands are: nodes the set of all nodes degree the in-degree and out-degree of each node transpose the reverse of the input edges preds ... the set of immediate predecessors of the specified nodes succs ... the set of immediate successors of the specified nodes forward ... the set of nodes transitively reachable from the specified nodes reverse ... the set of nodes that transitively reach the specified nodes somepath the list of nodes on some arbitrary path from the first node to the second allpaths the set of nodes on all paths from the first node to the second sccs all strongly connected components (one per line) scc the set of nodes nodes strongly connected to the specified one `) os.Exit(2) } func main() { flag.Usage = usage flag.Parse() args := flag.Args() if len(args) == 0 { usage() } if err := digraph(args[0], args[1:]); err != nil { fmt.Fprintf(os.Stderr, "digraph: %s\n", err) os.Exit(1) } } type nodelist []string func (l nodelist) println(sep string) { for i, label := range l { if i > 0 { fmt.Fprint(stdout, sep) } fmt.Fprint(stdout, label) } fmt.Fprintln(stdout) } type nodeset map[string]bool func (s nodeset) sort() nodelist { labels := make(nodelist, len(s)) var i int for label := range s { labels[i] = label i++ } sort.Strings(labels) return labels } func (s nodeset) addAll(x nodeset) { for label := range x { s[label] = true } } // A graph maps nodes to the non-nil set of their immediate successors. type graph map[string]nodeset func (g graph) addNode(label string) nodeset { edges := g[label] if edges == nil { edges = make(nodeset) g[label] = edges } return edges } func (g graph) addEdges(from string, to ...string) { edges := g.addNode(from) for _, to := range to { g.addNode(to) edges[to] = true } } func (g graph) reachableFrom(roots nodeset) nodeset { seen := make(nodeset) var visit func(label string) visit = func(label string) { if !seen[label] { seen[label] = true for e := range g[label] { visit(e) } } } for root := range roots { visit(root) } return seen } func (g graph) transpose() graph { rev := make(graph) for label, edges := range g { rev.addNode(label) for succ := range edges { rev.addEdges(succ, label) } } return rev } func (g graph) sccs() []nodeset { // Kosaraju's algorithm---Tarjan is overkill here. // Forward pass. S := make(nodelist, 0, len(g)) // postorder stack seen := make(nodeset) var visit func(label string) visit = func(label string) { if !seen[label] { seen[label] = true for e := range g[label] { visit(e) } S = append(S, label) } } for label := range g { visit(label) } // Reverse pass. rev := g.transpose() var scc nodeset seen = make(nodeset) var rvisit func(label string) rvisit = func(label string) { if !seen[label] { seen[label] = true scc[label] = true for e := range rev[label] { rvisit(e) } } } var sccs []nodeset for len(S) > 0 { top := S[len(S)-1] S = S[:len(S)-1] // pop if !seen[top] { scc = make(nodeset) rvisit(top) sccs = append(sccs, scc) } } return sccs } func (g graph) allpaths(from, to string) error { // Mark all nodes to "to". seen := make(nodeset) // value of seen[x] indicates whether x is on some path to "to" var visit func(node string) bool visit = func(node string) bool { reachesTo, ok := seen[node] if !ok { reachesTo = node == to seen[node] = reachesTo for e := range g[node] { if visit(e) { reachesTo = true } } if reachesTo && node != to { seen[node] = true } } return reachesTo } visit(from) // For each marked node, collect its marked successors. var edges []string for n := range seen { for succ := range g[n] { if seen[succ] { edges = append(edges, n+" "+succ) } } } // Sort (so that this method is deterministic) and print edges. sort.Strings(edges) for _, e := range edges { fmt.Fprintln(stdout, e) } return nil } func (g graph) somepath(from, to string) error { type edge struct{ from, to string } seen := make(nodeset) var dfs func(path []edge, from string) bool dfs = func(path []edge, from string) bool { if !seen[from] { seen[from] = true if from == to { // fmt.Println(path, len(path), cap(path)) // Print and unwind. for _, e := range path { fmt.Fprintln(stdout, e.from+" "+e.to) } return true } for e := range g[from] { if dfs(append(path, edge{from: from, to: e}), e) { return true } } } return false } maxEdgesInGraph := len(g) * (len(g) - 1) if !dfs(make([]edge, 0, maxEdgesInGraph), from) { return fmt.Errorf("no path from %q to %q", from, to) } return nil } func parse(rd io.Reader) (graph, error) { g := make(graph) var linenum int in := bufio.NewScanner(rd) for in.Scan() { linenum++ // Split into words, honoring double-quotes per Go spec. words, err := split(in.Text()) if err != nil { return nil, fmt.Errorf("at line %d: %v", linenum, err) } if len(words) > 0 { g.addEdges(words[0], words[1:]...) } } if err := in.Err(); err != nil { return nil, err } return g, nil } // Overridable for testing purposes. var stdin io.Reader = os.Stdin var stdout io.Writer = os.Stdout func digraph(cmd string, args []string) error { // Parse the input graph. g, err := parse(stdin) if err != nil { return err } // Parse the command line. switch cmd { case "nodes": if len(args) != 0 { return fmt.Errorf("usage: digraph nodes") } nodes := make(nodeset) for label := range g { nodes[label] = true } nodes.sort().println("\n") case "degree": if len(args) != 0 { return fmt.Errorf("usage: digraph degree") } nodes := make(nodeset) for label := range g { nodes[label] = true } rev := g.transpose() for _, label := range nodes.sort() { fmt.Fprintf(stdout, "%d\t%d\t%s\n", len(rev[label]), len(g[label]), label) } case "transpose": if len(args) != 0 { return fmt.Errorf("usage: digraph transpose") } var revEdges []string for node, succs := range g.transpose() { for succ := range succs { revEdges = append(revEdges, fmt.Sprintf("%s %s", node, succ)) } } sort.Strings(revEdges) // make output deterministic for _, e := range revEdges { fmt.Fprintln(stdout, e) } case "succs", "preds": if len(args) == 0 { return fmt.Errorf("usage: digraph %s