Source file src/cmd/doc/main.go

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

View as plain text