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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package repository
  4. import (
  5. "context"
  6. "fmt"
  7. "os"
  8. "path/filepath"
  9. "sort"
  10. "strings"
  11. "time"
  12. issues_model "code.gitea.io/gitea/models/issues"
  13. repo_model "code.gitea.io/gitea/models/repo"
  14. user_model "code.gitea.io/gitea/models/user"
  15. "code.gitea.io/gitea/modules/git"
  16. "code.gitea.io/gitea/modules/label"
  17. "code.gitea.io/gitea/modules/log"
  18. "code.gitea.io/gitea/modules/options"
  19. "code.gitea.io/gitea/modules/setting"
  20. "code.gitea.io/gitea/modules/util"
  21. asymkey_service "code.gitea.io/gitea/services/asymkey"
  22. )
  23. type OptionFile struct {
  24. DisplayName string
  25. Description string
  26. }
  27. var (
  28. // Gitignores contains the gitiginore files
  29. Gitignores []string
  30. // Licenses contains the license files
  31. Licenses []string
  32. // Readmes contains the readme files
  33. Readmes []string
  34. // LabelTemplateFiles contains the label template files, each item has its DisplayName and Description
  35. LabelTemplateFiles []OptionFile
  36. labelTemplateFileMap = map[string]string{} // DisplayName => FileName mapping
  37. )
  38. type optionFileList struct {
  39. all []string // all files provided by bindata & custom-path. Sorted.
  40. custom []string // custom files provided by custom-path. Non-sorted, internal use only.
  41. }
  42. // mergeCustomLabelFiles merges the custom label files. Always use the file's main name (DisplayName) as the key to de-duplicate.
  43. func mergeCustomLabelFiles(fl optionFileList) []string {
  44. exts := map[string]int{"": 0, ".yml": 1, ".yaml": 2} // "yaml" file has the highest priority to be used.
  45. m := map[string]string{}
  46. merge := func(list []string) {
  47. sort.Slice(list, func(i, j int) bool { return exts[filepath.Ext(list[i])] < exts[filepath.Ext(list[j])] })
  48. for _, f := range list {
  49. m[strings.TrimSuffix(f, filepath.Ext(f))] = f
  50. }
  51. }
  52. merge(fl.all)
  53. merge(fl.custom)
  54. files := make([]string, 0, len(m))
  55. for _, f := range m {
  56. files = append(files, f)
  57. }
  58. sort.Strings(files)
  59. return files
  60. }
  61. // LoadRepoConfig loads the repository config
  62. func LoadRepoConfig() error {
  63. types := []string{"gitignore", "license", "readme", "label"} // option file directories
  64. typeFiles := make([]optionFileList, len(types))
  65. for i, t := range types {
  66. var err error
  67. if typeFiles[i].all, err = options.AssetFS().ListFiles(t, true); err != nil {
  68. return fmt.Errorf("failed to list %s files: %w", t, err)
  69. }
  70. sort.Strings(typeFiles[i].all)
  71. customPath := filepath.Join(setting.CustomPath, "options", t)
  72. if isDir, err := util.IsDir(customPath); err != nil {
  73. return fmt.Errorf("failed to check custom %s dir: %w", t, err)
  74. } else if isDir {
  75. if typeFiles[i].custom, err = util.StatDir(customPath); err != nil {
  76. return fmt.Errorf("failed to list custom %s files: %w", t, err)
  77. }
  78. }
  79. }
  80. Gitignores = typeFiles[0].all
  81. Licenses = typeFiles[1].all
  82. Readmes = typeFiles[2].all
  83. // Load label templates
  84. LabelTemplateFiles = nil
  85. labelTemplateFileMap = map[string]string{}
  86. for _, file := range mergeCustomLabelFiles(typeFiles[3]) {
  87. description, err := label.LoadTemplateDescription(file)
  88. if err != nil {
  89. return fmt.Errorf("failed to load labels: %w", err)
  90. }
  91. displayName := strings.TrimSuffix(file, filepath.Ext(file))
  92. labelTemplateFileMap[displayName] = file
  93. LabelTemplateFiles = append(LabelTemplateFiles, OptionFile{DisplayName: displayName, Description: description})
  94. }
  95. // Filter out invalid names and promote preferred licenses.
  96. sortedLicenses := make([]string, 0, len(Licenses))
  97. for _, name := range setting.Repository.PreferredLicenses {
  98. if util.SliceContainsString(Licenses, name, true) {
  99. sortedLicenses = append(sortedLicenses, name)
  100. }
  101. }
  102. for _, name := range Licenses {
  103. if !util.SliceContainsString(setting.Repository.PreferredLicenses, name, true) {
  104. sortedLicenses = append(sortedLicenses, name)
  105. }
  106. }
  107. Licenses = sortedLicenses
  108. return nil
  109. }
  110. // InitRepoCommit temporarily changes with work directory.
  111. func InitRepoCommit(ctx context.Context, tmpPath string, repo *repo_model.Repository, u *user_model.User, defaultBranch string) (err error) {
  112. commitTimeStr := time.Now().Format(time.RFC3339)
  113. sig := u.NewGitSig()
  114. // Because this may call hooks we should pass in the environment
  115. env := append(os.Environ(),
  116. "GIT_AUTHOR_NAME="+sig.Name,
  117. "GIT_AUTHOR_EMAIL="+sig.Email,
  118. "GIT_AUTHOR_DATE="+commitTimeStr,
  119. "GIT_COMMITTER_DATE="+commitTimeStr,
  120. )
  121. committerName := sig.Name
  122. committerEmail := sig.Email
  123. if stdout, _, err := git.NewCommand(ctx, "add", "--all").
  124. SetDescription(fmt.Sprintf("initRepoCommit (git add): %s", tmpPath)).
  125. RunStdString(&git.RunOpts{Dir: tmpPath}); err != nil {
  126. log.Error("git add --all failed: Stdout: %s\nError: %v", stdout, err)
  127. return fmt.Errorf("git add --all: %w", err)
  128. }
  129. cmd := git.NewCommand(ctx, "commit", "--message=Initial commit").
  130. AddOptionFormat("--author='%s <%s>'", sig.Name, sig.Email)
  131. sign, keyID, signer, _ := asymkey_service.SignInitialCommit(ctx, tmpPath, u)
  132. if sign {
  133. cmd.AddOptionFormat("-S%s", keyID)
  134. if repo.GetTrustModel() == repo_model.CommitterTrustModel || repo.GetTrustModel() == repo_model.CollaboratorCommitterTrustModel {
  135. // need to set the committer to the KeyID owner
  136. committerName = signer.Name
  137. committerEmail = signer.Email
  138. }
  139. } else {
  140. cmd.AddArguments("--no-gpg-sign")
  141. }
  142. env = append(env,
  143. "GIT_COMMITTER_NAME="+committerName,
  144. "GIT_COMMITTER_EMAIL="+committerEmail,
  145. )
  146. if stdout, _, err := cmd.
  147. SetDescription(fmt.Sprintf("initRepoCommit (git commit): %s", tmpPath)).
  148. RunStdString(&git.RunOpts{Dir: tmpPath, Env: env}); err != nil {
  149. log.Error("Failed to commit: %v: Stdout: %s\nError: %v", cmd.String(), stdout, err)
  150. return fmt.Errorf("git commit: %w", err)
  151. }
  152. if len(defaultBranch) == 0 {
  153. defaultBranch = setting.Repository.DefaultBranch
  154. }
  155. if stdout, _, err := git.NewCommand(ctx, "push", "origin").AddDynamicArguments("HEAD:" + defaultBranch).
  156. SetDescription(fmt.Sprintf("initRepoCommit (git push): %s", tmpPath)).
  157. RunStdString(&git.RunOpts{Dir: tmpPath, Env: InternalPushingEnvironment(u, repo)}); err != nil {
  158. log.Error("Failed to push back to HEAD: Stdout: %s\nError: %v", stdout, err)
  159. return fmt.Errorf("git push: %w", err)
  160. }
  161. return nil
  162. }
  163. func CheckInitRepository(ctx context.Context, owner, name string) (err error) {
  164. // Somehow the directory could exist.
  165. repoPath := repo_model.RepoPath(owner, name)
  166. isExist, err := util.IsExist(repoPath)
  167. if err != nil {
  168. log.Error("Unable to check if %s exists. Error: %v", repoPath, err)
  169. return err
  170. }
  171. if isExist {
  172. return repo_model.ErrRepoFilesAlreadyExist{
  173. Uname: owner,
  174. Name: name,
  175. }
  176. }
  177. // Init git bare new repository.
  178. if err = git.InitRepository(ctx, repoPath, true); err != nil {
  179. return fmt.Errorf("git.InitRepository: %w", err)
  180. } else if err = CreateDelegateHooks(repoPath); err != nil {
  181. return fmt.Errorf("createDelegateHooks: %w", err)
  182. }
  183. return nil
  184. }
  185. // InitializeLabels adds a label set to a repository using a template
  186. func InitializeLabels(ctx context.Context, id int64, labelTemplate string, isOrg bool) error {
  187. list, err := LoadTemplateLabelsByDisplayName(labelTemplate)
  188. if err != nil {
  189. return err
  190. }
  191. labels := make([]*issues_model.Label, len(list))
  192. for i := 0; i < len(list); i++ {
  193. labels[i] = &issues_model.Label{
  194. Name: list[i].Name,
  195. Exclusive: list[i].Exclusive,
  196. Description: list[i].Description,
  197. Color: list[i].Color,
  198. }
  199. if isOrg {
  200. labels[i].OrgID = id
  201. } else {
  202. labels[i].RepoID = id
  203. }
  204. }
  205. for _, label := range labels {
  206. if err = issues_model.NewLabel(ctx, label); err != nil {
  207. return err
  208. }
  209. }
  210. return nil
  211. }
  212. // LoadTemplateLabelsByDisplayName loads a label template by its display name
  213. func LoadTemplateLabelsByDisplayName(displayName string) ([]*label.Label, error) {
  214. if fileName, ok := labelTemplateFileMap[displayName]; ok {
  215. return label.LoadTemplateFile(fileName)
  216. }
  217. return nil, label.ErrTemplateLoad{TemplateFile: displayName, OriginalError: fmt.Errorf("label template %q not found", displayName)}
  218. }