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

checkout.go 6.7 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. package main
  2. /*
  3. Checkout a PR and load the tests data into sqlite database
  4. */
  5. import (
  6. "flag"
  7. "fmt"
  8. "io/ioutil"
  9. "log"
  10. "net/http"
  11. "net/url"
  12. "os"
  13. "os/exec"
  14. "os/user"
  15. "path"
  16. "path/filepath"
  17. "runtime"
  18. "time"
  19. "code.gitea.io/gitea/modules/markup/external"
  20. "code.gitea.io/gitea/routers"
  21. "code.gitea.io/gitea/routers/routes"
  22. "github.com/Unknwon/com"
  23. "github.com/go-xorm/xorm"
  24. context2 "github.com/gorilla/context"
  25. "gopkg.in/src-d/go-git.v4"
  26. "gopkg.in/src-d/go-git.v4/config"
  27. "gopkg.in/src-d/go-git.v4/plumbing"
  28. "gopkg.in/testfixtures.v2"
  29. "code.gitea.io/gitea/models"
  30. "code.gitea.io/gitea/modules/setting"
  31. )
  32. var codeFilePath = "contrib/pr/checkout.go"
  33. func runPR() {
  34. log.Printf("[PR] Starting gitea ...\n")
  35. curDir, err := os.Getwd()
  36. if err != nil {
  37. log.Fatal(err)
  38. }
  39. setting.NewContext()
  40. setting.RepoRootPath, err = ioutil.TempDir(os.TempDir(), "repos")
  41. if err != nil {
  42. log.Fatalf("TempDir: %v\n", err)
  43. }
  44. setting.AppDataPath, err = ioutil.TempDir(os.TempDir(), "appdata")
  45. if err != nil {
  46. log.Fatalf("TempDir: %v\n", err)
  47. }
  48. setting.AppWorkPath = curDir
  49. setting.StaticRootPath = curDir
  50. setting.GravatarSourceURL, err = url.Parse("https://secure.gravatar.com/avatar/")
  51. if err != nil {
  52. log.Fatalf("url.Parse: %v\n", err)
  53. }
  54. setting.AppURL = "http://localhost:8080/"
  55. setting.HTTPPort = "8080"
  56. setting.SSH.Domain = "localhost"
  57. setting.SSH.Port = 3000
  58. setting.InstallLock = true
  59. setting.SecretKey = "9pCviYTWSb"
  60. setting.InternalToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYmYiOjE0OTI3OTU5ODN9.OQkH5UmzID2XBdwQ9TAI6Jj2t1X-wElVTjbE7aoN4I8"
  61. curUser, err := user.Current()
  62. if err != nil {
  63. log.Fatal(err)
  64. }
  65. setting.RunUser = curUser.Username
  66. log.Printf("[PR] Loading fixtures data ...\n")
  67. setting.CheckLFSVersion()
  68. //models.LoadConfigs()
  69. /*
  70. models.DbCfg.Type = "sqlite3"
  71. models.DbCfg.Path = ":memory:"
  72. models.DbCfg.Timeout = 500
  73. */
  74. db := setting.Cfg.Section("database")
  75. db.NewKey("DB_TYPE", "sqlite3")
  76. db.NewKey("PATH", ":memory:")
  77. setting.LogSQL = true
  78. models.LoadConfigs()
  79. routers.NewServices()
  80. //x, err = xorm.NewEngine("sqlite3", "file::memory:?cache=shared")
  81. var helper testfixtures.Helper
  82. helper = &testfixtures.SQLite{}
  83. models.NewEngine(func(_ *xorm.Engine) error {
  84. return nil
  85. })
  86. models.HasEngine = true
  87. //x.ShowSQL(true)
  88. err = models.InitFixtures(
  89. helper,
  90. path.Join(curDir, "models/fixtures/"),
  91. )
  92. if err != nil {
  93. fmt.Printf("Error initializing test database: %v\n", err)
  94. os.Exit(1)
  95. }
  96. models.LoadFixtures()
  97. os.RemoveAll(setting.RepoRootPath)
  98. os.RemoveAll(models.LocalCopyPath())
  99. os.RemoveAll(models.LocalWikiPath())
  100. com.CopyDir(path.Join(curDir, "integrations/gitea-repositories-meta"), setting.RepoRootPath)
  101. log.Printf("[PR] Setting up router\n")
  102. //routers.GlobalInit()
  103. external.RegisterParsers()
  104. m := routes.NewMacaron()
  105. routes.RegisterRoutes(m)
  106. log.Printf("[PR] Ready for testing !\n")
  107. log.Printf("[PR] Login with user1, user2, user3, ... with pass: password\n")
  108. /*
  109. log.Info("Listen: %v://%s%s", setting.Protocol, listenAddr, setting.AppSubURL)
  110. if setting.LFS.StartServer {
  111. log.Info("LFS server enabled")
  112. }
  113. if setting.EnablePprof {
  114. go func() {
  115. log.Info("Starting pprof server on localhost:6060")
  116. log.Info("%v", http.ListenAndServe("localhost:6060", nil))
  117. }()
  118. }
  119. */
  120. //Start the server
  121. http.ListenAndServe(":8080", context2.ClearHandler(m))
  122. log.Printf("[PR] Cleaning up ...\n")
  123. /*
  124. if err = os.RemoveAll(setting.Indexer.IssuePath); err != nil {
  125. fmt.Printf("os.RemoveAll: %v\n", err)
  126. os.Exit(1)
  127. }
  128. if err = os.RemoveAll(setting.Indexer.RepoPath); err != nil {
  129. fmt.Printf("Unable to remove repo indexer: %v\n", err)
  130. os.Exit(1)
  131. }
  132. */
  133. if err = os.RemoveAll(setting.RepoRootPath); err != nil {
  134. log.Fatalf("os.RemoveAll: %v\n", err)
  135. }
  136. if err = os.RemoveAll(setting.AppDataPath); err != nil {
  137. log.Fatalf("os.RemoveAll: %v\n", err)
  138. }
  139. }
  140. func main() {
  141. var runPRFlag = flag.Bool("run", false, "Run the PR code")
  142. flag.Parse()
  143. if *runPRFlag {
  144. runPR()
  145. return
  146. }
  147. //Otherwise checkout PR
  148. if len(os.Args) != 2 {
  149. log.Fatal("Need only one arg: the PR number")
  150. }
  151. pr := os.Args[1]
  152. codeFilePath = filepath.FromSlash(codeFilePath) //Convert to running OS
  153. //Copy this file if it will not exist in the PR branch
  154. dat, err := ioutil.ReadFile(codeFilePath)
  155. if err != nil {
  156. log.Fatalf("Failed to cache this code file : %v", err)
  157. }
  158. repo, err := git.PlainOpen(".")
  159. if err != nil {
  160. log.Fatalf("Failed to open the repo : %v", err)
  161. }
  162. //Find remote upstream
  163. remotes, err := repo.Remotes()
  164. if err != nil {
  165. log.Fatalf("Failed to list remotes of repo : %v", err)
  166. }
  167. remoteUpstream := "origin" //Default
  168. for _, r := range remotes {
  169. if r.Config().URLs[0] == "https://github.com/go-gitea/gitea" || r.Config().URLs[0] == "git@github.com:go-gitea/gitea.git" { //fetch at index 0
  170. remoteUpstream = r.Config().Name
  171. break
  172. }
  173. }
  174. branch := fmt.Sprintf("pr-%s-%d", pr, time.Now().Unix())
  175. branchRef := plumbing.NewBranchReferenceName(branch)
  176. log.Printf("Fetching PR #%s in %s\n", pr, branch)
  177. if runtime.GOOS == "windows" {
  178. //Use git cli command for windows
  179. runCmd("git", "fetch", remoteUpstream, fmt.Sprintf("pull/%s/head:%s", pr, branch))
  180. } else {
  181. ref := fmt.Sprintf("refs/pull/%s/head:%s", pr, branchRef)
  182. err = repo.Fetch(&git.FetchOptions{
  183. RemoteName: remoteUpstream,
  184. RefSpecs: []config.RefSpec{
  185. config.RefSpec(ref),
  186. },
  187. })
  188. if err != nil {
  189. log.Fatalf("Failed to fetch %s from %s : %v", ref, remoteUpstream, err)
  190. }
  191. }
  192. tree, err := repo.Worktree()
  193. if err != nil {
  194. log.Fatalf("Failed to parse git tree : %v", err)
  195. }
  196. log.Printf("Checkout PR #%s in %s\n", pr, branch)
  197. err = tree.Checkout(&git.CheckoutOptions{
  198. Branch: branchRef,
  199. //Force: runtime.GOOS == "windows",
  200. })
  201. if err != nil {
  202. log.Fatalf("Failed to checkout %s : %v", branch, err)
  203. }
  204. //Copy this file if not exist
  205. if _, err := os.Stat(codeFilePath); os.IsNotExist(err) {
  206. err = os.MkdirAll(filepath.Dir(codeFilePath), 0755)
  207. if err != nil {
  208. log.Fatalf("Failed to duplicate this code file in PR : %v", err)
  209. }
  210. err = ioutil.WriteFile(codeFilePath, dat, 0644)
  211. if err != nil {
  212. log.Fatalf("Failed to duplicate this code file in PR : %v", err)
  213. }
  214. }
  215. time.Sleep(5 * time.Second)
  216. //Start with integration test
  217. runCmd("go", "run", "-tags", "sqlite sqlite_unlock_notify", codeFilePath, "-run")
  218. }
  219. func runCmd(cmd ...string) {
  220. log.Printf("Executing : %s ...\n", cmd)
  221. c := exec.Command(cmd[0], cmd[1:]...)
  222. c.Stdout = os.Stdout
  223. c.Stderr = os.Stderr
  224. if err := c.Start(); err != nil {
  225. log.Panicln(err)
  226. }
  227. if err := c.Wait(); err != nil {
  228. log.Panicln(err)
  229. }
  230. }