Source file src/cmd/internal/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  // Package doc provides the implementation of the "go doc" subcommand and cmd/doc.
     6  package doc
     7  
     8  import (
     9  	"bytes"
    10  	"errors"
    11  	"flag"
    12  	"fmt"
    13  	"go/build"
    14  	"go/token"
    15  	"io"
    16  	"log"
    17  	"net"
    18  	"os"
    19  	"os/exec"
    20  	"os/signal"
    21  	"path"
    22  	"path/filepath"
    23  	"strings"
    24  
    25  	"cmd/internal/telemetry/counter"
    26  )
    27  
    28  var (
    29  	unexported bool   // -u flag
    30  	matchCase  bool   // -c flag
    31  	chdir      string // -C flag
    32  	showAll    bool   // -all flag
    33  	showCmd    bool   // -cmd flag
    34  	showSrc    bool   // -src flag
    35  	short      bool   // -short flag
    36  	serveHTTP  bool   // -http flag
    37  )
    38  
    39  // usage is a replacement usage function for the flags package.
    40  func usage(flagSet *flag.FlagSet) {
    41  	fmt.Fprintf(os.Stderr, "Usage of [go] doc:\n")
    42  	fmt.Fprintf(os.Stderr, "\tgo doc\n")
    43  	fmt.Fprintf(os.Stderr, "\tgo doc <pkg>\n")
    44  	fmt.Fprintf(os.Stderr, "\tgo doc <sym>[.<methodOrField>]\n")
    45  	fmt.Fprintf(os.Stderr, "\tgo doc [<pkg>.]<sym>[.<methodOrField>]\n")
    46  	fmt.Fprintf(os.Stderr, "\tgo doc [<pkg>.][<sym>.]<methodOrField>\n")
    47  	fmt.Fprintf(os.Stderr, "\tgo doc <pkg> <sym>[.<methodOrField>]\n")
    48  	fmt.Fprintf(os.Stderr, "For more information run\n")
    49  	fmt.Fprintf(os.Stderr, "\tgo help doc\n\n")
    50  	fmt.Fprintf(os.Stderr, "Flags:\n")
    51  	flagSet.PrintDefaults()
    52  	os.Exit(2)
    53  }
    54  
    55  // Main is the entry point, invoked both by go doc and cmd/doc.
    56  func Main(args []string) {
    57  	log.SetFlags(0)
    58  	log.SetPrefix("doc: ")
    59  	dirsInit()
    60  	var flagSet flag.FlagSet
    61  	err := do(os.Stdout, &flagSet, args)
    62  	if err != nil {
    63  		log.Fatal(err)
    64  	}
    65  }
    66  
    67  // do is the workhorse, broken out of main to make testing easier.
    68  func do(writer io.Writer, flagSet *flag.FlagSet, args []string) (err error) {
    69  	flagSet.Usage = func() { usage(flagSet) }
    70  	unexported = false
    71  	matchCase = false
    72  	flagSet.StringVar(&chdir, "C", "", "change to `dir` before running command")
    73  	flagSet.BoolVar(&unexported, "u", false, "show unexported symbols as well as exported")
    74  	flagSet.BoolVar(&matchCase, "c", false, "symbol matching honors case (paths not affected)")
    75  	flagSet.BoolVar(&showAll, "all", false, "show all documentation for package")
    76  	flagSet.BoolVar(&showCmd, "cmd", false, "show symbols with package docs even if package is a command")
    77  	flagSet.BoolVar(&showSrc, "src", false, "show source code for symbol")
    78  	flagSet.BoolVar(&short, "short", false, "one-line representation for each symbol")
    79  	flagSet.BoolVar(&serveHTTP, "http", false, "serve HTML docs over HTTP")
    80  	flagSet.Parse(args)
    81  	counter.CountFlags("doc/flag:", *flag.CommandLine)
    82  	if chdir != "" {
    83  		if err := os.Chdir(chdir); err != nil {
    84  			return err
    85  		}
    86  	}
    87  	if serveHTTP {
    88  		// Special case: if there are no arguments, try to go to an appropriate page
    89  		// depending on whether we're in a module or workspace. The pkgsite homepage
    90  		// is often not the most useful page.
    91  		if len(flagSet.Args()) == 0 {
    92  			mod, err := runCmd(append(os.Environ(), "GOWORK=off"), "go", "list", "-m")
    93  			if err == nil && mod != "" && mod != "command-line-arguments" {
    94  				// If there's a module, go to the module's doc page.
    95  				return doPkgsite(mod)
    96  			}
    97  			gowork, err := runCmd(nil, "go", "env", "GOWORK")
    98  			if err == nil && gowork != "" {
    99  				// Outside a module, but in a workspace, go to the home page
   100  				// with links to each of the modules' pages.
   101  				return doPkgsite("")
   102  			}
   103  			// Outside a module or workspace, go to the documentation for the standard library.
   104  			return doPkgsite("std")
   105  		}
   106  
   107  		// If args are provided, we need to figure out which page to open on the pkgsite
   108  		// instance. Run the logic below to determine a match for a symbol, method,
   109  		// or field, but don't actually print the documentation to the output.
   110  		writer = io.Discard
   111  	}
   112  	var paths []string
   113  	var symbol, method string
   114  	// Loop until something is printed.
   115  	dirs.Reset()
   116  	for i := 0; ; i++ {
   117  		buildPackage, userPath, sym, more := parseArgs(flagSet, flagSet.Args())
   118  		if i > 0 && !more { // Ignore the "more" bit on the first iteration.
   119  			return failMessage(paths, symbol, method)
   120  		}
   121  		if buildPackage == nil {
   122  			return fmt.Errorf("no such package: %s", userPath)
   123  		}
   124  
   125  		// The builtin package needs special treatment: its symbols are lower
   126  		// case but we want to see them, always.
   127  		if buildPackage.ImportPath == "builtin" {
   128  			unexported = true
   129  		}
   130  
   131  		symbol, method = parseSymbol(flagSet, sym)
   132  		pkg := parsePackage(writer, buildPackage, userPath)
   133  		paths = append(paths, pkg.prettyPath())
   134  
   135  		defer func() {
   136  			pkg.flush()
   137  			e := recover()
   138  			if e == nil {
   139  				return
   140  			}
   141  			pkgError, ok := e.(PackageError)
   142  			if ok {
   143  				err = pkgError
   144  				return
   145  			}
   146  			panic(e)
   147  		}()
   148  
   149  		var found bool
   150  		switch {
   151  		case symbol == "":
   152  			pkg.packageDoc() // The package exists, so we got some output.
   153  			found = true
   154  		case method == "":
   155  			if pkg.symbolDoc(symbol) {
   156  				found = true
   157  			}
   158  		case pkg.printMethodDoc(symbol, method):
   159  			found = true
   160  		case pkg.printFieldDoc(symbol, method):
   161  			found = true
   162  		}
   163  		if found {
   164  			if serveHTTP {
   165  				path, err := objectPath(userPath, pkg, symbol, method)
   166  				if err != nil {
   167  					return err
   168  				}
   169  				return doPkgsite(path)
   170  			}
   171  			return nil
   172  		}
   173  	}
   174  }
   175  
   176  func runCmd(env []string, cmdline ...string) (string, error) {
   177  	var stdout, stderr strings.Builder
   178  	cmd := exec.Command(cmdline[0], cmdline[1:]...)
   179  	cmd.Env = env
   180  	cmd.Stdout = &stdout
   181  	cmd.Stderr = &stderr
   182  	if err := cmd.Run(); err != nil {
   183  		return "", fmt.Errorf("go doc: %s: %v\n%s\n", strings.Join(cmdline, " "), err, stderr.String())
   184  	}
   185  	return strings.TrimSpace(stdout.String()), nil
   186  }
   187  
   188  func objectPath(userPath string, pkg *Package, symbol, method string) (string, error) {
   189  	var err error
   190  	path := pkg.build.ImportPath
   191  	if path == "." {
   192  		// go/build couldn't determine the import path, probably
   193  		// because this was a relative path into a module. Use
   194  		// go list to get the import path.
   195  		path, err = runCmd(nil, "go", "list", userPath)
   196  		if err != nil {
   197  			return "", err
   198  		}
   199  	}
   200  
   201  	object := symbol
   202  	if symbol != "" && method != "" {
   203  		object = symbol + "." + method
   204  	}
   205  	if object != "" {
   206  		path = path + "#" + object
   207  	}
   208  	return path, nil
   209  }
   210  
   211  func doPkgsite(urlPath string) error {
   212  	port, err := pickUnusedPort()
   213  	if err != nil {
   214  		return fmt.Errorf("failed to find port for documentation server: %v", err)
   215  	}
   216  	addr := fmt.Sprintf("localhost:%d", port)
   217  	path := path.Join("http://"+addr, urlPath)
   218  
   219  	// Turn off the default signal handler for SIGINT (and SIGQUIT on Unix)
   220  	// and instead wait for the child process to handle the signal and
   221  	// exit before exiting ourselves.
   222  	signal.Ignore(signalsToIgnore...)
   223  
   224  	// Prepend the local download cache to GOPROXY to get around deprecation checks.
   225  	env := os.Environ()
   226  	vars, err := runCmd(nil, "go", "env", "GOPROXY", "GOMODCACHE")
   227  	fields := strings.Fields(vars)
   228  	if err == nil && len(fields) == 2 {
   229  		goproxy, gomodcache := fields[0], fields[1]
   230  		gomodcache = filepath.Join(gomodcache, "cache", "download")
   231  		// Convert absolute path to file URL. pkgsite will not accept
   232  		// Windows absolute paths because they look like a host:path remote.
   233  		// TODO(golang.org/issue/32456): use url.FromFilePath when implemented.
   234  		if strings.HasPrefix(gomodcache, "/") {
   235  			gomodcache = "file://" + gomodcache
   236  		} else {
   237  			gomodcache = "file:///" + filepath.ToSlash(gomodcache)
   238  		}
   239  		env = append(env, "GOPROXY="+gomodcache+","+goproxy)
   240  	}
   241  
   242  	const version = "v0.0.0-20250608123103-82c52f1754cd"
   243  	cmd := exec.Command("go", "run", "golang.org/x/pkgsite/cmd/internal/doc@"+version,
   244  		"-gorepo", buildCtx.GOROOT,
   245  		"-http", addr,
   246  		"-open", path)
   247  	cmd.Env = env
   248  	cmd.Stdout = os.Stderr
   249  	cmd.Stderr = os.Stderr
   250  
   251  	if err := cmd.Run(); err != nil {
   252  		var ee *exec.ExitError
   253  		if errors.As(err, &ee) {
   254  			// Exit with the same exit status as pkgsite to avoid
   255  			// printing of "exit status" error messages.
   256  			// Any relevant messages have already been printed
   257  			// to stdout or stderr.
   258  			os.Exit(ee.ExitCode())
   259  		}
   260  		return err
   261  	}
   262  
   263  	return nil
   264  }
   265  
   266  // pickUnusedPort finds an unused port by trying to listen on port 0
   267  // and letting the OS pick a port, then closing that connection and
   268  // returning that port number.
   269  // This is inherently racy.
   270  func pickUnusedPort() (int, error) {
   271  	l, err := net.Listen("tcp", "localhost:0")
   272  	if err != nil {
   273  		return 0, err
   274  	}
   275  	port := l.Addr().(*net.TCPAddr).Port
   276  	if err := l.Close(); err != nil {
   277  		return 0, err
   278  	}
   279  	return port, nil
   280  }
   281  
   282  // failMessage creates a nicely formatted error message when there is no result to show.
   283  func failMessage(paths []string, symbol, method string) error {
   284  	var b bytes.Buffer
   285  	if len(paths) > 1 {
   286  		b.WriteString("s")
   287  	}
   288  	b.WriteString(" ")
   289  	for i, path := range paths {
   290  		if i > 0 {
   291  			b.WriteString(", ")
   292  		}
   293  		b.WriteString(path)
   294  	}
   295  	if method == "" {
   296  		return fmt.Errorf("no symbol %s in package%s", symbol, &b)
   297  	}
   298  	return fmt.Errorf("no method or field %s.%s in package%s", symbol, method, &b)
   299  }
   300  
   301  // parseArgs analyzes the arguments (if any) and returns the package
   302  // it represents, the part of the argument the user used to identify
   303  // the path (or "" if it's the current package) and the symbol
   304  // (possibly with a .method) within that package.
   305  // parseSymbol is used to analyze the symbol itself.
   306  // The boolean final argument reports whether it is possible that
   307  // there may be more directories worth looking at. It will only
   308  // be true if the package path is a partial match for some directory
   309  // and there may be more matches. For example, if the argument
   310  // is rand.Float64, we must scan both crypto/rand and math/rand
   311  // to find the symbol, and the first call will return crypto/rand, true.
   312  func parseArgs(flagSet *flag.FlagSet, args []string) (pkg *build.Package, path, symbol string, more bool) {
   313  	wd, err := os.Getwd()
   314  	if err != nil {
   315  		log.Fatal(err)
   316  	}
   317  	if len(args) == 0 {
   318  		// Easy: current directory.
   319  		return importDir(wd), "", "", false
   320  	}
   321  	arg := args[0]
   322  	// We have an argument. If it is a directory name beginning with . or ..,
   323  	// use the absolute path name. This discriminates "./errors" from "errors"
   324  	// if the current directory contains a non-standard errors package.
   325  	if isDotSlash(arg) {
   326  		arg = filepath.Join(wd, arg)
   327  	}
   328  	switch len(args) {
   329  	default:
   330  		usage(flagSet)
   331  	case 1:
   332  		// Done below.
   333  	case 2:
   334  		// Package must be findable and importable.
   335  		pkg, err := build.Import(args[0], wd, build.ImportComment)
   336  		if err == nil {
   337  			return pkg, args[0], args[1], false
   338  		}
   339  		for {
   340  			packagePath, ok := findNextPackage(arg)
   341  			if !ok {
   342  				break
   343  			}
   344  			if pkg, err := build.ImportDir(packagePath, build.ImportComment); err == nil {
   345  				return pkg, arg, args[1], true
   346  			}
   347  		}
   348  		return nil, args[0], args[1], false
   349  	}
   350  	// Usual case: one argument.
   351  	// If it contains slashes, it begins with either a package path
   352  	// or an absolute directory.
   353  	// First, is it a complete package path as it is? If so, we are done.
   354  	// This avoids confusion over package paths that have other
   355  	// package paths as their prefix.
   356  	var importErr error
   357  	if filepath.IsAbs(arg) {
   358  		pkg, importErr = build.ImportDir(arg, build.ImportComment)
   359  		if importErr == nil {
   360  			return pkg, arg, "", false
   361  		}
   362  	} else {
   363  		pkg, importErr = build.Import(arg, wd, build.ImportComment)
   364  		if importErr == nil {
   365  			return pkg, arg, "", false
   366  		}
   367  	}
   368  	// Another disambiguator: If the argument starts with an upper
   369  	// case letter, it can only be a symbol in the current directory.
   370  	// Kills the problem caused by case-insensitive file systems
   371  	// matching an upper case name as a package name.
   372  	if !strings.ContainsAny(arg, `/\`) && token.IsExported(arg) {
   373  		pkg, err := build.ImportDir(".", build.ImportComment)
   374  		if err == nil {
   375  			return pkg, "", arg, false
   376  		}
   377  	}
   378  	// If it has a slash, it must be a package path but there is a symbol.
   379  	// It's the last package path we care about.
   380  	slash := strings.LastIndex(arg, "/")
   381  	// There may be periods in the package path before or after the slash
   382  	// and between a symbol and method.
   383  	// Split the string at various periods to see what we find.
   384  	// In general there may be ambiguities but this should almost always
   385  	// work.
   386  	var period int
   387  	// slash+1: if there's no slash, the value is -1 and start is 0; otherwise
   388  	// start is the byte after the slash.
   389  	for start := slash + 1; start < len(arg); start = period + 1 {
   390  		period = strings.Index(arg[start:], ".")
   391  		symbol := ""
   392  		if period < 0 {
   393  			period = len(arg)
   394  		} else {
   395  			period += start
   396  			symbol = arg[period+1:]
   397  		}
   398  		// Have we identified a package already?
   399  		pkg, err := build.Import(arg[0:period], wd, build.ImportComment)
   400  		if err == nil {
   401  			return pkg, arg[0:period], symbol, false
   402  		}
   403  		// See if we have the basename or tail of a package, as in json for encoding/json
   404  		// or ivy/value for robpike.io/ivy/value.
   405  		pkgName := arg[:period]
   406  		for {
   407  			path, ok := findNextPackage(pkgName)
   408  			if !ok {
   409  				break
   410  			}
   411  			if pkg, err = build.ImportDir(path, build.ImportComment); err == nil {
   412  				return pkg, arg[0:period], symbol, true
   413  			}
   414  		}
   415  		dirs.Reset() // Next iteration of for loop must scan all the directories again.
   416  	}
   417  	// If it has a slash, we've failed.
   418  	if slash >= 0 {
   419  		// build.Import should always include the path in its error message,
   420  		// and we should avoid repeating it. Unfortunately, build.Import doesn't
   421  		// return a structured error. That can't easily be fixed, since it
   422  		// invokes 'go list' and returns the error text from the loaded package.
   423  		// TODO(golang.org/issue/34750): load using golang.org/x/tools/go/packages
   424  		// instead of go/build.
   425  		importErrStr := importErr.Error()
   426  		if strings.Contains(importErrStr, arg[:period]) {
   427  			log.Fatal(importErrStr)
   428  		} else {
   429  			log.Fatalf("no such package %s: %s", arg[:period], importErrStr)
   430  		}
   431  	}
   432  	// Guess it's a symbol in the current directory.
   433  	return importDir(wd), "", arg, false
   434  }
   435  
   436  // dotPaths lists all the dotted paths legal on Unix-like and
   437  // Windows-like file systems. We check them all, as the chance
   438  // of error is minute and even on Windows people will use ./
   439  // sometimes.
   440  var dotPaths = []string{
   441  	`./`,
   442  	`../`,
   443  	`.\`,
   444  	`..\`,
   445  }
   446  
   447  // isDotSlash reports whether the path begins with a reference
   448  // to the local . or .. directory.
   449  func isDotSlash(arg string) bool {
   450  	if arg == "." || arg == ".." {
   451  		return true
   452  	}
   453  	for _, dotPath := range dotPaths {
   454  		if strings.HasPrefix(arg, dotPath) {
   455  			return true
   456  		}
   457  	}
   458  	return false
   459  }
   460  
   461  // importDir is just an error-catching wrapper for build.ImportDir.
   462  func importDir(dir string) *build.Package {
   463  	pkg, err := build.ImportDir(dir, build.ImportComment)
   464  	if err != nil {
   465  		log.Fatal(err)
   466  	}
   467  	return pkg
   468  }
   469  
   470  // parseSymbol breaks str apart into a symbol and method.
   471  // Both may be missing or the method may be missing.
   472  // If present, each must be a valid Go identifier.
   473  func parseSymbol(flagSet *flag.FlagSet, str string) (symbol, method string) {
   474  	if str == "" {
   475  		return
   476  	}
   477  	elem := strings.Split(str, ".")
   478  	switch len(elem) {
   479  	case 1:
   480  	case 2:
   481  		method = elem[1]
   482  	default:
   483  		log.Printf("too many periods in symbol specification")
   484  		usage(flagSet)
   485  	}
   486  	symbol = elem[0]
   487  	return
   488  }
   489  
   490  // isExported reports whether the name is an exported identifier.
   491  // If the unexported flag (-u) is true, isExported returns true because
   492  // it means that we treat the name as if it is exported.
   493  func isExported(name string) bool {
   494  	return unexported || token.IsExported(name)
   495  }
   496  
   497  // findNextPackage returns the next full file name path that matches the
   498  // (perhaps partial) package path pkg. The boolean reports if any match was found.
   499  func findNextPackage(pkg string) (string, bool) {
   500  	if filepath.IsAbs(pkg) {
   501  		if dirs.offset == 0 {
   502  			dirs.offset = -1
   503  			return pkg, true
   504  		}
   505  		return "", false
   506  	}
   507  	if pkg == "" || token.IsExported(pkg) { // Upper case symbol cannot be a package name.
   508  		return "", false
   509  	}
   510  	pkg = path.Clean(pkg)
   511  	pkgSuffix := "/" + pkg
   512  	for {
   513  		d, ok := dirs.Next()
   514  		if !ok {
   515  			return "", false
   516  		}
   517  		if d.importPath == pkg || strings.HasSuffix(d.importPath, pkgSuffix) {
   518  			return d.dir, true
   519  		}
   520  	}
   521  }
   522  
   523  var buildCtx = build.Default
   524  
   525  // splitGopath splits $GOPATH into a list of roots.
   526  func splitGopath() []string {
   527  	return filepath.SplitList(buildCtx.GOPATH)
   528  }
   529  

View as plain text