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.

385 lines
10 KiB

  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 models
  5. import (
  6. "fmt"
  7. "io/ioutil"
  8. "os"
  9. "path"
  10. "path/filepath"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "code.gitea.io/gitea/modules/git"
  15. "code.gitea.io/gitea/modules/log"
  16. "code.gitea.io/gitea/modules/util"
  17. "github.com/gobwas/glob"
  18. "github.com/unknwon/com"
  19. )
  20. // GenerateRepoOptions contains the template units to generate
  21. type GenerateRepoOptions struct {
  22. Name string
  23. Description string
  24. Private bool
  25. GitContent bool
  26. Topics bool
  27. GitHooks bool
  28. Webhooks bool
  29. Avatar bool
  30. IssueLabels bool
  31. }
  32. // IsValid checks whether at least one option is chosen for generation
  33. func (gro GenerateRepoOptions) IsValid() bool {
  34. return gro.GitContent || gro.Topics || gro.GitHooks || gro.Webhooks || gro.Avatar || gro.IssueLabels // or other items as they are added
  35. }
  36. // GiteaTemplate holds information about a .gitea/template file
  37. type GiteaTemplate struct {
  38. Path string
  39. Content []byte
  40. globs []glob.Glob
  41. }
  42. // Globs parses the .gitea/template globs or returns them if they were already parsed
  43. func (gt GiteaTemplate) Globs() []glob.Glob {
  44. if gt.globs != nil {
  45. return gt.globs
  46. }
  47. gt.globs = make([]glob.Glob, 0)
  48. lines := strings.Split(string(util.NormalizeEOL(gt.Content)), "\n")
  49. for _, line := range lines {
  50. line = strings.TrimSpace(line)
  51. if line == "" || strings.HasPrefix(line, "#") {
  52. continue
  53. }
  54. g, err := glob.Compile(line, '/')
  55. if err != nil {
  56. log.Info("Invalid glob expression '%s' (skipped): %v", line, err)
  57. continue
  58. }
  59. gt.globs = append(gt.globs, g)
  60. }
  61. return gt.globs
  62. }
  63. func checkGiteaTemplate(tmpDir string) (*GiteaTemplate, error) {
  64. gtPath := filepath.Join(tmpDir, ".gitea", "template")
  65. if _, err := os.Stat(gtPath); os.IsNotExist(err) {
  66. return nil, nil
  67. } else if err != nil {
  68. return nil, err
  69. }
  70. content, err := ioutil.ReadFile(gtPath)
  71. if err != nil {
  72. return nil, err
  73. }
  74. gt := &GiteaTemplate{
  75. Path: gtPath,
  76. Content: content,
  77. }
  78. return gt, nil
  79. }
  80. func generateRepoCommit(e Engine, repo, templateRepo, generateRepo *Repository, tmpDir string) error {
  81. commitTimeStr := time.Now().Format(time.RFC3339)
  82. authorSig := repo.Owner.NewGitSig()
  83. // Because this may call hooks we should pass in the environment
  84. env := append(os.Environ(),
  85. "GIT_AUTHOR_NAME="+authorSig.Name,
  86. "GIT_AUTHOR_EMAIL="+authorSig.Email,
  87. "GIT_AUTHOR_DATE="+commitTimeStr,
  88. "GIT_COMMITTER_NAME="+authorSig.Name,
  89. "GIT_COMMITTER_EMAIL="+authorSig.Email,
  90. "GIT_COMMITTER_DATE="+commitTimeStr,
  91. )
  92. // Clone to temporary path and do the init commit.
  93. templateRepoPath := templateRepo.repoPath(e)
  94. if err := git.Clone(templateRepoPath, tmpDir, git.CloneRepoOptions{
  95. Depth: 1,
  96. }); err != nil {
  97. return fmt.Errorf("git clone: %v", err)
  98. }
  99. if err := os.RemoveAll(path.Join(tmpDir, ".git")); err != nil {
  100. return fmt.Errorf("remove git dir: %v", err)
  101. }
  102. // Variable expansion
  103. gt, err := checkGiteaTemplate(tmpDir)
  104. if err != nil {
  105. return fmt.Errorf("checkGiteaTemplate: %v", err)
  106. }
  107. if err := os.Remove(gt.Path); err != nil {
  108. return fmt.Errorf("remove .giteatemplate: %v", err)
  109. }
  110. // Avoid walking tree if there are no globs
  111. if len(gt.Globs()) > 0 {
  112. tmpDirSlash := strings.TrimSuffix(filepath.ToSlash(tmpDir), "/") + "/"
  113. if err := filepath.Walk(tmpDirSlash, func(path string, info os.FileInfo, walkErr error) error {
  114. if walkErr != nil {
  115. return walkErr
  116. }
  117. if info.IsDir() {
  118. return nil
  119. }
  120. base := strings.TrimPrefix(filepath.ToSlash(path), tmpDirSlash)
  121. for _, g := range gt.Globs() {
  122. if g.Match(base) {
  123. content, err := ioutil.ReadFile(path)
  124. if err != nil {
  125. return err
  126. }
  127. if err := ioutil.WriteFile(path,
  128. []byte(generateExpansion(string(content), templateRepo, generateRepo)),
  129. 0644); err != nil {
  130. return err
  131. }
  132. break
  133. }
  134. }
  135. return nil
  136. }); err != nil {
  137. return err
  138. }
  139. }
  140. if err := git.InitRepository(tmpDir, false); err != nil {
  141. return err
  142. }
  143. repoPath := repo.repoPath(e)
  144. if stdout, err := git.NewCommand("remote", "add", "origin", repoPath).
  145. SetDescription(fmt.Sprintf("generateRepoCommit (git remote add): %s to %s", templateRepoPath, tmpDir)).
  146. RunInDirWithEnv(tmpDir, env); err != nil {
  147. log.Error("Unable to add %v as remote origin to temporary repo to %s: stdout %s\nError: %v", repo, tmpDir, stdout, err)
  148. return fmt.Errorf("git remote add: %v", err)
  149. }
  150. return initRepoCommit(tmpDir, repo, repo.Owner)
  151. }
  152. // generateRepository initializes repository from template
  153. func generateRepository(e Engine, repo, templateRepo, generateRepo *Repository) (err error) {
  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(e), err)
  157. }
  158. defer func() {
  159. if err := os.RemoveAll(tmpDir); err != nil {
  160. log.Error("RemoveAll: %v", err)
  161. }
  162. }()
  163. if err = generateRepoCommit(e, repo, templateRepo, generateRepo, tmpDir); err != nil {
  164. return fmt.Errorf("generateRepoCommit: %v", err)
  165. }
  166. // re-fetch repo
  167. if repo, err = getRepositoryByID(e, repo.ID); err != nil {
  168. return fmt.Errorf("getRepositoryByID: %v", err)
  169. }
  170. repo.DefaultBranch = "master"
  171. if err = updateRepository(e, repo, false); err != nil {
  172. return fmt.Errorf("updateRepository: %v", err)
  173. }
  174. return nil
  175. }
  176. // GenerateRepository generates a repository from a template
  177. func GenerateRepository(ctx DBContext, doer, owner *User, templateRepo *Repository, opts GenerateRepoOptions) (_ *Repository, err error) {
  178. generateRepo := &Repository{
  179. OwnerID: owner.ID,
  180. Owner: owner,
  181. Name: opts.Name,
  182. LowerName: strings.ToLower(opts.Name),
  183. Description: opts.Description,
  184. IsPrivate: opts.Private,
  185. IsEmpty: !opts.GitContent || templateRepo.IsEmpty,
  186. IsFsckEnabled: templateRepo.IsFsckEnabled,
  187. TemplateID: templateRepo.ID,
  188. }
  189. if err = createRepository(ctx.e, doer, owner, generateRepo); err != nil {
  190. return nil, err
  191. }
  192. repoPath := RepoPath(owner.Name, generateRepo.Name)
  193. if err = checkInitRepository(repoPath); err != nil {
  194. return generateRepo, err
  195. }
  196. return generateRepo, nil
  197. }
  198. // GenerateGitContent generates git content from a template repository
  199. func GenerateGitContent(ctx DBContext, templateRepo, generateRepo *Repository) error {
  200. if err := generateRepository(ctx.e, generateRepo, templateRepo, generateRepo); err != nil {
  201. return err
  202. }
  203. if err := generateRepo.updateSize(ctx.e); err != nil {
  204. return fmt.Errorf("failed to update size for repository: %v", err)
  205. }
  206. if err := copyLFS(ctx.e, generateRepo, templateRepo); err != nil {
  207. return fmt.Errorf("failed to copy LFS: %v", err)
  208. }
  209. return nil
  210. }
  211. // GenerateTopics generates topics from a template repository
  212. func GenerateTopics(ctx DBContext, templateRepo, generateRepo *Repository) error {
  213. for _, topic := range templateRepo.Topics {
  214. if _, err := addTopicByNameToRepo(ctx.e, generateRepo.ID, topic); err != nil {
  215. return err
  216. }
  217. }
  218. return nil
  219. }
  220. // GenerateGitHooks generates git hooks from a template repository
  221. func GenerateGitHooks(ctx DBContext, templateRepo, generateRepo *Repository) error {
  222. generateGitRepo, err := git.OpenRepository(generateRepo.repoPath(ctx.e))
  223. if err != nil {
  224. return err
  225. }
  226. defer generateGitRepo.Close()
  227. templateGitRepo, err := git.OpenRepository(templateRepo.repoPath(ctx.e))
  228. if err != nil {
  229. return err
  230. }
  231. defer templateGitRepo.Close()
  232. templateHooks, err := templateGitRepo.Hooks()
  233. if err != nil {
  234. return err
  235. }
  236. for _, templateHook := range templateHooks {
  237. generateHook, err := generateGitRepo.GetHook(templateHook.Name())
  238. if err != nil {
  239. return err
  240. }
  241. generateHook.Content = templateHook.Content
  242. if err := generateHook.Update(); err != nil {
  243. return err
  244. }
  245. }
  246. return nil
  247. }
  248. // GenerateWebhooks generates webhooks from a template repository
  249. func GenerateWebhooks(ctx DBContext, templateRepo, generateRepo *Repository) error {
  250. templateWebhooks, err := GetWebhooksByRepoID(templateRepo.ID)
  251. if err != nil {
  252. return err
  253. }
  254. for _, templateWebhook := range templateWebhooks {
  255. generateWebhook := &Webhook{
  256. RepoID: generateRepo.ID,
  257. URL: templateWebhook.URL,
  258. HTTPMethod: templateWebhook.HTTPMethod,
  259. ContentType: templateWebhook.ContentType,
  260. Secret: templateWebhook.Secret,
  261. HookEvent: templateWebhook.HookEvent,
  262. IsActive: templateWebhook.IsActive,
  263. HookTaskType: templateWebhook.HookTaskType,
  264. OrgID: templateWebhook.OrgID,
  265. Events: templateWebhook.Events,
  266. Meta: templateWebhook.Meta,
  267. }
  268. if err := createWebhook(ctx.e, generateWebhook); err != nil {
  269. return err
  270. }
  271. }
  272. return nil
  273. }
  274. // GenerateAvatar generates the avatar from a template repository
  275. func GenerateAvatar(ctx DBContext, templateRepo, generateRepo *Repository) error {
  276. generateRepo.Avatar = strings.Replace(templateRepo.Avatar, strconv.FormatInt(templateRepo.ID, 10), strconv.FormatInt(generateRepo.ID, 10), 1)
  277. if err := com.Copy(templateRepo.CustomAvatarPath(), generateRepo.CustomAvatarPath()); err != nil {
  278. return err
  279. }
  280. return updateRepositoryCols(ctx.e, generateRepo, "avatar")
  281. }
  282. // GenerateIssueLabels generates issue labels from a template repository
  283. func GenerateIssueLabels(ctx DBContext, templateRepo, generateRepo *Repository) error {
  284. templateLabels, err := getLabelsByRepoID(ctx.e, templateRepo.ID, "")
  285. if err != nil {
  286. return err
  287. }
  288. for _, templateLabel := range templateLabels {
  289. generateLabel := &Label{
  290. RepoID: generateRepo.ID,
  291. Name: templateLabel.Name,
  292. Description: templateLabel.Description,
  293. Color: templateLabel.Color,
  294. }
  295. if err := newLabel(ctx.e, generateLabel); err != nil {
  296. return err
  297. }
  298. }
  299. return nil
  300. }
  301. func generateExpansion(src string, templateRepo, generateRepo *Repository) string {
  302. return os.Expand(src, func(key string) string {
  303. switch key {
  304. case "REPO_NAME":
  305. return generateRepo.Name
  306. case "TEMPLATE_NAME":
  307. return templateRepo.Name
  308. case "REPO_DESCRIPTION":
  309. return generateRepo.Description
  310. case "TEMPLATE_DESCRIPTION":
  311. return templateRepo.Description
  312. case "REPO_OWNER":
  313. return generateRepo.MustOwnerName()
  314. case "TEMPLATE_OWNER":
  315. return templateRepo.MustOwnerName()
  316. case "REPO_LINK":
  317. return generateRepo.Link()
  318. case "TEMPLATE_LINK":
  319. return templateRepo.Link()
  320. case "REPO_HTTPS_URL":
  321. return generateRepo.CloneLink().HTTPS
  322. case "TEMPLATE_HTTPS_URL":
  323. return templateRepo.CloneLink().HTTPS
  324. case "REPO_SSH_URL":
  325. return generateRepo.CloneLink().SSH
  326. case "TEMPLATE_SSH_URL":
  327. return templateRepo.CloneLink().SSH
  328. default:
  329. return key
  330. }
  331. })
  332. }