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.9 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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/modules/markup"
  21. "code.gitea.io/gitea/modules/markup/external"
  22. "code.gitea.io/gitea/routers"
  23. "code.gitea.io/gitea/routers/routes"
  24. "github.com/Unknwon/com"
  25. "github.com/go-xorm/xorm"
  26. context2 "github.com/gorilla/context"
  27. "gopkg.in/src-d/go-git.v4"
  28. "gopkg.in/src-d/go-git.v4/config"
  29. "gopkg.in/src-d/go-git.v4/plumbing"
  30. "gopkg.in/testfixtures.v2"
  31. "code.gitea.io/gitea/models"
  32. "code.gitea.io/gitea/modules/setting"
  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. models.DbCfg.Type = "sqlite3"
  74. models.DbCfg.Path = ":memory:"
  75. models.DbCfg.Timeout = 500
  76. */
  77. db := setting.Cfg.Section("database")
  78. db.NewKey("DB_TYPE", "sqlite3")
  79. db.NewKey("PATH", ":memory:")
  80. setting.LogSQL = true
  81. models.LoadConfigs()
  82. routers.NewServices()
  83. //x, err = xorm.NewEngine("sqlite3", "file::memory:?cache=shared")
  84. var helper testfixtures.Helper
  85. helper = &testfixtures.SQLite{}
  86. models.NewEngine(func(_ *xorm.Engine) error {
  87. return nil
  88. })
  89. models.HasEngine = true
  90. //x.ShowSQL(true)
  91. err = models.InitFixtures(
  92. helper,
  93. path.Join(curDir, "models/fixtures/"),
  94. )
  95. if err != nil {
  96. fmt.Printf("Error initializing test database: %v\n", err)
  97. os.Exit(1)
  98. }
  99. models.LoadFixtures()
  100. os.RemoveAll(setting.RepoRootPath)
  101. os.RemoveAll(models.LocalCopyPath())
  102. com.CopyDir(path.Join(curDir, "integrations/gitea-repositories-meta"), setting.RepoRootPath)
  103. log.Printf("[PR] Setting up router\n")
  104. //routers.GlobalInit()
  105. external.RegisterParsers()
  106. markup.Init()
  107. m := routes.NewMacaron()
  108. routes.RegisterRoutes(m)
  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", context2.ClearHandler(m))
  125. log.Printf("[PR] Cleaning up ...\n")
  126. /*
  127. if err = os.RemoveAll(setting.Indexer.IssuePath); err != nil {
  128. fmt.Printf("os.RemoveAll: %v\n", err)
  129. os.Exit(1)
  130. }
  131. if err = os.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 = os.RemoveAll(setting.RepoRootPath); err != nil {
  137. log.Fatalf("os.RemoveAll: %v\n", err)
  138. }
  139. if err = os.RemoveAll(setting.AppDataPath); err != nil {
  140. log.Fatalf("os.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 := ioutil.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" || r.Config().URLs[0] == "git@github.com:go-gitea/gitea.git" { //fetch at index 0
  178. remoteUpstream = r.Config().Name
  179. break
  180. }
  181. }
  182. branch := fmt.Sprintf("pr-%s-%d", pr, time.Now().Unix())
  183. branchRef := plumbing.NewBranchReferenceName(branch)
  184. log.Printf("Fetching PR #%s in %s\n", pr, branch)
  185. if runtime.GOOS == "windows" {
  186. //Use git cli command for windows
  187. runCmd("git", "fetch", remoteUpstream, fmt.Sprintf("pull/%s/head:%s", pr, branch))
  188. } else {
  189. ref := fmt.Sprintf("refs/pull/%s/head:%s", pr, branchRef)
  190. err = repo.Fetch(&git.FetchOptions{
  191. RemoteName: remoteUpstream,
  192. RefSpecs: []config.RefSpec{
  193. config.RefSpec(ref),
  194. },
  195. })
  196. if err != nil {
  197. log.Fatalf("Failed to fetch %s from %s : %v", ref, remoteUpstream, err)
  198. }
  199. }
  200. tree, err := repo.Worktree()
  201. if err != nil {
  202. log.Fatalf("Failed to parse git tree : %v", err)
  203. }
  204. log.Printf("Checkout PR #%s in %s\n", pr, branch)
  205. err = tree.Checkout(&git.CheckoutOptions{
  206. Branch: branchRef,
  207. Force: force,
  208. })
  209. if err != nil {
  210. log.Fatalf("Failed to checkout %s : %v", branch, err)
  211. }
  212. //Copy this file if not exist
  213. if _, err := os.Stat(codeFilePath); os.IsNotExist(err) {
  214. err = os.MkdirAll(filepath.Dir(codeFilePath), 0755)
  215. if err != nil {
  216. log.Fatalf("Failed to duplicate this code file in PR : %v", err)
  217. }
  218. err = ioutil.WriteFile(codeFilePath, dat, 0644)
  219. if err != nil {
  220. log.Fatalf("Failed to duplicate this code file in PR : %v", err)
  221. }
  222. }
  223. time.Sleep(5 * time.Second)
  224. //Start with integration test
  225. runCmd("go", "run", "-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. }