🌲

go modの依存関係をツリー表示するコマンドを作った

2022/04/03に公開

背景

脆弱性対応とかでパッケージの依存関係を見たい時がある
go modでパッケージ管理をしていればgo mod graphが使えるが、親子関係がペアで表示されるシンプルな作りになってる

$ go mod graph
github.com/ryutoyasugi/gomod-tree github.com/inconshreveable/mousetrap@v1.0.0
github.com/ryutoyasugi/gomod-tree github.com/spf13/cobra@v1.4.0
github.com/ryutoyasugi/gomod-tree github.com/spf13/pflag@v1.0.5
github.com/spf13/cobra@v1.4.0 github.com/cpuguy83/go-md2man/v2@v2.0.1
github.com/spf13/cobra@v1.4.0 github.com/inconshreveable/mousetrap@v1.0.0
...

npm listみたいな感じのツリー表示で見たいなあと思ったのでコマンドを作った

作ったもの

https://github.com/ryutoyasugi/gomod-tree

$ go install github.com/ryutoyasugi/gomod-tree@latest

$ gomod-tree
- github.com/ryutoyasugi/gomod-tree
    - github.com/inconshreveable/mousetrap@v1.0.0
    - github.com/spf13/cobra@v1.4.0
        - github.com/cpuguy83/go-md2man/v2@v2.0.1
            - github.com/russross/blackfriday/v2@v2.1.0
        - github.com/inconshreveable/mousetrap@v1.0.0
        - github.com/spf13/pflag@v1.0.5
        - gopkg.in/yaml.v2@v2.4.0
            - gopkg.in/check.v1@v0.0.0-20161208181325-20d25e280405
    - github.com/spf13/pflag@v1.0.5

depthの指定もできる

$ gomod-tree -d 1
- github.com/ryutoyasugi/gomod-tree
    - github.com/inconshreveable/mousetrap@v1.0.0
    - github.com/spf13/cobra@v1.4.0
    - github.com/spf13/pflag@v1.0.5

使った技術

https://github.com/spf13/cobra
cobraを使えばCLIが簡単に作れます

$ go mod init
$ go install github.com/spf13/cobra-cli@latest
$ cobra-cli init # 設定ファイルが不要であれば--viper=falseをつける
$ tree
.
├── LICENSE
├── cmd
│   └── root.go
├── go.mod
├── go.sum
└── main.go
root.go
-    // Run: func(cmd *cobra.Command, args []string) { },
+    Run: func(cmd *cobra.Command, args []string) {
+        fmt.Println("Hello World!")
+    },
$ go run main.go
Hello World!

ヘルプまで追加されてます

$ go run main.go -h
A longer description that spans multiple lines and likely contains
examples and usage of using your application. For example:

Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.

Usage:
  sample [flags]
  sample [command]

Available Commands:
  completion  Generate the autocompletion script for the specified shell
  foo         A brief description of your command
  help        Help about any command

Flags:
  -h, --help     help for sample
  -t, --toggle   Help message for toggle

Use "sample [command] --help" for more information about a command.

サブコマンドの追加方法

$ cobra-cli add foo
$ ls cmd
./       ../      foo.go   root.go

$ go run main.go foo
foo called

Discussion