goconvey.go 8.8 KB

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