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.1KB

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