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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. // Copyright 2020 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package main
  4. /*
  5. Checkout a PR and load the tests data into sqlite database
  6. */
  7. import (
  8. "context"
  9. "flag"
  10. "fmt"
  11. "log"
  12. "net/http"
  13. "os"
  14. "os/exec"
  15. "os/user"
  16. "path"
  17. "path/filepath"
  18. "runtime"
  19. "strconv"
  20. "time"
  21. "code.gitea.io/gitea/models/db"
  22. "code.gitea.io/gitea/models/unittest"
  23. gitea_git "code.gitea.io/gitea/modules/git"
  24. "code.gitea.io/gitea/modules/graceful"
  25. "code.gitea.io/gitea/modules/markup"
  26. "code.gitea.io/gitea/modules/markup/external"
  27. repo_module "code.gitea.io/gitea/modules/repository"
  28. "code.gitea.io/gitea/modules/setting"
  29. "code.gitea.io/gitea/modules/util"
  30. "code.gitea.io/gitea/routers"
  31. markup_service "code.gitea.io/gitea/services/markup"
  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.GravatarSource = "https://secure.gravatar.com/avatar/"
  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. //models.LoadConfigs()
  71. /*
  72. setting.Database.Type = "sqlite3"
  73. setting.Database.Path = ":memory:"
  74. setting.Database.Timeout = 500
  75. */
  76. dbCfg := setting.Cfg.Section("database")
  77. dbCfg.NewKey("DB_TYPE", "sqlite3")
  78. dbCfg.NewKey("PATH", ":memory:")
  79. routers.InitGitServices()
  80. setting.Database.LogSQL = true
  81. // x, err = xorm.NewEngine("sqlite3", "file::memory:?cache=shared")
  82. db.InitEngineWithMigration(context.Background(), func(_ *xorm.Engine) error {
  83. return nil
  84. })
  85. db.HasEngine = true
  86. // x.ShowSQL(true)
  87. err = unittest.InitFixtures(
  88. unittest.FixturesOptions{
  89. Dir: path.Join(curDir, "models/fixtures/"),
  90. },
  91. )
  92. if err != nil {
  93. fmt.Printf("Error initializing test database: %v\n", err)
  94. os.Exit(1)
  95. }
  96. unittest.LoadFixtures()
  97. util.RemoveAll(setting.RepoRootPath)
  98. util.RemoveAll(repo_module.LocalCopyPath())
  99. unittest.CopyDir(path.Join(curDir, "tests/gitea-repositories-meta"), setting.RepoRootPath)
  100. log.Printf("[PR] Setting up router\n")
  101. // routers.GlobalInit()
  102. external.RegisterRenderers()
  103. markup.Init(markup_service.ProcessorHelper())
  104. c := routers.NormalRoutes(graceful.GetManager().HammerContext())
  105. log.Printf("[PR] Ready for testing !\n")
  106. log.Printf("[PR] Login with user1, user2, user3, ... with pass: password\n")
  107. /*
  108. log.Info("Listen: %v://%s%s", setting.Protocol, listenAddr, setting.AppSubURL)
  109. if setting.LFS.StartServer {
  110. log.Info("LFS server enabled")
  111. }
  112. if setting.EnablePprof {
  113. go func() {
  114. log.Info("Starting pprof server on localhost:6060")
  115. log.Info("%v", http.ListenAndServe("localhost:6060", nil))
  116. }()
  117. }
  118. */
  119. // Start the server
  120. http.ListenAndServe(":8080", c)
  121. log.Printf("[PR] Cleaning up ...\n")
  122. /*
  123. if err = util.RemoveAll(setting.Indexer.IssuePath); err != nil {
  124. fmt.Printf("util.RemoveAll: %v\n", err)
  125. os.Exit(1)
  126. }
  127. if err = util.RemoveAll(setting.Indexer.RepoPath); err != nil {
  128. fmt.Printf("Unable to remove repo indexer: %v\n", err)
  129. os.Exit(1)
  130. }
  131. */
  132. if err = util.RemoveAll(setting.RepoRootPath); err != nil {
  133. log.Fatalf("util.RemoveAll: %v\n", err)
  134. }
  135. if err = util.RemoveAll(setting.AppDataPath); err != nil {
  136. log.Fatalf("util.RemoveAll: %v\n", err)
  137. }
  138. }
  139. func main() {
  140. runPRFlag := flag.Bool("run", false, "Run the PR code")
  141. flag.Parse()
  142. if *runPRFlag {
  143. runPR()
  144. return
  145. }
  146. // To force checkout (e.g. Windows complains about unclean work tree) set env variable FORCE=true
  147. force, err := strconv.ParseBool(os.Getenv("FORCE"))
  148. if err != nil {
  149. force = false
  150. }
  151. // Otherwise checkout PR
  152. if len(os.Args) != 2 {
  153. log.Fatal("Need only one arg: the PR number")
  154. }
  155. pr := os.Args[1]
  156. codeFilePath = filepath.FromSlash(codeFilePath) // Convert to running OS
  157. // Copy this file if it will not exist in the PR branch
  158. dat, err := os.ReadFile(codeFilePath)
  159. if err != nil {
  160. log.Fatalf("Failed to cache this code file : %v", err)
  161. }
  162. repo, err := git.PlainOpen(".")
  163. if err != nil {
  164. log.Fatalf("Failed to open the repo : %v", err)
  165. }
  166. // Find remote upstream
  167. remotes, err := repo.Remotes()
  168. if err != nil {
  169. log.Fatalf("Failed to list remotes of repo : %v", err)
  170. }
  171. remoteUpstream := "origin" // Default
  172. for _, r := range remotes {
  173. if r.Config().URLs[0] == "https://github.com/go-gitea/gitea.git" ||
  174. r.Config().URLs[0] == "https://github.com/go-gitea/gitea" ||
  175. 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("%s%s/head:%s", gitea_git.PullPrefix, 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), 0o755)
  213. if err != nil {
  214. log.Fatalf("Failed to duplicate this code file in PR : %v", err)
  215. }
  216. err = os.WriteFile(codeFilePath, dat, 0o644)
  217. if err != nil {
  218. log.Fatalf("Failed to duplicate this code file in PR : %v", err)
  219. }
  220. }
  221. // Force build of js, css, bin, ...
  222. runCmd("make", "build")
  223. // Start with integration test
  224. runCmd("go", "run", "-mod", "vendor", "-tags", "sqlite sqlite_unlock_notify", codeFilePath, "-run")
  225. }
  226. func runCmd(cmd ...string) {
  227. log.Printf("Executing : %s ...\n", cmd)
  228. c := exec.Command(cmd[0], cmd[1:]...)
  229. c.Stdout = os.Stdout
  230. c.Stderr = os.Stderr
  231. if err := c.Start(); err != nil {
  232. log.Panicln(err)
  233. }
  234. if err := c.Wait(); err != nil {
  235. log.Panicln(err)
  236. }
  237. }