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

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