gopl-zh.github.com/ch10/ch10-07-6.md

117 lines
3.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

### 10.7.6. 査詢包
`go list`命令可以査詢可用包的信息。其最簡單的形式,可以測試包是否在工作區併打印它的導入路徑:
```
$ go list github.com/go-sql-driver/mysql
github.com/go-sql-driver/mysql
```
`go list`命令的參數還可以用`"..."`表示匹配任意的包的導入路徑。我們可以用它來列表工作區中的所有包:
```
$ go list ...
archive/tar
archive/zip
bufio
bytes
cmd/addr2line
cmd/api
...many more...
```
或者是特定子目録下的所有包:
```
$ go list gopl.io/ch3/...
gopl.io/ch3/basename1
gopl.io/ch3/basename2
gopl.io/ch3/comma
gopl.io/ch3/mandelbrot
gopl.io/ch3/netflag
gopl.io/ch3/printints
gopl.io/ch3/surface
```
或者是和某個主題相關的所有包:
```
$ go list ...xml...
encoding/xml
gopl.io/ch7/xmlselect
```
`go list`命令還可以獲取每個包完整的元信息,而不僅僅隻是導入路徑,這些元信息可以以不同格式提供給用戶。其中`-json`命令行參數表示用JSON格式打印每個包的元信息。
```
$ go list -json hash
{
"Dir": "/home/gopher/go/src/hash",
"ImportPath": "hash",
"Name": "hash",
"Doc": "Package hash provides interfaces for hash functions.",
"Target": "/home/gopher/go/pkg/darwin_amd64/hash.a",
"Goroot": true,
"Standard": true,
"Root": "/home/gopher/go",
"GoFiles": [
"hash.go"
],
"Imports": [
"io"
],
"Deps": [
"errors",
"io",
"runtime",
"sync",
"sync/atomic",
"unsafe"
]
}
```
命令行參數`-f`則允許用戶使用text/template包§4.6的模闆語言定義輸出文本的格式。下面的命令將打印strconv包的依賴的包然後用join模闆函數將結果鏈接爲一行連接時每個結果之間用一個空格分隔
{% raw %}
```
$ go list -f '{{join .Deps " "}}' strconv
errors math runtime unicode/utf8 unsafe
```
{% endraw %}
譯註上面的命令在Windows的命令行運行會遇到`template: main:1: unclosed action`的錯誤。産生這個錯誤的原因是因爲命令行對命令中的`" "`參數進行了轉義處理。可以按照下面的方法解決轉義字符串的問題:
{% raw %}
```
$ go list -f "{{join .Deps \" \"}}" strconv
```
{% endraw %}
下面的命令打印compress子目録下所有包的依賴包列表
{% raw %}
```
$ go list -f '{{.ImportPath}} -> {{join .Imports " "}}' compress/...
compress/bzip2 -> bufio io sort
compress/flate -> bufio fmt io math sort strconv
compress/gzip -> bufio compress/flate errors fmt hash hash/crc32 io time
compress/lzw -> bufio errors fmt io
compress/zlib -> bufio compress/flate errors fmt hash hash/adler32 io
```
{% endraw %}
譯註Windows下有同樣有問題要避免轉義字符串的榦擾
{% raw %}
```
$ go list -f "{{.ImportPath}} -> {{join .Imports \" \"}}" compress/...
```
{% endraw %}
`go list`命令對於一次性的交互式査詢或自動化構建或測試腳本都很有幫助。我們將在11.2.4節中再次使用它。每個子命令的更多信息,包括可設置的字段和意義,可以用`go help list`命令査看。
在本章我們解釋了Go語言工具中除了測試命令之外的所有重要的子命令。在下一章我們將看到如何用`go test`命令去運行Go語言程序中的測試代碼。
**練習 10.4** 創建一個工具,根據命令行指定的參數,報告工作區所有依賴指定包的其它包集合。提示:你需要運行`go list`命令兩次一次用於初始化包一次用於所有包。你可能需要用encoding/json§4.5包來分析輸出的JSON格式的信息。