github.com/megatontech/mynoteforgo@v0.0.0-20200507084910-5d0c6ea6e890/源码/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 // The -src flag causes doc to print the full source code for the symbol, such 32 // as the body of a struct, function or method. 33 // 34 // The -all flag causes doc to print all documentation for the package and 35 // all its visible symbols. The argument must identify a package. 36 // 37 // For complete documentation, run "go help doc". 38 package main 39 40 import ( 41 "bytes" 42 "flag" 43 "fmt" 44 "go/build" 45 "io" 46 "log" 47 "os" 48 "path" 49 "path/filepath" 50 "strings" 51 "unicode" 52 "unicode/utf8" 53 ) 54 55 var ( 56 unexported bool // -u flag 57 matchCase bool // -c flag 58 showAll bool // -all flag 59 showCmd bool // -cmd flag 60 showSrc bool // -src flag 61 ) 62 63 // usage is a replacement usage function for the flags package. 64 func usage() { 65 fmt.Fprintf(os.Stderr, "Usage of [go] doc:\n") 66 fmt.Fprintf(os.Stderr, "\tgo doc\n") 67 fmt.Fprintf(os.Stderr, "\tgo doc <pkg>\n") 68 fmt.Fprintf(os.Stderr, "\tgo doc <sym>[.<method>]\n") 69 fmt.Fprintf(os.Stderr, "\tgo doc [<pkg>].<sym>[.<method>]\n") 70 fmt.Fprintf(os.Stderr, "\tgo doc <pkg> <sym>[.<method>]\n") 71 fmt.Fprintf(os.Stderr, "For more information run\n") 72 fmt.Fprintf(os.Stderr, "\tgo help doc\n\n") 73 fmt.Fprintf(os.Stderr, "Flags:\n") 74 flag.PrintDefaults() 75 os.Exit(2) 76 } 77 78 func main() { 79 log.SetFlags(0) 80 log.SetPrefix("doc: ") 81 dirsInit() 82 err := do(os.Stdout, flag.CommandLine, os.Args[1:]) 83 if err != nil { 84 log.Fatal(err) 85 } 86 } 87 88 // do is the workhorse, broken out of main to make testing easier. 89 func do(writer io.Writer, flagSet *flag.FlagSet, args []string) (err error) { 90 flagSet.Usage = usage 91 unexported = false 92 matchCase = false 93 flagSet.BoolVar(&unexported, "u", false, "show unexported symbols as well as exported") 94 flagSet.BoolVar(&matchCase, "c", false, "symbol matching honors case (paths not affected)") 95 flagSet.BoolVar(&showAll, "all", false, "show all documentation for package") 96 flagSet.BoolVar(&showCmd, "cmd", false, "show symbols with package docs even if package is a command") 97 flagSet.BoolVar(&showSrc, "src", false, "show source code for symbol") 98 flagSet.Parse(args) 99 var paths []string 100 var symbol, method string 101 // Loop until something is printed. 102 dirs.Reset() 103 for i := 0; ; i++ { 104 buildPackage, userPath, sym, more := parseArgs(flagSet.Args()) 105 if i > 0 && !more { // Ignore the "more" bit on the first iteration. 106 return failMessage(paths, symbol, method) 107 } 108 if buildPackage == nil { 109 return fmt.Errorf("no such package: %s", userPath) 110 } 111 symbol, method = parseSymbol(sym) 112 pkg := parsePackage(writer, buildPackage, userPath) 113 paths = append(paths, pkg.prettyPath()) 114 115 defer func() { 116 pkg.flush() 117 e := recover() 118 if e == nil { 119 return 120 } 121 pkgError, ok := e.(PackageError) 122 if ok { 123 err = pkgError 124 return 125 } 126 panic(e) 127 }() 128 129 // The builtin package needs special treatment: its symbols are lower 130 // case but we want to see them, always. 131 if pkg.build.ImportPath == "builtin" { 132 unexported = true 133 } 134 135 // We have a package. 136 if showAll && symbol == "" { 137 pkg.allDoc() 138 return 139 } 140 141 switch { 142 case symbol == "": 143 pkg.packageDoc() // The package exists, so we got some output. 144 return 145 case method == "": 146 if pkg.symbolDoc(symbol) { 147 return 148 } 149 default: 150 if pkg.methodDoc(symbol, method) { 151 return 152 } 153 if pkg.fieldDoc(symbol, method) { 154 return 155 } 156 } 157 } 158 } 159 160 // failMessage creates a nicely formatted error message when there is no result to show. 161 func failMessage(paths []string, symbol, method string) error { 162 var b bytes.Buffer 163 if len(paths) > 1 { 164 b.WriteString("s") 165 } 166 b.WriteString(" ") 167 for i, path := range paths { 168 if i > 0 { 169 b.WriteString(", ") 170 } 171 b.WriteString(path) 172 } 173 if method == "" { 174 return fmt.Errorf("no symbol %s in package%s", symbol, &b) 175 } 176 return fmt.Errorf("no method or field %s.%s in package%s", symbol, method, &b) 177 } 178 179 // parseArgs analyzes the arguments (if any) and returns the package 180 // it represents, the part of the argument the user used to identify 181 // the path (or "" if it's the current package) and the symbol 182 // (possibly with a .method) within that package. 183 // parseSymbol is used to analyze the symbol itself. 184 // The boolean final argument reports whether it is possible that 185 // there may be more directories worth looking at. It will only 186 // be true if the package path is a partial match for some directory 187 // and there may be more matches. For example, if the argument 188 // is rand.Float64, we must scan both crypto/rand and math/rand 189 // to find the symbol, and the first call will return crypto/rand, true. 190 func parseArgs(args []string) (pkg *build.Package, path, symbol string, more bool) { 191 if len(args) == 0 { 192 // Easy: current directory. 193 return importDir(pwd()), "", "", false 194 } 195 arg := args[0] 196 // We have an argument. If it is a directory name beginning with . or .., 197 // use the absolute path name. This discriminates "./errors" from "errors" 198 // if the current directory contains a non-standard errors package. 199 if isDotSlash(arg) { 200 arg = filepath.Join(pwd(), arg) 201 } 202 switch len(args) { 203 default: 204 usage() 205 case 1: 206 // Done below. 207 case 2: 208 // Package must be findable and importable. 209 pkg, err := build.Import(args[0], "", build.ImportComment) 210 if err == nil { 211 return pkg, args[0], args[1], false 212 } 213 for { 214 packagePath, ok := findNextPackage(arg) 215 if !ok { 216 break 217 } 218 if pkg, err := build.ImportDir(packagePath, build.ImportComment); err == nil { 219 return pkg, arg, args[1], true 220 } 221 } 222 return nil, args[0], args[1], false 223 } 224 // Usual case: one argument. 225 // If it contains slashes, it begins with a package path. 226 // First, is it a complete package path as it is? If so, we are done. 227 // This avoids confusion over package paths that have other 228 // package paths as their prefix. 229 pkg, err := build.Import(arg, "", build.ImportComment) 230 if err == nil { 231 return pkg, arg, "", false 232 } 233 // Another disambiguator: If the symbol starts with an upper 234 // case letter, it can only be a symbol in the current directory. 235 // Kills the problem caused by case-insensitive file systems 236 // matching an upper case name as a package name. 237 if isUpper(arg) { 238 pkg, err := build.ImportDir(".", build.ImportComment) 239 if err == nil { 240 return pkg, "", arg, false 241 } 242 } 243 // If it has a slash, it must be a package path but there is a symbol. 244 // It's the last package path we care about. 245 slash := strings.LastIndex(arg, "/") 246 // There may be periods in the package path before or after the slash 247 // and between a symbol and method. 248 // Split the string at various periods to see what we find. 249 // In general there may be ambiguities but this should almost always 250 // work. 251 var period int 252 // slash+1: if there's no slash, the value is -1 and start is 0; otherwise 253 // start is the byte after the slash. 254 for start := slash + 1; start < len(arg); start = period + 1 { 255 period = strings.Index(arg[start:], ".") 256 symbol := "" 257 if period < 0 { 258 period = len(arg) 259 } else { 260 period += start 261 symbol = arg[period+1:] 262 } 263 // Have we identified a package already? 264 pkg, err := build.Import(arg[0:period], "", build.ImportComment) 265 if err == nil { 266 return pkg, arg[0:period], symbol, false 267 } 268 // See if we have the basename or tail of a package, as in json for encoding/json 269 // or ivy/value for robpike.io/ivy/value. 270 pkgName := arg[:period] 271 for { 272 path, ok := findNextPackage(pkgName) 273 if !ok { 274 break 275 } 276 if pkg, err = build.ImportDir(path, build.ImportComment); err == nil { 277 return pkg, arg[0:period], symbol, true 278 } 279 } 280 dirs.Reset() // Next iteration of for loop must scan all the directories again. 281 } 282 // If it has a slash, we've failed. 283 if slash >= 0 { 284 log.Fatalf("no such package %s", arg[0:period]) 285 } 286 // Guess it's a symbol in the current directory. 287 return importDir(pwd()), "", arg, false 288 } 289 290 // dotPaths lists all the dotted paths legal on Unix-like and 291 // Windows-like file systems. We check them all, as the chance 292 // of error is minute and even on Windows people will use ./ 293 // sometimes. 294 var dotPaths = []string{ 295 `./`, 296 `../`, 297 `.\`, 298 `..\`, 299 } 300 301 // isDotSlash reports whether the path begins with a reference 302 // to the local . or .. directory. 303 func isDotSlash(arg string) bool { 304 if arg == "." || arg == ".." { 305 return true 306 } 307 for _, dotPath := range dotPaths { 308 if strings.HasPrefix(arg, dotPath) { 309 return true 310 } 311 } 312 return false 313 } 314 315 // importDir is just an error-catching wrapper for build.ImportDir. 316 func importDir(dir string) *build.Package { 317 pkg, err := build.ImportDir(dir, build.ImportComment) 318 if err != nil { 319 log.Fatal(err) 320 } 321 return pkg 322 } 323 324 // parseSymbol breaks str apart into a symbol and method. 325 // Both may be missing or the method may be missing. 326 // If present, each must be a valid Go identifier. 327 func parseSymbol(str string) (symbol, method string) { 328 if str == "" { 329 return 330 } 331 elem := strings.Split(str, ".") 332 switch len(elem) { 333 case 1: 334 case 2: 335 method = elem[1] 336 isIdentifier(method) 337 default: 338 log.Printf("too many periods in symbol specification") 339 usage() 340 } 341 symbol = elem[0] 342 isIdentifier(symbol) 343 return 344 } 345 346 // isIdentifier checks that the name is valid Go identifier, and 347 // logs and exits if it is not. 348 func isIdentifier(name string) { 349 if len(name) == 0 { 350 log.Fatal("empty symbol") 351 } 352 for i, ch := range name { 353 if unicode.IsLetter(ch) || ch == '_' || i > 0 && unicode.IsDigit(ch) { 354 continue 355 } 356 log.Fatalf("invalid identifier %q", name) 357 } 358 } 359 360 // isExported reports whether the name is an exported identifier. 361 // If the unexported flag (-u) is true, isExported returns true because 362 // it means that we treat the name as if it is exported. 363 func isExported(name string) bool { 364 return unexported || isUpper(name) 365 } 366 367 // isUpper reports whether the name starts with an upper case letter. 368 func isUpper(name string) bool { 369 ch, _ := utf8.DecodeRuneInString(name) 370 return unicode.IsUpper(ch) 371 } 372 373 // findNextPackage returns the next full file name path that matches the 374 // (perhaps partial) package path pkg. The boolean reports if any match was found. 375 func findNextPackage(pkg string) (string, bool) { 376 if pkg == "" || isUpper(pkg) { // Upper case symbol cannot be a package name. 377 return "", false 378 } 379 if filepath.IsAbs(pkg) { 380 if dirs.offset == 0 { 381 dirs.offset = -1 382 return pkg, true 383 } 384 return "", false 385 } 386 pkg = path.Clean(pkg) 387 pkgSuffix := "/" + pkg 388 for { 389 d, ok := dirs.Next() 390 if !ok { 391 return "", false 392 } 393 if d.importPath == pkg || strings.HasSuffix(d.importPath, pkgSuffix) { 394 return d.dir, true 395 } 396 } 397 } 398 399 var buildCtx = build.Default 400 401 // splitGopath splits $GOPATH into a list of roots. 402 func splitGopath() []string { 403 return filepath.SplitList(buildCtx.GOPATH) 404 } 405 406 // pwd returns the current directory. 407 func pwd() string { 408 wd, err := os.Getwd() 409 if err != nil { 410 log.Fatal(err) 411 } 412 return wd 413 }