您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package repository
  4. import (
  5. "bytes"
  6. "context"
  7. "fmt"
  8. "os"
  9. "path"
  10. "path/filepath"
  11. "sort"
  12. "strings"
  13. "time"
  14. issues_model "code.gitea.io/gitea/models/issues"
  15. repo_model "code.gitea.io/gitea/models/repo"
  16. user_model "code.gitea.io/gitea/models/user"
  17. "code.gitea.io/gitea/modules/git"
  18. "code.gitea.io/gitea/modules/log"
  19. "code.gitea.io/gitea/modules/options"
  20. "code.gitea.io/gitea/modules/setting"
  21. "code.gitea.io/gitea/modules/templates/vars"
  22. "code.gitea.io/gitea/modules/util"
  23. asymkey_service "code.gitea.io/gitea/services/asymkey"
  24. )
  25. var (
  26. // Gitignores contains the gitiginore files
  27. Gitignores []string
  28. // Licenses contains the license files
  29. Licenses []string
  30. // Readmes contains the readme files
  31. Readmes []string
  32. // LabelTemplates contains the label template files and the list of labels for each file
  33. LabelTemplates map[string]string
  34. )
  35. // ErrIssueLabelTemplateLoad represents a "ErrIssueLabelTemplateLoad" kind of error.
  36. type ErrIssueLabelTemplateLoad struct {
  37. TemplateFile string
  38. OriginalError error
  39. }
  40. // IsErrIssueLabelTemplateLoad checks if an error is a ErrIssueLabelTemplateLoad.
  41. func IsErrIssueLabelTemplateLoad(err error) bool {
  42. _, ok := err.(ErrIssueLabelTemplateLoad)
  43. return ok
  44. }
  45. func (err ErrIssueLabelTemplateLoad) Error() string {
  46. return fmt.Sprintf("Failed to load label template file '%s': %v", err.TemplateFile, err.OriginalError)
  47. }
  48. // GetRepoInitFile returns repository init files
  49. func GetRepoInitFile(tp, name string) ([]byte, error) {
  50. cleanedName := strings.TrimLeft(path.Clean("/"+name), "/")
  51. relPath := path.Join("options", tp, cleanedName)
  52. // Use custom file when available.
  53. customPath := path.Join(setting.CustomPath, relPath)
  54. isFile, err := util.IsFile(customPath)
  55. if err != nil {
  56. log.Error("Unable to check if %s is a file. Error: %v", customPath, err)
  57. }
  58. if isFile {
  59. return os.ReadFile(customPath)
  60. }
  61. switch tp {
  62. case "readme":
  63. return options.Readme(cleanedName)
  64. case "gitignore":
  65. return options.Gitignore(cleanedName)
  66. case "license":
  67. return options.License(cleanedName)
  68. case "label":
  69. return options.Labels(cleanedName)
  70. default:
  71. return []byte{}, fmt.Errorf("Invalid init file type")
  72. }
  73. }
  74. // GetLabelTemplateFile loads the label template file by given name,
  75. // then parses and returns a list of name-color pairs and optionally description.
  76. func GetLabelTemplateFile(name string) ([][3]string, error) {
  77. data, err := GetRepoInitFile("label", name)
  78. if err != nil {
  79. return nil, ErrIssueLabelTemplateLoad{name, fmt.Errorf("GetRepoInitFile: %w", err)}
  80. }
  81. lines := strings.Split(string(data), "\n")
  82. list := make([][3]string, 0, len(lines))
  83. for i := 0; i < len(lines); i++ {
  84. line := strings.TrimSpace(lines[i])
  85. if len(line) == 0 {
  86. continue
  87. }
  88. parts := strings.SplitN(line, ";", 2)
  89. fields := strings.SplitN(parts[0], " ", 2)
  90. if len(fields) != 2 {
  91. return nil, ErrIssueLabelTemplateLoad{name, fmt.Errorf("line is malformed: %s", line)}
  92. }
  93. color := strings.Trim(fields[0], " ")
  94. if len(color) == 6 {
  95. color = "#" + color
  96. }
  97. if !issues_model.LabelColorPattern.MatchString(color) {
  98. return nil, ErrIssueLabelTemplateLoad{name, fmt.Errorf("bad HTML color code in line: %s", line)}
  99. }
  100. var description string
  101. if len(parts) > 1 {
  102. description = strings.TrimSpace(parts[1])
  103. }
  104. fields[1] = strings.TrimSpace(fields[1])
  105. list = append(list, [3]string{fields[1], color, description})
  106. }
  107. return list, nil
  108. }
  109. func loadLabels(labelTemplate string) ([]string, error) {
  110. list, err := GetLabelTemplateFile(labelTemplate)
  111. if err != nil {
  112. return nil, err
  113. }
  114. labels := make([]string, len(list))
  115. for i := 0; i < len(list); i++ {
  116. labels[i] = list[i][0]
  117. }
  118. return labels, nil
  119. }
  120. // LoadLabelsFormatted loads the labels' list of a template file as a string separated by comma
  121. func LoadLabelsFormatted(labelTemplate string) (string, error) {
  122. labels, err := loadLabels(labelTemplate)
  123. return strings.Join(labels, ", "), err
  124. }
  125. // LoadRepoConfig loads the repository config
  126. func LoadRepoConfig() {
  127. // Load .gitignore and license files and readme templates.
  128. types := []string{"gitignore", "license", "readme", "label"}
  129. typeFiles := make([][]string, 4)
  130. for i, t := range types {
  131. files, err := options.Dir(t)
  132. if err != nil {
  133. log.Fatal("Failed to get %s files: %v", t, err)
  134. }
  135. customPath := path.Join(setting.CustomPath, "options", t)
  136. isDir, err := util.IsDir(customPath)
  137. if err != nil {
  138. log.Fatal("Failed to get custom %s files: %v", t, err)
  139. }
  140. if isDir {
  141. customFiles, err := util.StatDir(customPath)
  142. if err != nil {
  143. log.Fatal("Failed to get custom %s files: %v", t, err)
  144. }
  145. for _, f := range customFiles {
  146. if !util.SliceContainsString(files, f, true) {
  147. files = append(files, f)
  148. }
  149. }
  150. }
  151. typeFiles[i] = files
  152. }
  153. Gitignores = typeFiles[0]
  154. Licenses = typeFiles[1]
  155. Readmes = typeFiles[2]
  156. LabelTemplatesFiles := typeFiles[3]
  157. sort.Strings(Gitignores)
  158. sort.Strings(Licenses)
  159. sort.Strings(Readmes)
  160. sort.Strings(LabelTemplatesFiles)
  161. // Load label templates
  162. LabelTemplates = make(map[string]string)
  163. for _, templateFile := range LabelTemplatesFiles {
  164. labels, err := LoadLabelsFormatted(templateFile)
  165. if err != nil {
  166. log.Error("Failed to load labels: %v", err)
  167. }
  168. LabelTemplates[templateFile] = labels
  169. }
  170. // Filter out invalid names and promote preferred licenses.
  171. sortedLicenses := make([]string, 0, len(Licenses))
  172. for _, name := range setting.Repository.PreferredLicenses {
  173. if util.SliceContainsString(Licenses, name, true) {
  174. sortedLicenses = append(sortedLicenses, name)
  175. }
  176. }
  177. for _, name := range Licenses {
  178. if !util.SliceContainsString(setting.Repository.PreferredLicenses, name, true) {
  179. sortedLicenses = append(sortedLicenses, name)
  180. }
  181. }
  182. Licenses = sortedLicenses
  183. }
  184. func prepareRepoCommit(ctx context.Context, repo *repo_model.Repository, tmpDir, repoPath string, opts CreateRepoOptions) error {
  185. commitTimeStr := time.Now().Format(time.RFC3339)
  186. authorSig := repo.Owner.NewGitSig()
  187. // Because this may call hooks we should pass in the environment
  188. env := append(os.Environ(),
  189. "GIT_AUTHOR_NAME="+authorSig.Name,
  190. "GIT_AUTHOR_EMAIL="+authorSig.Email,
  191. "GIT_AUTHOR_DATE="+commitTimeStr,
  192. "GIT_COMMITTER_NAME="+authorSig.Name,
  193. "GIT_COMMITTER_EMAIL="+authorSig.Email,
  194. "GIT_COMMITTER_DATE="+commitTimeStr,
  195. )
  196. // Clone to temporary path and do the init commit.
  197. if stdout, _, err := git.NewCommand(ctx, "clone").AddDynamicArguments(repoPath, tmpDir).
  198. SetDescription(fmt.Sprintf("prepareRepoCommit (git clone): %s to %s", repoPath, tmpDir)).
  199. RunStdString(&git.RunOpts{Dir: "", Env: env}); err != nil {
  200. log.Error("Failed to clone from %v into %s: stdout: %s\nError: %v", repo, tmpDir, stdout, err)
  201. return fmt.Errorf("git clone: %w", err)
  202. }
  203. // README
  204. data, err := GetRepoInitFile("readme", opts.Readme)
  205. if err != nil {
  206. return fmt.Errorf("GetRepoInitFile[%s]: %w", opts.Readme, err)
  207. }
  208. cloneLink := repo.CloneLink()
  209. match := map[string]string{
  210. "Name": repo.Name,
  211. "Description": repo.Description,
  212. "CloneURL.SSH": cloneLink.SSH,
  213. "CloneURL.HTTPS": cloneLink.HTTPS,
  214. "OwnerName": repo.OwnerName,
  215. }
  216. res, err := vars.Expand(string(data), match)
  217. if err != nil {
  218. // here we could just log the error and continue the rendering
  219. log.Error("unable to expand template vars for repo README: %s, err: %v", opts.Readme, err)
  220. }
  221. if err = os.WriteFile(filepath.Join(tmpDir, "README.md"),
  222. []byte(res), 0o644); err != nil {
  223. return fmt.Errorf("write README.md: %w", err)
  224. }
  225. // .gitignore
  226. if len(opts.Gitignores) > 0 {
  227. var buf bytes.Buffer
  228. names := strings.Split(opts.Gitignores, ",")
  229. for _, name := range names {
  230. data, err = GetRepoInitFile("gitignore", name)
  231. if err != nil {
  232. return fmt.Errorf("GetRepoInitFile[%s]: %w", name, err)
  233. }
  234. buf.WriteString("# ---> " + name + "\n")
  235. buf.Write(data)
  236. buf.WriteString("\n")
  237. }
  238. if buf.Len() > 0 {
  239. if err = os.WriteFile(filepath.Join(tmpDir, ".gitignore"), buf.Bytes(), 0o644); err != nil {
  240. return fmt.Errorf("write .gitignore: %w", err)
  241. }
  242. }
  243. }
  244. // LICENSE
  245. if len(opts.License) > 0 {
  246. data, err = GetRepoInitFile("license", opts.License)
  247. if err != nil {
  248. return fmt.Errorf("GetRepoInitFile[%s]: %w", opts.License, err)
  249. }
  250. if err = os.WriteFile(filepath.Join(tmpDir, "LICENSE"), data, 0o644); err != nil {
  251. return fmt.Errorf("write LICENSE: %w", err)
  252. }
  253. }
  254. return nil
  255. }
  256. // initRepoCommit temporarily changes with work directory.
  257. func initRepoCommit(ctx context.Context, tmpPath string, repo *repo_model.Repository, u *user_model.User, defaultBranch string) (err error) {
  258. commitTimeStr := time.Now().Format(time.RFC3339)
  259. sig := u.NewGitSig()
  260. // Because this may call hooks we should pass in the environment
  261. env := append(os.Environ(),
  262. "GIT_AUTHOR_NAME="+sig.Name,
  263. "GIT_AUTHOR_EMAIL="+sig.Email,
  264. "GIT_AUTHOR_DATE="+commitTimeStr,
  265. "GIT_COMMITTER_DATE="+commitTimeStr,
  266. )
  267. committerName := sig.Name
  268. committerEmail := sig.Email
  269. if stdout, _, err := git.NewCommand(ctx, "add", "--all").
  270. SetDescription(fmt.Sprintf("initRepoCommit (git add): %s", tmpPath)).
  271. RunStdString(&git.RunOpts{Dir: tmpPath}); err != nil {
  272. log.Error("git add --all failed: Stdout: %s\nError: %v", stdout, err)
  273. return fmt.Errorf("git add --all: %w", err)
  274. }
  275. cmd := git.NewCommand(ctx,
  276. "commit", git.CmdArg(fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email)),
  277. "-m", "Initial commit",
  278. )
  279. sign, keyID, signer, _ := asymkey_service.SignInitialCommit(ctx, tmpPath, u)
  280. if sign {
  281. cmd.AddArguments(git.CmdArg("-S" + keyID))
  282. if repo.GetTrustModel() == repo_model.CommitterTrustModel || repo.GetTrustModel() == repo_model.CollaboratorCommitterTrustModel {
  283. // need to set the committer to the KeyID owner
  284. committerName = signer.Name
  285. committerEmail = signer.Email
  286. }
  287. } else {
  288. cmd.AddArguments("--no-gpg-sign")
  289. }
  290. env = append(env,
  291. "GIT_COMMITTER_NAME="+committerName,
  292. "GIT_COMMITTER_EMAIL="+committerEmail,
  293. )
  294. if stdout, _, err := cmd.
  295. SetDescription(fmt.Sprintf("initRepoCommit (git commit): %s", tmpPath)).
  296. RunStdString(&git.RunOpts{Dir: tmpPath, Env: env}); err != nil {
  297. log.Error("Failed to commit: %v: Stdout: %s\nError: %v", cmd.String(), stdout, err)
  298. return fmt.Errorf("git commit: %w", err)
  299. }
  300. if len(defaultBranch) == 0 {
  301. defaultBranch = setting.Repository.DefaultBranch
  302. }
  303. if stdout, _, err := git.NewCommand(ctx, "push", "origin").AddDynamicArguments("HEAD:" + defaultBranch).
  304. SetDescription(fmt.Sprintf("initRepoCommit (git push): %s", tmpPath)).
  305. RunStdString(&git.RunOpts{Dir: tmpPath, Env: InternalPushingEnvironment(u, repo)}); err != nil {
  306. log.Error("Failed to push back to HEAD: Stdout: %s\nError: %v", stdout, err)
  307. return fmt.Errorf("git push: %w", err)
  308. }
  309. return nil
  310. }
  311. func checkInitRepository(ctx context.Context, owner, name string) (err error) {
  312. // Somehow the directory could exist.
  313. repoPath := repo_model.RepoPath(owner, name)
  314. isExist, err := util.IsExist(repoPath)
  315. if err != nil {
  316. log.Error("Unable to check if %s exists. Error: %v", repoPath, err)
  317. return err
  318. }
  319. if isExist {
  320. return repo_model.ErrRepoFilesAlreadyExist{
  321. Uname: owner,
  322. Name: name,
  323. }
  324. }
  325. // Init git bare new repository.
  326. if err = git.InitRepository(ctx, repoPath, true); err != nil {
  327. return fmt.Errorf("git.InitRepository: %w", err)
  328. } else if err = createDelegateHooks(repoPath); err != nil {
  329. return fmt.Errorf("createDelegateHooks: %w", err)
  330. }
  331. return nil
  332. }
  333. // InitRepository initializes README and .gitignore if needed.
  334. func initRepository(ctx context.Context, repoPath string, u *user_model.User, repo *repo_model.Repository, opts CreateRepoOptions) (err error) {
  335. if err = checkInitRepository(ctx, repo.OwnerName, repo.Name); err != nil {
  336. return err
  337. }
  338. // Initialize repository according to user's choice.
  339. if opts.AutoInit {
  340. tmpDir, err := os.MkdirTemp(os.TempDir(), "gitea-"+repo.Name)
  341. if err != nil {
  342. return fmt.Errorf("Failed to create temp dir for repository %s: %w", repo.RepoPath(), err)
  343. }
  344. defer func() {
  345. if err := util.RemoveAll(tmpDir); err != nil {
  346. log.Warn("Unable to remove temporary directory: %s: Error: %v", tmpDir, err)
  347. }
  348. }()
  349. if err = prepareRepoCommit(ctx, repo, tmpDir, repoPath, opts); err != nil {
  350. return fmt.Errorf("prepareRepoCommit: %w", err)
  351. }
  352. // Apply changes and commit.
  353. if err = initRepoCommit(ctx, tmpDir, repo, u, opts.DefaultBranch); err != nil {
  354. return fmt.Errorf("initRepoCommit: %w", err)
  355. }
  356. }
  357. // Re-fetch the repository from database before updating it (else it would
  358. // override changes that were done earlier with sql)
  359. if repo, err = repo_model.GetRepositoryByID(ctx, repo.ID); err != nil {
  360. return fmt.Errorf("getRepositoryByID: %w", err)
  361. }
  362. if !opts.AutoInit {
  363. repo.IsEmpty = true
  364. }
  365. repo.DefaultBranch = setting.Repository.DefaultBranch
  366. if len(opts.DefaultBranch) > 0 {
  367. repo.DefaultBranch = opts.DefaultBranch
  368. gitRepo, err := git.OpenRepository(ctx, repo.RepoPath())
  369. if err != nil {
  370. return fmt.Errorf("openRepository: %w", err)
  371. }
  372. defer gitRepo.Close()
  373. if err = gitRepo.SetDefaultBranch(repo.DefaultBranch); err != nil {
  374. return fmt.Errorf("setDefaultBranch: %w", err)
  375. }
  376. }
  377. if err = UpdateRepository(ctx, repo, false); err != nil {
  378. return fmt.Errorf("updateRepository: %w", err)
  379. }
  380. return nil
  381. }
  382. // InitializeLabels adds a label set to a repository using a template
  383. func InitializeLabels(ctx context.Context, id int64, labelTemplate string, isOrg bool) error {
  384. list, err := GetLabelTemplateFile(labelTemplate)
  385. if err != nil {
  386. return err
  387. }
  388. labels := make([]*issues_model.Label, len(list))
  389. for i := 0; i < len(list); i++ {
  390. labels[i] = &issues_model.Label{
  391. Name: list[i][0],
  392. Description: list[i][2],
  393. Color: list[i][1],
  394. }
  395. if isOrg {
  396. labels[i].OrgID = id
  397. } else {
  398. labels[i].RepoID = id
  399. }
  400. }
  401. for _, label := range labels {
  402. if err = issues_model.NewLabel(ctx, label); err != nil {
  403. return err
  404. }
  405. }
  406. return nil
  407. }