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


背景

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

$ go mod graph
github.com/ryutoyasugi/gomod-tree github.com/inconshreveable/[email protected]
github.com/ryutoyasugi/gomod-tree github.com/spf13/[email protected]
github.com/ryutoyasugi/gomod-tree github.com/spf13/[email protected]
github.com/spf13/[email protected] github.com/cpuguy83/go-md2man/[email protected]
github.com/spf13/[email protected] github.com/inconshreveable/[email protected]
...

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/[email protected]
    - github.com/spf13/[email protected]
        - github.com/cpuguy83/go-md2man/[email protected]
            - github.com/russross/blackfriday/[email protected]
        - github.com/inconshreveable/[email protected]
        - github.com/spf13/[email protected]
        - gopkg.in/[email protected]
            - gopkg.in/[email protected]
    - github.com/spf13/[email protected]

depthの指定もできる

$ gomod-tree -d 1
- github.com/ryutoyasugi/gomod-tree
    - github.com/inconshreveable/[email protected]
    - github.com/spf13/[email protected]
    - github.com/spf13/[email protected]

使った技術

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