github.com/tidwall/go@v0.0.0-20170415222209-6694a6888b7d/src/cmd/doc/main.go (about) 1 // Copyright 2015 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 // Doc (usually run as go doc) accepts zero, one or two arguments. 6 // 7 // Zero arguments: 8 // go doc 9 // Show the documentation for the package in the current directory. 10 // 11 // One argument: 12 // go doc <pkg> 13 // go doc <sym>[.<methodOrField>] 14 // go doc [<pkg>.]<sym>[.<methodOrField>] 15 // go doc [<pkg>.][<sym>.]<methodOrField> 16 // The first item in this list that succeeds is the one whose documentation 17 // is printed. If there is a symbol but no package, the package in the current 18 // directory is chosen. However, if the argument begins with a capital 19 // letter it is always assumed to be a symbol in the current directory. 20 // 21 // Two arguments: 22 // go doc <pkg> <sym>[.<methodOrField>] 23 // 24 // Show the documentation for the package, symbol, and method or field. The 25 // first argument must be a full package path. This is similar to the 26 // command-line usage for the godoc command. 27 // 28 // For commands, unless the -cmd flag is present "go doc command" 29 // shows only the package-level docs for the package. 30 // 31 // For complete documentation, run "go help doc". 32 package main 33 34 import ( 35 "bytes" 36 "flag" 37 "fmt" 38 "go/build" 39 "io" 40 "log" 41 "os" 42 "path/filepath" 43 "strings" 44 "unicode" 45 "unicode/utf8" 46 ) 47 48 var ( 49 unexported bool // -u flag 50 matchCase bool // -c flag 51 showCmd bool // -cmd flag 52 ) 53 54 // usage is a replacement usage function for the flags package. 55 func usage() { 56 fmt.Fprintf(os.Stderr, "Usage of [go] doc:\n") 57 fmt.Fprintf(os.Stderr, "\tgo doc\n") 58 fmt.Fprintf(os.Stderr, "\tgo doc <pkg>\n") 59 fmt.Fprintf(os.Stderr, "\tgo doc <sym>[.<method>]\n") 60 fmt.Fprintf(os.Stderr, "\tgo doc [<pkg>].<sym>[.<method>]\n") 61 fmt.Fprintf(os.Stderr, "\tgo doc <pkg> <sym>[.<method>]\n") 62 fmt.Fprintf(os.Stderr, "For more information run\n") 63 fmt.Fprintf(os.Stderr, "\tgo help doc\n\n") 64 fmt.Fprintf(os.Stderr, "Flags:\n") 65 flag.PrintDefaults() 66 os.Exit(2) 67 } 68 69 func main() { 70 log.SetFlags(0) 71 log.SetPrefix("doc: ") 72 err := do(os.Stdout, flag.CommandLine, os.Args[1:]) 73 if err != nil { 74 log.Fatal(err) 75 } 76 } 77 78 // do is the workhorse, broken out of main to make testing easier. 79 func do(writer io.Writer, flagSet *flag.FlagSet, args []string) (err error) { 80 flagSet.Usage = usage 81 unexported = false 82 matchCase = false 83 flagSet.BoolVar(&unexported, "u", false, "show unexported symbols as well as exported") 84 flagSet.BoolVar(&matchCase, "c", false, "symbol matching honors case (paths not affected)") 85 flagSet.BoolVar(&showCmd, "cmd", false, "show symbols with package docs even if package is a command") 86 flagSet.Parse(args) 87 var paths []string 88 var symbol, method string 89 // Loop until something is printed. 90 dirs.Reset() 91 for i := 0; ; i++ { 92 buildPackage, userPath, sym, more := parseArgs(flagSet.Args()) 93 if i > 0 && !more { // Ignore the "more" bit on the first iteration. 94 return failMessage(paths, symbol, method) 95 } 96 symbol, method = parseSymbol(sym) 97 pkg := parsePackage(writer, buildPackage, userPath) 98 paths = append(paths, pkg.prettyPath()) 99 100 defer func() { 101 pkg.flush() 102 e := recover() 103 if e == nil { 104 return 105 } 106 pkgError, ok := e.(PackageError) 107 if ok { 108 err = pkgError 109 return 110 } 111 panic(e) 112 }() 113 114 // The builtin package needs special treatment: its symbols are lower 115 // case but we want to see them, always. 116 if pkg.build.ImportPath == "builtin" { 117 unexported = true 118 } 119 120 switch { 121 case symbol == "": 122 pkg.packageDoc() // The package exists, so we got some output. 123 return 124 case method == "": 125 if pkg.symbolDoc(symbol) { 126 return 127 } 128 default: 129 if pkg.methodDoc(symbol, method) { 130 return 131 } 132 if pkg.fieldDoc(symbol, method) { 133 return 134 } 135 } 136 } 137 } 138 139 // failMessage creates a nicely formatted error message when there is no result to show. 140 func failMessage(paths []string, symbol, method string) error { 141 var b bytes.Buffer 142 if len(paths) > 1 { 143 b.WriteString("s") 144 } 145 b.WriteString(" ") 146 for i, path := range paths { 147 if i > 0 { 148 b.WriteString(", ") 149 } 150 b.WriteString(path) 151 } 152 if method == "" { 153 return fmt.Errorf("no symbol %s in package%s", symbol, &b) 154 } 155 return fmt.Errorf("no method or field %s.%s in package%s", symbol, method, &b) 156 } 157 158 // parseArgs analyzes the arguments (if any) and returns the package 159 // it represents, the part of the argument the user used to identify 160 // the path (or "" if it's the current package) and the symbol 161 // (possibly with a .method) within that package. 162 // parseSymbol is used to analyze the symbol itself. 163 // The boolean final argument reports whether it is possible that 164 // there may be more directories worth looking at. It will only 165 // be true if the package path is a partial match for some directory 166 // and there may be more matches. For example, if the argument 167 // is rand.Float64, we must scan both crypto/rand and math/rand 168 // to find the symbol, and the first call will return crypto/rand, true. 169 func parseArgs(args []string) (pkg *build.Package, path, symbol string, more bool) { 170 switch len(args) { 171 default: 172 usage() 173 case 0: 174 // Easy: current directory. 175 return importDir(pwd()), "", "", false 176 case 1: 177 // Done below. 178 case 2: 179 // Package must be importable. 180 pkg, err := build.Import(args[0], "", build.ImportComment) 181 if err != nil { 182 log.Fatalf("%s", err) 183 } 184 return pkg, args[0], args[1], false 185 } 186 // Usual case: one argument. 187 arg := args[0] 188 // If it contains slashes, it begins with a package path. 189 // First, is it a complete package path as it is? If so, we are done. 190 // This avoids confusion over package paths that have other 191 // package paths as their prefix. 192 pkg, err := build.Import(arg, "", build.ImportComment) 193 if err == nil { 194 return pkg, arg, "", false 195 } 196 // Another disambiguator: If the symbol starts with an upper 197 // case letter, it can only be a symbol in the current directory. 198 // Kills the problem caused by case-insensitive file systems 199 // matching an upper case name as a package name. 200 if isUpper(arg) { 201 pkg, err := build.ImportDir(".", build.ImportComment) 202 if err == nil { 203 return pkg, "", arg, false 204 } 205 } 206 // If it has a slash, it must be a package path but there is a symbol. 207 // It's the last package path we care about. 208 slash := strings.LastIndex(arg, "/") 209 // There may be periods in the package path before or after the slash 210 // and between a symbol and method. 211 // Split the string at various periods to see what we find. 212 // In general there may be ambiguities but this should almost always 213 // work. 214 var period int 215 // slash+1: if there's no slash, the value is -1 and start is 0; otherwise 216 // start is the byte after the slash. 217 for start := slash + 1; start < len(arg); start = period + 1 { 218 period = strings.Index(arg[start:], ".") 219 symbol := "" 220 if period < 0 { 221 period = len(arg) 222 } else { 223 period += start 224 symbol = arg[period+1:] 225 } 226 // Have we identified a package already? 227 pkg, err := build.Import(arg[0:period], "", build.ImportComment) 228 if err == nil { 229 return pkg, arg[0:period], symbol, false 230 } 231 // See if we have the basename or tail of a package, as in json for encoding/json 232 // or ivy/value for robpike.io/ivy/value. 233 // Launch findPackage as a goroutine so it can return multiple paths if required. 234 path, ok := findPackage(arg[0:period]) 235 if ok { 236 return importDir(path), arg[0:period], symbol, true 237 } 238 dirs.Reset() // Next iteration of for loop must scan all the directories again. 239 } 240 // If it has a slash, we've failed. 241 if slash >= 0 { 242 log.Fatalf("no such package %s", arg[0:period]) 243 } 244 // Guess it's a symbol in the current directory. 245 return importDir(pwd()), "", arg, false 246 } 247 248 // importDir is just an error-catching wrapper for build.ImportDir. 249 func importDir(dir string) *build.Package { 250 pkg, err := build.ImportDir(dir, build.ImportComment) 251 if err != nil { 252 log.Fatal(err) 253 } 254 return pkg 255 } 256 257 // parseSymbol breaks str apart into a symbol and method. 258 // Both may be missing or the method may be missing. 259 // If present, each must be a valid Go identifier. 260 func parseSymbol(str string) (symbol, method string) { 261 if str == "" { 262 return 263 } 264 elem := strings.Split(str, ".") 265 switch len(elem) { 266 case 1: 267 case 2: 268 method = elem[1] 269 isIdentifier(method) 270 default: 271 log.Printf("too many periods in symbol specification") 272 usage() 273 } 274 symbol = elem[0] 275 isIdentifier(symbol) 276 return 277 } 278 279 // isIdentifier checks that the name is valid Go identifier, and 280 // logs and exits if it is not. 281 func isIdentifier(name string) { 282 if len(name) == 0 { 283 log.Fatal("empty symbol") 284 } 285 for i, ch := range name { 286 if unicode.IsLetter(ch) || ch == '_' || i > 0 && unicode.IsDigit(ch) { 287 continue 288 } 289 log.Fatalf("invalid identifier %q", name) 290 } 291 } 292 293 // isExported reports whether the name is an exported identifier. 294 // If the unexported flag (-u) is true, isExported returns true because 295 // it means that we treat the name as if it is exported. 296 func isExported(name string) bool { 297 return unexported || isUpper(name) 298 } 299 300 // isUpper reports whether the name starts with an upper case letter. 301 func isUpper(name string) bool { 302 ch, _ := utf8.DecodeRuneInString(name) 303 return unicode.IsUpper(ch) 304 } 305 306 // findPackage returns the full file name path that first matches the 307 // (perhaps partial) package path pkg. The boolean reports if any match was found. 308 func findPackage(pkg string) (string, bool) { 309 if pkg == "" || isUpper(pkg) { // Upper case symbol cannot be a package name. 310 return "", false 311 } 312 pkgString := filepath.Clean(string(filepath.Separator) + pkg) 313 for { 314 path, ok := dirs.Next() 315 if !ok { 316 return "", false 317 } 318 if strings.HasSuffix(path, pkgString) { 319 return path, true 320 } 321 } 322 } 323 324 // splitGopath splits $GOPATH into a list of roots. 325 func splitGopath() []string { 326 return filepath.SplitList(build.Default.GOPATH) 327 } 328 329 // pwd returns the current directory. 330 func pwd() string { 331 wd, err := os.Getwd() 332 if err != nil { 333 log.Fatal(err) 334 } 335 return wd 336 }