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 7.0KB

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