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.

checkout.go 6.7KB

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