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.

init.go 7.0 kB

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