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 14KB

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