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.

387 lines
11 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 gt != nil {
  108. if err := os.Remove(gt.Path); err != nil {
  109. return fmt.Errorf("remove .giteatemplate: %v", err)
  110. }
  111. // Avoid walking tree if there are no globs
  112. if len(gt.Globs()) > 0 {
  113. tmpDirSlash := strings.TrimSuffix(filepath.ToSlash(tmpDir), "/") + "/"
  114. if err := filepath.Walk(tmpDirSlash, func(path string, info os.FileInfo, walkErr error) error {
  115. if walkErr != nil {
  116. return walkErr
  117. }
  118. if info.IsDir() {
  119. return nil
  120. }
  121. base := strings.TrimPrefix(filepath.ToSlash(path), tmpDirSlash)
  122. for _, g := range gt.Globs() {
  123. if g.Match(base) {
  124. content, err := ioutil.ReadFile(path)
  125. if err != nil {
  126. return err
  127. }
  128. if err := ioutil.WriteFile(path,
  129. []byte(generateExpansion(string(content), templateRepo, generateRepo)),
  130. 0644); err != nil {
  131. return err
  132. }
  133. break
  134. }
  135. }
  136. return nil
  137. }); err != nil {
  138. return err
  139. }
  140. }
  141. }
  142. if err := git.InitRepository(tmpDir, false); err != nil {
  143. return err
  144. }
  145. repoPath := repo.repoPath(e)
  146. if stdout, err := git.NewCommand("remote", "add", "origin", repoPath).
  147. SetDescription(fmt.Sprintf("generateRepoCommit (git remote add): %s to %s", templateRepoPath, tmpDir)).
  148. RunInDirWithEnv(tmpDir, env); err != nil {
  149. log.Error("Unable to add %v as remote origin to temporary repo to %s: stdout %s\nError: %v", repo, tmpDir, stdout, err)
  150. return fmt.Errorf("git remote add: %v", err)
  151. }
  152. return initRepoCommit(tmpDir, repo, repo.Owner)
  153. }
  154. // generateRepository initializes repository from template
  155. func generateRepository(e Engine, repo, templateRepo, generateRepo *Repository) (err error) {
  156. tmpDir, err := ioutil.TempDir(os.TempDir(), "gitea-"+repo.Name)
  157. if err != nil {
  158. return fmt.Errorf("Failed to create temp dir for repository %s: %v", repo.repoPath(e), err)
  159. }
  160. defer func() {
  161. if err := os.RemoveAll(tmpDir); err != nil {
  162. log.Error("RemoveAll: %v", err)
  163. }
  164. }()
  165. if err = generateRepoCommit(e, repo, templateRepo, generateRepo, tmpDir); err != nil {
  166. return fmt.Errorf("generateRepoCommit: %v", err)
  167. }
  168. // re-fetch repo
  169. if repo, err = getRepositoryByID(e, repo.ID); err != nil {
  170. return fmt.Errorf("getRepositoryByID: %v", err)
  171. }
  172. repo.DefaultBranch = "master"
  173. if err = updateRepository(e, repo, false); err != nil {
  174. return fmt.Errorf("updateRepository: %v", err)
  175. }
  176. return nil
  177. }
  178. // GenerateRepository generates a repository from a template
  179. func GenerateRepository(ctx DBContext, doer, owner *User, templateRepo *Repository, opts GenerateRepoOptions) (_ *Repository, err error) {
  180. generateRepo := &Repository{
  181. OwnerID: owner.ID,
  182. Owner: owner,
  183. Name: opts.Name,
  184. LowerName: strings.ToLower(opts.Name),
  185. Description: opts.Description,
  186. IsPrivate: opts.Private,
  187. IsEmpty: !opts.GitContent || templateRepo.IsEmpty,
  188. IsFsckEnabled: templateRepo.IsFsckEnabled,
  189. TemplateID: templateRepo.ID,
  190. }
  191. if err = createRepository(ctx.e, doer, owner, generateRepo); err != nil {
  192. return nil, err
  193. }
  194. repoPath := RepoPath(owner.Name, generateRepo.Name)
  195. if err = checkInitRepository(repoPath); err != nil {
  196. return generateRepo, err
  197. }
  198. return generateRepo, nil
  199. }
  200. // GenerateGitContent generates git content from a template repository
  201. func GenerateGitContent(ctx DBContext, templateRepo, generateRepo *Repository) error {
  202. if err := generateRepository(ctx.e, generateRepo, templateRepo, generateRepo); err != nil {
  203. return err
  204. }
  205. if err := generateRepo.updateSize(ctx.e); err != nil {
  206. return fmt.Errorf("failed to update size for repository: %v", err)
  207. }
  208. if err := copyLFS(ctx.e, generateRepo, templateRepo); err != nil {
  209. return fmt.Errorf("failed to copy LFS: %v", err)
  210. }
  211. return nil
  212. }
  213. // GenerateTopics generates topics from a template repository
  214. func GenerateTopics(ctx DBContext, templateRepo, generateRepo *Repository) error {
  215. for _, topic := range templateRepo.Topics {
  216. if _, err := addTopicByNameToRepo(ctx.e, generateRepo.ID, topic); err != nil {
  217. return err
  218. }
  219. }
  220. return nil
  221. }
  222. // GenerateGitHooks generates git hooks from a template repository
  223. func GenerateGitHooks(ctx DBContext, templateRepo, generateRepo *Repository) error {
  224. generateGitRepo, err := git.OpenRepository(generateRepo.repoPath(ctx.e))
  225. if err != nil {
  226. return err
  227. }
  228. defer generateGitRepo.Close()
  229. templateGitRepo, err := git.OpenRepository(templateRepo.repoPath(ctx.e))
  230. if err != nil {
  231. return err
  232. }
  233. defer templateGitRepo.Close()
  234. templateHooks, err := templateGitRepo.Hooks()
  235. if err != nil {
  236. return err
  237. }
  238. for _, templateHook := range templateHooks {
  239. generateHook, err := generateGitRepo.GetHook(templateHook.Name())
  240. if err != nil {
  241. return err
  242. }
  243. generateHook.Content = templateHook.Content
  244. if err := generateHook.Update(); err != nil {
  245. return err
  246. }
  247. }
  248. return nil
  249. }
  250. // GenerateWebhooks generates webhooks from a template repository
  251. func GenerateWebhooks(ctx DBContext, templateRepo, generateRepo *Repository) error {
  252. templateWebhooks, err := GetWebhooksByRepoID(templateRepo.ID)
  253. if err != nil {
  254. return err
  255. }
  256. for _, templateWebhook := range templateWebhooks {
  257. generateWebhook := &Webhook{
  258. RepoID: generateRepo.ID,
  259. URL: templateWebhook.URL,
  260. HTTPMethod: templateWebhook.HTTPMethod,
  261. ContentType: templateWebhook.ContentType,
  262. Secret: templateWebhook.Secret,
  263. HookEvent: templateWebhook.HookEvent,
  264. IsActive: templateWebhook.IsActive,
  265. HookTaskType: templateWebhook.HookTaskType,
  266. OrgID: templateWebhook.OrgID,
  267. Events: templateWebhook.Events,
  268. Meta: templateWebhook.Meta,
  269. }
  270. if err := createWebhook(ctx.e, generateWebhook); err != nil {
  271. return err
  272. }
  273. }
  274. return nil
  275. }
  276. // GenerateAvatar generates the avatar from a template repository
  277. func GenerateAvatar(ctx DBContext, templateRepo, generateRepo *Repository) error {
  278. generateRepo.Avatar = strings.Replace(templateRepo.Avatar, strconv.FormatInt(templateRepo.ID, 10), strconv.FormatInt(generateRepo.ID, 10), 1)
  279. if err := com.Copy(templateRepo.CustomAvatarPath(), generateRepo.CustomAvatarPath()); err != nil {
  280. return err
  281. }
  282. return updateRepositoryCols(ctx.e, generateRepo, "avatar")
  283. }
  284. // GenerateIssueLabels generates issue labels from a template repository
  285. func GenerateIssueLabels(ctx DBContext, templateRepo, generateRepo *Repository) error {
  286. templateLabels, err := getLabelsByRepoID(ctx.e, templateRepo.ID, "")
  287. if err != nil {
  288. return err
  289. }
  290. for _, templateLabel := range templateLabels {
  291. generateLabel := &Label{
  292. RepoID: generateRepo.ID,
  293. Name: templateLabel.Name,
  294. Description: templateLabel.Description,
  295. Color: templateLabel.Color,
  296. }
  297. if err := newLabel(ctx.e, generateLabel); err != nil {
  298. return err
  299. }
  300. }
  301. return nil
  302. }
  303. func generateExpansion(src string, templateRepo, generateRepo *Repository) string {
  304. return os.Expand(src, func(key string) string {
  305. switch key {
  306. case "REPO_NAME":
  307. return generateRepo.Name
  308. case "TEMPLATE_NAME":
  309. return templateRepo.Name
  310. case "REPO_DESCRIPTION":
  311. return generateRepo.Description
  312. case "TEMPLATE_DESCRIPTION":
  313. return templateRepo.Description
  314. case "REPO_OWNER":
  315. return generateRepo.MustOwnerName()
  316. case "TEMPLATE_OWNER":
  317. return templateRepo.MustOwnerName()
  318. case "REPO_LINK":
  319. return generateRepo.Link()
  320. case "TEMPLATE_LINK":
  321. return templateRepo.Link()
  322. case "REPO_HTTPS_URL":
  323. return generateRepo.CloneLink().HTTPS
  324. case "TEMPLATE_HTTPS_URL":
  325. return templateRepo.CloneLink().HTTPS
  326. case "REPO_SSH_URL":
  327. return generateRepo.CloneLink().SSH
  328. case "TEMPLATE_SSH_URL":
  329. return templateRepo.CloneLink().SSH
  330. default:
  331. return key
  332. }
  333. })
  334. }