goconvey.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. // This executable provides an HTTP server that watches for file system changes
  2. // to .go files within the working directory (and all nested go packages).
  3. // Navigating to the configured host and port in a web browser will display the
  4. // latest results of running `go test` in each go package.
  5. package main
  6. import (
  7. "flag"
  8. "fmt"
  9. "log"
  10. "net"
  11. "net/http"
  12. "os"
  13. "os/exec"
  14. "path/filepath"
  15. "runtime"
  16. "strings"
  17. "time"
  18. "go/build"
  19. "github.com/smartystreets/goconvey/web/server/api"
  20. "github.com/smartystreets/goconvey/web/server/contract"
  21. "github.com/smartystreets/goconvey/web/server/executor"
  22. "github.com/smartystreets/goconvey/web/server/messaging"
  23. "github.com/smartystreets/goconvey/web/server/parser"
  24. "github.com/smartystreets/goconvey/web/server/system"
  25. "github.com/smartystreets/goconvey/web/server/watch"
  26. )
  27. func init() {
  28. flags()
  29. folders()
  30. }
  31. func flags() {
  32. flag.IntVar(&port, "port", 8080, "The port at which to serve http.")
  33. flag.StringVar(&host, "host", "127.0.0.1", "The host at which to serve http.")
  34. flag.DurationVar(&nap, "poll", quarterSecond, "The interval to wait between polling the file system for changes.")
  35. flag.IntVar(&packages, "packages", 10, "The number of packages to test in parallel. Higher == faster but more costly in terms of computing.")
  36. flag.StringVar(&gobin, "gobin", "go", "The path to the 'go' binary (default: search on the PATH).")
  37. flag.BoolVar(&cover, "cover", true, "Enable package-level coverage statistics. Requires Go 1.2+ and the go cover tool.")
  38. flag.IntVar(&depth, "depth", -1, "The directory scanning depth. If -1, scan infinitely deep directory structures. 0: scan working directory. 1+: Scan into nested directories, limited to value.")
  39. flag.StringVar(&timeout, "timeout", "0", "The test execution timeout if none is specified in the *.goconvey file (default is '0', which is the same as not providing this option).")
  40. flag.StringVar(&watchedSuffixes, "watchedSuffixes", ".go", "A comma separated list of file suffixes to watch for modifications.")
  41. flag.StringVar(&excludedDirs, "excludedDirs", "vendor,node_modules", "A comma separated list of directories that will be excluded from being watched")
  42. flag.StringVar(&workDir, "workDir", "", "set goconvey working directory (default current directory)")
  43. flag.BoolVar(&autoLaunchBrowser, "launchBrowser", true, "toggle auto launching of browser (default: true)")
  44. log.SetOutput(os.Stdout)
  45. log.SetFlags(log.LstdFlags | log.Lshortfile)
  46. }
  47. func folders() {
  48. _, file, _, _ := runtime.Caller(0)
  49. here := filepath.Dir(file)
  50. static = filepath.Join(here, "/web/client")
  51. reports = filepath.Join(static, "reports")
  52. }
  53. func main() {
  54. flag.Parse()
  55. log.Printf(initialConfiguration, host, port, nap, cover)
  56. working := getWorkDir()
  57. cover = coverageEnabled(cover, reports)
  58. shell := system.NewShell(gobin, reports, cover, timeout)
  59. watcherInput := make(chan messaging.WatcherCommand)
  60. watcherOutput := make(chan messaging.Folders)
  61. excludedDirItems := strings.Split(excludedDirs, `,`)
  62. watcher := watch.NewWatcher(working, depth, nap, watcherInput, watcherOutput, watchedSuffixes, excludedDirItems)
  63. parser := parser.NewParser(parser.ParsePackageResults)
  64. tester := executor.NewConcurrentTester(shell)
  65. tester.SetBatchSize(packages)
  66. longpollChan := make(chan chan string)
  67. executor := executor.NewExecutor(tester, parser, longpollChan)
  68. server := api.NewHTTPServer(working, watcherInput, executor, longpollChan)
  69. listener := createListener()
  70. go runTestOnUpdates(watcherOutput, executor, server)
  71. go watcher.Listen()
  72. if autoLaunchBrowser {
  73. go launchBrowser(listener.Addr().String())
  74. }
  75. serveHTTP(server, listener)
  76. }
  77. func browserCmd() (string, bool) {
  78. browser := map[string]string{
  79. "darwin": "open",
  80. "linux": "xdg-open",
  81. "win32": "start",
  82. }
  83. cmd, ok := browser[runtime.GOOS]
  84. return cmd, ok
  85. }
  86. func launchBrowser(addr string) {
  87. browser, ok := browserCmd()
  88. if !ok {
  89. log.Printf("Skipped launching browser for this OS: %s", runtime.GOOS)
  90. return
  91. }
  92. log.Printf("Launching browser on %s", addr)
  93. url := fmt.Sprintf("http://%s", addr)
  94. cmd := exec.Command(browser, url)
  95. output, err := cmd.CombinedOutput()
  96. if err != nil {
  97. log.Println(err)
  98. }
  99. log.Println(string(output))
  100. }
  101. func runTestOnUpdates(queue chan messaging.Folders, executor contract.Executor, server contract.Server) {
  102. for update := range queue {
  103. log.Println("Received request from watcher to execute tests...")
  104. packages := extractPackages(update)
  105. output := executor.ExecuteTests(packages)
  106. root := extractRoot(update, packages)
  107. server.ReceiveUpdate(root, output)
  108. }
  109. }
  110. func extractPackages(folderList messaging.Folders) []*contract.Package {
  111. packageList := []*contract.Package{}
  112. for _, folder := range folderList {
  113. hasImportCycle := testFilesImportTheirOwnPackage(folder.Path)
  114. packageList = append(packageList, contract.NewPackage(folder, hasImportCycle))
  115. }
  116. return packageList
  117. }
  118. func extractRoot(folderList messaging.Folders, packageList []*contract.Package) string {
  119. path := packageList[0].Path
  120. folder := folderList[path]
  121. return folder.Root
  122. }
  123. // This method exists because of a bug in the go cover tool that
  124. // causes an infinite loop when you try to run `go test -cover`
  125. // on a package that has an import cycle defined in one of it's
  126. // test files. Yuck.
  127. func testFilesImportTheirOwnPackage(packagePath string) bool {
  128. meta, err := build.ImportDir(packagePath, build.AllowBinary)
  129. if err != nil {
  130. return false
  131. }
  132. for _, dependency := range meta.TestImports {
  133. if dependency == meta.ImportPath {
  134. return true
  135. }
  136. }
  137. return false
  138. }
  139. func createListener() net.Listener {
  140. l, err := net.Listen("tcp", fmt.Sprintf("%s:%d", host, port))
  141. if err != nil {
  142. log.Println(err)
  143. }
  144. if l == nil {
  145. os.Exit(1)
  146. }
  147. return l
  148. }
  149. func serveHTTP(server contract.Server, listener net.Listener) {
  150. serveStaticResources()
  151. serveAjaxMethods(server)
  152. activateServer(listener)
  153. }
  154. func serveStaticResources() {
  155. http.Handle("/", http.FileServer(http.Dir(static)))
  156. }
  157. func serveAjaxMethods(server contract.Server) {
  158. http.HandleFunc("/watch", server.Watch)
  159. http.HandleFunc("/ignore", server.Ignore)
  160. http.HandleFunc("/reinstate", server.Reinstate)
  161. http.HandleFunc("/latest", server.Results)
  162. http.HandleFunc("/execute", server.Execute)
  163. http.HandleFunc("/status", server.Status)
  164. http.HandleFunc("/status/poll", server.LongPollStatus)
  165. http.HandleFunc("/pause", server.TogglePause)
  166. }
  167. func activateServer(listener net.Listener) {
  168. log.Printf("Serving HTTP at: http://%s\n", listener.Addr())
  169. err := http.Serve(listener, nil)
  170. if err != nil {
  171. log.Println(err)
  172. }
  173. }
  174. func coverageEnabled(cover bool, reports string) bool {
  175. return (cover &&
  176. goVersion_1_2_orGreater() &&
  177. coverToolInstalled() &&
  178. ensureReportDirectoryExists(reports))
  179. }
  180. func goVersion_1_2_orGreater() bool {
  181. version := runtime.Version() // 'go1.2....'
  182. major, minor := version[2], version[4]
  183. version_1_2 := major >= byte('1') && minor >= byte('2')
  184. if !version_1_2 {
  185. log.Printf(pleaseUpgradeGoVersion, version)
  186. return false
  187. }
  188. return true
  189. }
  190. func coverToolInstalled() bool {
  191. working := getWorkDir()
  192. command := system.NewCommand(working, "go", "tool", "cover").Execute()
  193. installed := strings.Contains(command.Output, "Usage of 'go tool cover':")
  194. if !installed {
  195. log.Print(coverToolMissing)
  196. return false
  197. }
  198. return true
  199. }
  200. func ensureReportDirectoryExists(reports string) bool {
  201. result, err := exists(reports)
  202. if err != nil {
  203. log.Fatal(err)
  204. }
  205. if result {
  206. return true
  207. }
  208. if err := os.Mkdir(reports, 0755); err == nil {
  209. return true
  210. }
  211. log.Printf(reportDirectoryUnavailable, reports)
  212. return false
  213. }
  214. func exists(path string) (bool, error) {
  215. _, err := os.Stat(path)
  216. if err == nil {
  217. return true, nil
  218. }
  219. if os.IsNotExist(err) {
  220. return false, nil
  221. }
  222. return false, err
  223. }
  224. func getWorkDir() string {
  225. working := ""
  226. var err error
  227. if workDir != "" {
  228. working = workDir
  229. } else {
  230. working, err = os.Getwd()
  231. if err != nil {
  232. log.Fatal(err)
  233. }
  234. }
  235. result, err := exists(working)
  236. if err != nil {
  237. log.Fatal(err)
  238. }
  239. if !result {
  240. log.Fatalf("Path:%s does not exists", working)
  241. }
  242. return working
  243. }
  244. var (
  245. port int
  246. host string
  247. gobin string
  248. nap time.Duration
  249. packages int
  250. cover bool
  251. depth int
  252. timeout string
  253. watchedSuffixes string
  254. excludedDirs string
  255. autoLaunchBrowser bool
  256. static string
  257. reports string
  258. quarterSecond = time.Millisecond * 250
  259. workDir string
  260. )
  261. const (
  262. initialConfiguration = "Initial configuration: [host: %s] [port: %d] [poll: %v] [cover: %v]\n"
  263. pleaseUpgradeGoVersion = "Go version is less that 1.2 (%s), please upgrade to the latest stable version to enable coverage reporting.\n"
  264. coverToolMissing = "Go cover tool is not installed or not accessible: for Go < 1.5 run`go get golang.org/x/tools/cmd/cover`\n For >= Go 1.5 run `go install $GOROOT/src/cmd/cover`\n"
  265. reportDirectoryUnavailable = "Could not find or create the coverage report directory (at: '%s'). You probably won't see any coverage statistics...\n"
  266. )