You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

207 lines
5.7 KiB

  1. // Copyright 2013 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. package godoc
  5. import (
  6. "fmt"
  7. "go/ast"
  8. "go/build"
  9. "io"
  10. "log"
  11. "os"
  12. pathpkg "path"
  13. "path/filepath"
  14. "regexp"
  15. "strings"
  16. "golang.org/x/tools/godoc/vfs"
  17. )
  18. const (
  19. target = "/target"
  20. cmdPrefix = "cmd/"
  21. srcPrefix = "src/"
  22. toolsPath = "golang.org/x/tools/cmd/"
  23. )
  24. // CommandLine returns godoc results to w.
  25. // Note that it may add a /target path to fs.
  26. func CommandLine(w io.Writer, fs vfs.NameSpace, pres *Presentation, args []string) error {
  27. path := args[0]
  28. srcMode := pres.SrcMode
  29. cmdMode := strings.HasPrefix(path, cmdPrefix)
  30. if strings.HasPrefix(path, srcPrefix) {
  31. path = strings.TrimPrefix(path, srcPrefix)
  32. srcMode = true
  33. }
  34. var abspath, relpath string
  35. if cmdMode {
  36. path = strings.TrimPrefix(path, cmdPrefix)
  37. } else {
  38. abspath, relpath = paths(fs, pres, path)
  39. }
  40. var mode PageInfoMode
  41. if relpath == builtinPkgPath {
  42. // the fake built-in package contains unexported identifiers
  43. mode = NoFiltering | NoTypeAssoc
  44. }
  45. if srcMode {
  46. // only filter exports if we don't have explicit command-line filter arguments
  47. if len(args) > 1 {
  48. mode |= NoFiltering
  49. }
  50. mode |= ShowSource
  51. }
  52. // First, try as package unless forced as command.
  53. var info *PageInfo
  54. if !cmdMode {
  55. info = pres.GetPkgPageInfo(abspath, relpath, mode)
  56. }
  57. // Second, try as command (if the path is not absolute).
  58. var cinfo *PageInfo
  59. if !filepath.IsAbs(path) {
  60. // First try go.tools/cmd.
  61. abspath = pathpkg.Join(pres.PkgFSRoot(), toolsPath+path)
  62. cinfo = pres.GetCmdPageInfo(abspath, relpath, mode)
  63. if cinfo.IsEmpty() {
  64. // Then try $GOROOT/cmd.
  65. abspath = pathpkg.Join(pres.CmdFSRoot(), path)
  66. cinfo = pres.GetCmdPageInfo(abspath, relpath, mode)
  67. }
  68. }
  69. // determine what to use
  70. if info == nil || info.IsEmpty() {
  71. if cinfo != nil && !cinfo.IsEmpty() {
  72. // only cinfo exists - switch to cinfo
  73. info = cinfo
  74. }
  75. } else if cinfo != nil && !cinfo.IsEmpty() {
  76. // both info and cinfo exist - use cinfo if info
  77. // contains only subdirectory information
  78. if info.PAst == nil && info.PDoc == nil {
  79. info = cinfo
  80. } else if relpath != target {
  81. // The above check handles the case where an operating system path
  82. // is provided (see documentation for paths below). In that case,
  83. // relpath is set to "/target" (in anticipation of accessing packages there),
  84. // and is therefore not expected to match a command.
  85. fmt.Fprintf(w, "use 'godoc %s%s' for documentation on the %s command \n\n", cmdPrefix, relpath, relpath)
  86. }
  87. }
  88. if info == nil {
  89. return fmt.Errorf("%s: no such directory or package", args[0])
  90. }
  91. if info.Err != nil {
  92. return info.Err
  93. }
  94. if info.PDoc != nil && info.PDoc.ImportPath == target {
  95. // Replace virtual /target with actual argument from command line.
  96. info.PDoc.ImportPath = args[0]
  97. }
  98. // If we have more than one argument, use the remaining arguments for filtering.
  99. if len(args) > 1 {
  100. info.IsFiltered = true
  101. filterInfo(args[1:], info)
  102. }
  103. packageText := pres.PackageText
  104. if pres.HTMLMode {
  105. packageText = pres.PackageHTML
  106. }
  107. if err := packageText.Execute(w, info); err != nil {
  108. return err
  109. }
  110. return nil
  111. }
  112. // paths determines the paths to use.
  113. //
  114. // If we are passed an operating system path like . or ./foo or /foo/bar or c:\mysrc,
  115. // we need to map that path somewhere in the fs name space so that routines
  116. // like getPageInfo will see it. We use the arbitrarily-chosen virtual path "/target"
  117. // for this. That is, if we get passed a directory like the above, we map that
  118. // directory so that getPageInfo sees it as /target.
  119. // Returns the absolute and relative paths.
  120. func paths(fs vfs.NameSpace, pres *Presentation, path string) (string, string) {
  121. if filepath.IsAbs(path) {
  122. fs.Bind(target, vfs.OS(path), "/", vfs.BindReplace)
  123. return target, target
  124. }
  125. if build.IsLocalImport(path) {
  126. cwd, _ := os.Getwd() // ignore errors
  127. path = filepath.Join(cwd, path)
  128. fs.Bind(target, vfs.OS(path), "/", vfs.BindReplace)
  129. return target, target
  130. }
  131. if bp, _ := build.Import(path, "", build.FindOnly); bp.Dir != "" && bp.ImportPath != "" {
  132. fs.Bind(target, vfs.OS(bp.Dir), "/", vfs.BindReplace)
  133. return target, bp.ImportPath
  134. }
  135. return pathpkg.Join(pres.PkgFSRoot(), path), path
  136. }
  137. // filterInfo updates info to include only the nodes that match the given
  138. // filter args.
  139. func filterInfo(args []string, info *PageInfo) {
  140. rx, err := makeRx(args)
  141. if err != nil {
  142. log.Fatalf("illegal regular expression from %v: %v", args, err)
  143. }
  144. filter := func(s string) bool { return rx.MatchString(s) }
  145. switch {
  146. case info.PAst != nil:
  147. newPAst := map[string]*ast.File{}
  148. for name, a := range info.PAst {
  149. cmap := ast.NewCommentMap(info.FSet, a, a.Comments)
  150. a.Comments = []*ast.CommentGroup{} // remove all comments.
  151. ast.FilterFile(a, filter)
  152. if len(a.Decls) > 0 {
  153. newPAst[name] = a
  154. }
  155. for _, d := range a.Decls {
  156. // add back the comments associated with d only
  157. comments := cmap.Filter(d).Comments()
  158. a.Comments = append(a.Comments, comments...)
  159. }
  160. }
  161. info.PAst = newPAst // add only matching files.
  162. case info.PDoc != nil:
  163. info.PDoc.Filter(filter)
  164. }
  165. }
  166. // Does s look like a regular expression?
  167. func isRegexp(s string) bool {
  168. return strings.ContainsAny(s, ".(|)*+?^$[]")
  169. }
  170. // Make a regular expression of the form
  171. // names[0]|names[1]|...names[len(names)-1].
  172. // Returns an error if the regular expression is illegal.
  173. func makeRx(names []string) (*regexp.Regexp, error) {
  174. if len(names) == 0 {
  175. return nil, fmt.Errorf("no expression provided")
  176. }
  177. s := ""
  178. for i, name := range names {
  179. if i > 0 {
  180. s += "|"
  181. }
  182. if isRegexp(name) {
  183. s += name
  184. } else {
  185. s += "^" + name + "$" // must match exactly
  186. }
  187. }
  188. return regexp.Compile(s)
  189. }