Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

init.go 6.4KB

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