go2make.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. /*
  2. Copyright 2017 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package main
  14. import (
  15. "bytes"
  16. goflag "flag"
  17. "fmt"
  18. "go/build"
  19. "io"
  20. "os"
  21. "sort"
  22. "strings"
  23. "github.com/spf13/pflag"
  24. )
  25. var flPrune = pflag.StringSlice("prune", nil, "sub-packages to prune (recursive, may be specified multiple times)")
  26. var flDebug = pflag.BoolP("debug", "d", false, "enable debugging output")
  27. var flHelp = pflag.BoolP("help", "h", false, "print help and exit")
  28. func main() {
  29. pflag.CommandLine.AddGoFlagSet(goflag.CommandLine)
  30. pflag.Usage = func() { help(os.Stderr) }
  31. pflag.Parse()
  32. debug("PWD", getwd())
  33. build.Default.BuildTags = []string{"ignore_autogenerated"}
  34. build.Default.UseAllFiles = false
  35. if *flHelp {
  36. help(os.Stdout)
  37. os.Exit(0)
  38. }
  39. if len(pflag.Args()) == 0 {
  40. help(os.Stderr)
  41. os.Exit(1)
  42. }
  43. for _, in := range pflag.Args() {
  44. if strings.HasSuffix(in, "/...") {
  45. // Recurse.
  46. debug("starting", in)
  47. pkgName := strings.TrimSuffix(in, "/...")
  48. if err := WalkPkg(pkgName, visitPkg); err != nil {
  49. fmt.Fprintln(os.Stderr, err)
  50. os.Exit(1)
  51. }
  52. } else {
  53. // Import one package.
  54. if err := saveImport(in); err != nil {
  55. fmt.Fprintln(os.Stderr, err)
  56. os.Exit(2)
  57. }
  58. }
  59. }
  60. }
  61. func help(out io.Writer) {
  62. fmt.Fprintf(out, "Usage: %s [FLAG...] <PKG...>\n", os.Args[0])
  63. fmt.Fprintf(out, "\n")
  64. fmt.Fprintf(out, "go2make calculates all of the dependencies of a set of Go packages and prints\n")
  65. fmt.Fprintf(out, "them as variable definitions suitable for use as a Makefile.\n")
  66. fmt.Fprintf(out, "\n")
  67. fmt.Fprintf(out, "Package specifications may be simple (e.g. 'example.com/txt/color') or\n")
  68. fmt.Fprintf(out, "recursive (e.g. 'example.com/txt/...')\n")
  69. fmt.Fprintf(out, " Example:\n")
  70. fmt.Fprintf(out, " $ %s ./example.com/pretty\n", os.Args[0])
  71. fmt.Fprintf(out, " example.com/txt/split := \\\n")
  72. fmt.Fprintf(out, " /go/src/example.com/txt/split/ \\\n")
  73. fmt.Fprintf(out, " /go/src/example.com/txt/split/split.go \\\n")
  74. fmt.Fprintf(out, " ./example.com/pretty := \\\n")
  75. fmt.Fprintf(out, " /go/src/example.com/pretty/ \\\n")
  76. fmt.Fprintf(out, " /go/src/example.com/pretty/print.go \\\n")
  77. fmt.Fprintf(out, " /go/src/example.com/txt/split/ \\\n")
  78. fmt.Fprintf(out, " /go/src/example.com/txt/split/split.go\n")
  79. fmt.Fprintf(out, "\n")
  80. fmt.Fprintf(out, " Flags:\n")
  81. pflag.PrintDefaults()
  82. }
  83. func debug(items ...interface{}) {
  84. if *flDebug {
  85. x := []interface{}{"DBG:"}
  86. x = append(x, items...)
  87. fmt.Println(x...)
  88. }
  89. }
  90. func visitPkg(importPath, absPath string) error {
  91. debug("visit", importPath)
  92. return saveImport(importPath)
  93. }
  94. func prune(pkgName string) bool {
  95. for _, pr := range *flPrune {
  96. if pr == pkgName {
  97. return true
  98. }
  99. }
  100. return false
  101. }
  102. // cache keeps track of which packages we have already loaded.
  103. var cache = map[string]*build.Package{}
  104. func saveImport(pkgName string) error {
  105. if cache[pkgName] != nil {
  106. return nil
  107. }
  108. if prune(pkgName) {
  109. debug("prune", pkgName)
  110. return ErrSkipPkg
  111. }
  112. pkg, err := loadPackage(pkgName)
  113. if err != nil {
  114. return err
  115. }
  116. debug("save", pkgName)
  117. cache[pkgName] = pkg
  118. debug("recurse", pkgName)
  119. defer func() { debug("done ", pkgName) }()
  120. if !pkg.Goroot && (len(pkg.GoFiles)+len(pkg.Imports) > 0) {
  121. // Process deps of this package before the package itself.
  122. for _, impName := range pkg.Imports {
  123. if impName == "C" {
  124. continue
  125. }
  126. debug("depends on", impName)
  127. saveImport(impName)
  128. }
  129. // Emit a variable for each package.
  130. var buf bytes.Buffer
  131. buf.WriteString(pkgName)
  132. buf.WriteString(" := ")
  133. // Packages depend on their own directories, their own files, and
  134. // transitive list of all deps' directories and files.
  135. all := map[string]struct{}{}
  136. all[pkg.Dir+"/"] = struct{}{}
  137. filesForPkg(pkg, all)
  138. for _, imp := range pkg.Imports {
  139. pkg := cache[imp]
  140. if pkg == nil || pkg.Goroot {
  141. continue
  142. }
  143. all[pkg.Dir+"/"] = struct{}{}
  144. filesForPkg(pkg, all)
  145. }
  146. // Sort and de-dup them.
  147. files := flatten(all)
  148. for _, f := range files {
  149. buf.WriteString(" \\\n ")
  150. buf.WriteString(f)
  151. }
  152. fmt.Println(buf.String())
  153. }
  154. return nil
  155. }
  156. func filesForPkg(pkg *build.Package, all map[string]struct{}) {
  157. for _, file := range pkg.GoFiles {
  158. if pkg.Dir != "." {
  159. file = pkg.Dir + "/" + file
  160. }
  161. all[file] = struct{}{}
  162. }
  163. }
  164. func flatten(all map[string]struct{}) []string {
  165. list := make([]string, 0, len(all))
  166. for k := range all {
  167. list = append(list, k)
  168. }
  169. sort.Strings(list)
  170. return list
  171. }
  172. func loadPackage(pkgName string) (*build.Package, error) {
  173. debug("load", pkgName)
  174. pkg, err := build.Import(pkgName, getwd(), 0)
  175. if err != nil {
  176. // We can ignore NoGoError. Anything else is real.
  177. if _, ok := err.(*build.NoGoError); !ok {
  178. return nil, err
  179. }
  180. }
  181. return pkg, nil
  182. }
  183. func getwd() string {
  184. pwd, err := os.Getwd()
  185. if err != nil {
  186. panic(fmt.Sprintf("can't get working directory: %v", err))
  187. }
  188. return pwd
  189. }