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.

init.go 7.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. // Copyright 2019 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 repository
  5. import (
  6. "bytes"
  7. "fmt"
  8. "io/ioutil"
  9. "os"
  10. "path/filepath"
  11. "strings"
  12. "time"
  13. "code.gitea.io/gitea/models"
  14. "code.gitea.io/gitea/modules/git"
  15. "code.gitea.io/gitea/modules/log"
  16. "code.gitea.io/gitea/modules/setting"
  17. "github.com/mcuadros/go-version"
  18. "github.com/unknwon/com"
  19. )
  20. func prepareRepoCommit(ctx models.DBContext, repo *models.Repository, tmpDir, repoPath string, opts models.CreateRepoOptions) error {
  21. commitTimeStr := time.Now().Format(time.RFC3339)
  22. authorSig := repo.Owner.NewGitSig()
  23. // Because this may call hooks we should pass in the environment
  24. env := append(os.Environ(),
  25. "GIT_AUTHOR_NAME="+authorSig.Name,
  26. "GIT_AUTHOR_EMAIL="+authorSig.Email,
  27. "GIT_AUTHOR_DATE="+commitTimeStr,
  28. "GIT_COMMITTER_NAME="+authorSig.Name,
  29. "GIT_COMMITTER_EMAIL="+authorSig.Email,
  30. "GIT_COMMITTER_DATE="+commitTimeStr,
  31. )
  32. // Clone to temporary path and do the init commit.
  33. if stdout, err := git.NewCommand("clone", repoPath, tmpDir).
  34. SetDescription(fmt.Sprintf("prepareRepoCommit (git clone): %s to %s", repoPath, tmpDir)).
  35. RunInDirWithEnv("", env); err != nil {
  36. log.Error("Failed to clone from %v into %s: stdout: %s\nError: %v", repo, tmpDir, stdout, err)
  37. return fmt.Errorf("git clone: %v", err)
  38. }
  39. // README
  40. data, err := models.GetRepoInitFile("readme", opts.Readme)
  41. if err != nil {
  42. return fmt.Errorf("GetRepoInitFile[%s]: %v", opts.Readme, err)
  43. }
  44. cloneLink := repo.CloneLink()
  45. match := map[string]string{
  46. "Name": repo.Name,
  47. "Description": repo.Description,
  48. "CloneURL.SSH": cloneLink.SSH,
  49. "CloneURL.HTTPS": cloneLink.HTTPS,
  50. "OwnerName": repo.OwnerName,
  51. }
  52. if err = ioutil.WriteFile(filepath.Join(tmpDir, "README.md"),
  53. []byte(com.Expand(string(data), match)), 0644); err != nil {
  54. return fmt.Errorf("write README.md: %v", err)
  55. }
  56. // .gitignore
  57. if len(opts.Gitignores) > 0 {
  58. var buf bytes.Buffer
  59. names := strings.Split(opts.Gitignores, ",")
  60. for _, name := range names {
  61. data, err = models.GetRepoInitFile("gitignore", name)
  62. if err != nil {
  63. return fmt.Errorf("GetRepoInitFile[%s]: %v", name, err)
  64. }
  65. buf.WriteString("# ---> " + name + "\n")
  66. buf.Write(data)
  67. buf.WriteString("\n")
  68. }
  69. if buf.Len() > 0 {
  70. if err = ioutil.WriteFile(filepath.Join(tmpDir, ".gitignore"), buf.Bytes(), 0644); err != nil {
  71. return fmt.Errorf("write .gitignore: %v", err)
  72. }
  73. }
  74. }
  75. // LICENSE
  76. if len(opts.License) > 0 {
  77. data, err = models.GetRepoInitFile("license", opts.License)
  78. if err != nil {
  79. return fmt.Errorf("GetRepoInitFile[%s]: %v", opts.License, err)
  80. }
  81. if err = ioutil.WriteFile(filepath.Join(tmpDir, "LICENSE"), data, 0644); err != nil {
  82. return fmt.Errorf("write LICENSE: %v", err)
  83. }
  84. }
  85. return nil
  86. }
  87. // initRepoCommit temporarily changes with work directory.
  88. func initRepoCommit(tmpPath string, repo *models.Repository, u *models.User, defaultBranch string) (err error) {
  89. commitTimeStr := time.Now().Format(time.RFC3339)
  90. sig := u.NewGitSig()
  91. // Because this may call hooks we should pass in the environment
  92. env := append(os.Environ(),
  93. "GIT_AUTHOR_NAME="+sig.Name,
  94. "GIT_AUTHOR_EMAIL="+sig.Email,
  95. "GIT_AUTHOR_DATE="+commitTimeStr,
  96. "GIT_COMMITTER_NAME="+sig.Name,
  97. "GIT_COMMITTER_EMAIL="+sig.Email,
  98. "GIT_COMMITTER_DATE="+commitTimeStr,
  99. )
  100. if stdout, err := git.NewCommand("add", "--all").
  101. SetDescription(fmt.Sprintf("initRepoCommit (git add): %s", tmpPath)).
  102. RunInDir(tmpPath); err != nil {
  103. log.Error("git add --all failed: Stdout: %s\nError: %v", stdout, err)
  104. return fmt.Errorf("git add --all: %v", err)
  105. }
  106. binVersion, err := git.BinVersion()
  107. if err != nil {
  108. return fmt.Errorf("Unable to get git version: %v", err)
  109. }
  110. args := []string{
  111. "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  112. "-m", "Initial commit",
  113. }
  114. if version.Compare(binVersion, "1.7.9", ">=") {
  115. sign, keyID, _ := models.SignInitialCommit(tmpPath, u)
  116. if sign {
  117. args = append(args, "-S"+keyID)
  118. } else if version.Compare(binVersion, "2.0.0", ">=") {
  119. args = append(args, "--no-gpg-sign")
  120. }
  121. }
  122. if stdout, err := git.NewCommand(args...).
  123. SetDescription(fmt.Sprintf("initRepoCommit (git commit): %s", tmpPath)).
  124. RunInDirWithEnv(tmpPath, env); err != nil {
  125. log.Error("Failed to commit: %v: Stdout: %s\nError: %v", args, stdout, err)
  126. return fmt.Errorf("git commit: %v", err)
  127. }
  128. if len(defaultBranch) == 0 {
  129. defaultBranch = setting.Repository.DefaultBranch
  130. }
  131. if stdout, err := git.NewCommand("push", "origin", "master:"+defaultBranch).
  132. SetDescription(fmt.Sprintf("initRepoCommit (git push): %s", tmpPath)).
  133. RunInDirWithEnv(tmpPath, models.InternalPushingEnvironment(u, repo)); err != nil {
  134. log.Error("Failed to push back to master: Stdout: %s\nError: %v", stdout, err)
  135. return fmt.Errorf("git push: %v", err)
  136. }
  137. return nil
  138. }
  139. func checkInitRepository(repoPath string) (err error) {
  140. // Somehow the directory could exist.
  141. if com.IsExist(repoPath) {
  142. return fmt.Errorf("checkInitRepository: path already exists: %s", repoPath)
  143. }
  144. // Init git bare new repository.
  145. if err = git.InitRepository(repoPath, true); err != nil {
  146. return fmt.Errorf("git.InitRepository: %v", err)
  147. } else if err = createDelegateHooks(repoPath); err != nil {
  148. return fmt.Errorf("createDelegateHooks: %v", err)
  149. }
  150. return nil
  151. }
  152. // InitRepository initializes README and .gitignore if needed.
  153. func initRepository(ctx models.DBContext, repoPath string, u *models.User, repo *models.Repository, opts models.CreateRepoOptions) (err error) {
  154. if err = checkInitRepository(repoPath); err != nil {
  155. return err
  156. }
  157. // Initialize repository according to user's choice.
  158. if opts.AutoInit {
  159. tmpDir, err := ioutil.TempDir(os.TempDir(), "gitea-"+repo.Name)
  160. if err != nil {
  161. return fmt.Errorf("Failed to create temp dir for repository %s: %v", repo.RepoPath(), err)
  162. }
  163. defer os.RemoveAll(tmpDir)
  164. if err = prepareRepoCommit(ctx, repo, tmpDir, repoPath, opts); err != nil {
  165. return fmt.Errorf("prepareRepoCommit: %v", err)
  166. }
  167. // Apply changes and commit.
  168. if err = initRepoCommit(tmpDir, repo, u, opts.DefaultBranch); err != nil {
  169. return fmt.Errorf("initRepoCommit: %v", err)
  170. }
  171. }
  172. // Re-fetch the repository from database before updating it (else it would
  173. // override changes that were done earlier with sql)
  174. if repo, err = models.GetRepositoryByIDCtx(ctx, repo.ID); err != nil {
  175. return fmt.Errorf("getRepositoryByID: %v", err)
  176. }
  177. if !opts.AutoInit {
  178. repo.IsEmpty = true
  179. }
  180. repo.DefaultBranch = "master"
  181. if len(opts.DefaultBranch) > 0 {
  182. repo.DefaultBranch = opts.DefaultBranch
  183. gitRepo, err := git.OpenRepository(repo.RepoPath())
  184. if err != nil {
  185. return fmt.Errorf("openRepository: %v", err)
  186. }
  187. if err = gitRepo.SetDefaultBranch(repo.DefaultBranch); err != nil {
  188. return fmt.Errorf("setDefaultBranch: %v", err)
  189. }
  190. }
  191. if err = models.UpdateRepositoryCtx(ctx, repo, false); err != nil {
  192. return fmt.Errorf("updateRepository: %v", err)
  193. }
  194. return nil
  195. }