Black Lives Matter. Support the Equal Justice Initiative.

Source file src/cmd/go/internal/modcmd/graph.go

Documentation: cmd/go/internal/modcmd

     1  // Copyright 2018 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // go mod graph
     6  
     7  package modcmd
     8  
     9  import (
    10  	"bufio"
    11  	"context"
    12  	"os"
    13  
    14  	"cmd/go/internal/base"
    15  	"cmd/go/internal/modload"
    16  
    17  	"golang.org/x/mod/module"
    18  )
    19  
    20  var cmdGraph = &base.Command{
    21  	UsageLine: "go mod graph [-go=version]",
    22  	Short:     "print module requirement graph",
    23  	Long: `
    24  Graph prints the module requirement graph (with replacements applied)
    25  in text form. Each line in the output has two space-separated fields: a module
    26  and one of its requirements. Each module is identified as a string of the form
    27  path@version, except for the main module, which has no @version suffix.
    28  
    29  The -go flag causes graph to report the module graph as loaded by the
    30  given Go version, instead of the version indicated by the 'go' directive
    31  in the go.mod file.
    32  
    33  See https://golang.org/ref/mod#go-mod-graph for more about 'go mod graph'.
    34  	`,
    35  	Run: runGraph,
    36  }
    37  
    38  var (
    39  	graphGo goVersionFlag
    40  )
    41  
    42  func init() {
    43  	cmdGraph.Flag.Var(&graphGo, "go", "")
    44  	base.AddModCommonFlags(&cmdGraph.Flag)
    45  }
    46  
    47  func runGraph(ctx context.Context, cmd *base.Command, args []string) {
    48  	if len(args) > 0 {
    49  		base.Fatalf("go mod graph: graph takes no arguments")
    50  	}
    51  	modload.ForceUseModules = true
    52  	modload.RootMode = modload.NeedRoot
    53  	mg := modload.LoadModGraph(ctx, graphGo.String())
    54  
    55  	w := bufio.NewWriter(os.Stdout)
    56  	defer w.Flush()
    57  
    58  	format := func(m module.Version) {
    59  		w.WriteString(m.Path)
    60  		if m.Version != "" {
    61  			w.WriteString("@")
    62  			w.WriteString(m.Version)
    63  		}
    64  	}
    65  
    66  	mg.WalkBreadthFirst(func(m module.Version) {
    67  		reqs, _ := mg.RequiredBy(m)
    68  		for _, r := range reqs {
    69  			format(m)
    70  			w.WriteByte(' ')
    71  			format(r)
    72  			w.WriteByte('\n')
    73  		}
    74  	})
    75  }
    76  

View as plain text