gitea源码

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. // Copyright 2020 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package repository
  4. import (
  5. "context"
  6. "fmt"
  7. "os"
  8. "path"
  9. "path/filepath"
  10. "strings"
  11. "code.gitea.io/gitea/models/db"
  12. git_model "code.gitea.io/gitea/models/git"
  13. repo_model "code.gitea.io/gitea/models/repo"
  14. user_model "code.gitea.io/gitea/models/user"
  15. "code.gitea.io/gitea/modules/container"
  16. "code.gitea.io/gitea/modules/gitrepo"
  17. "code.gitea.io/gitea/modules/glob"
  18. "code.gitea.io/gitea/modules/graceful"
  19. "code.gitea.io/gitea/modules/log"
  20. "code.gitea.io/gitea/modules/optional"
  21. repo_module "code.gitea.io/gitea/modules/repository"
  22. "code.gitea.io/gitea/modules/setting"
  23. "code.gitea.io/gitea/modules/util"
  24. notify_service "code.gitea.io/gitea/services/notify"
  25. )
  26. func deleteFailedAdoptRepository(repoID int64) error {
  27. return db.WithTx(graceful.GetManager().ShutdownContext(), func(ctx context.Context) error {
  28. if err := deleteDBRepository(ctx, repoID); err != nil {
  29. return fmt.Errorf("deleteDBRepository: %w", err)
  30. }
  31. if err := git_model.DeleteRepoBranches(ctx, repoID); err != nil {
  32. return fmt.Errorf("deleteRepoBranches: %w", err)
  33. }
  34. return repo_model.DeleteRepoReleases(ctx, repoID)
  35. })
  36. }
  37. // AdoptRepository adopts pre-existing repository files for the user/organization.
  38. func AdoptRepository(ctx context.Context, doer, owner *user_model.User, opts CreateRepoOptions) (*repo_model.Repository, error) {
  39. if !doer.CanCreateRepoIn(owner) {
  40. return nil, repo_model.ErrReachLimitOfRepo{
  41. Limit: owner.MaxRepoCreation,
  42. }
  43. }
  44. repo := &repo_model.Repository{
  45. OwnerID: owner.ID,
  46. Owner: owner,
  47. OwnerName: owner.Name,
  48. Name: opts.Name,
  49. LowerName: strings.ToLower(opts.Name),
  50. Description: opts.Description,
  51. OriginalURL: opts.OriginalURL,
  52. OriginalServiceType: opts.GitServiceType,
  53. IsPrivate: opts.IsPrivate,
  54. IsFsckEnabled: !opts.IsMirror,
  55. CloseIssuesViaCommitInAnyBranch: setting.Repository.DefaultCloseIssuesViaCommitsInAnyBranch,
  56. Status: repo_model.RepositoryBeingMigrated,
  57. IsEmpty: !opts.AutoInit,
  58. }
  59. // 1 - create the repository database operations first
  60. err := db.WithTx(ctx, func(ctx context.Context) error {
  61. return createRepositoryInDB(ctx, doer, owner, repo, false)
  62. })
  63. if err != nil {
  64. return nil, err
  65. }
  66. // last - clean up if something goes wrong
  67. // WARNING: Don't override all later err with local variables
  68. defer func() {
  69. if err != nil {
  70. // we can not use the ctx because it maybe canceled or timeout
  71. if errDel := deleteFailedAdoptRepository(repo.ID); errDel != nil {
  72. log.Error("Failed to delete repository %s that could not be adopted: %v", repo.FullName(), errDel)
  73. }
  74. }
  75. }()
  76. // Re-fetch the repository from database before updating it (else it would
  77. // override changes that were done earlier with sql)
  78. if repo, err = repo_model.GetRepositoryByID(ctx, repo.ID); err != nil {
  79. return nil, fmt.Errorf("getRepositoryByID: %w", err)
  80. }
  81. // 2 - adopt the repository from disk
  82. if err = adoptRepository(ctx, repo, opts.DefaultBranch); err != nil {
  83. return nil, fmt.Errorf("adoptRepository: %w", err)
  84. }
  85. // 3 - Update the git repository
  86. if err = updateGitRepoAfterCreate(ctx, repo); err != nil {
  87. return nil, fmt.Errorf("updateGitRepoAfterCreate: %w", err)
  88. }
  89. // 4 - update repository status
  90. repo.Status = repo_model.RepositoryReady
  91. if err = repo_model.UpdateRepositoryColsWithAutoTime(ctx, repo, "status"); err != nil {
  92. return nil, fmt.Errorf("UpdateRepositoryCols: %w", err)
  93. }
  94. notify_service.AdoptRepository(ctx, doer, owner, repo)
  95. return repo, nil
  96. }
  97. func adoptRepository(ctx context.Context, repo *repo_model.Repository, defaultBranch string) (err error) {
  98. isExist, err := gitrepo.IsRepositoryExist(ctx, repo)
  99. if err != nil {
  100. log.Error("Unable to check if %s exists. Error: %v", repo.FullName(), err)
  101. return err
  102. }
  103. if !isExist {
  104. return fmt.Errorf("adoptRepository: path does not already exist: %s", repo.FullName())
  105. }
  106. if err := gitrepo.CreateDelegateHooks(ctx, repo); err != nil {
  107. return fmt.Errorf("createDelegateHooks: %w", err)
  108. }
  109. repo.IsEmpty = false
  110. if len(defaultBranch) > 0 {
  111. repo.DefaultBranch = defaultBranch
  112. if err = gitrepo.SetDefaultBranch(ctx, repo, repo.DefaultBranch); err != nil {
  113. return fmt.Errorf("setDefaultBranch: %w", err)
  114. }
  115. } else {
  116. repo.DefaultBranch, err = gitrepo.GetDefaultBranch(ctx, repo)
  117. if err != nil {
  118. repo.DefaultBranch = setting.Repository.DefaultBranch
  119. if err = gitrepo.SetDefaultBranch(ctx, repo, repo.DefaultBranch); err != nil {
  120. return fmt.Errorf("setDefaultBranch: %w", err)
  121. }
  122. }
  123. }
  124. // Don't bother looking this repo in the context it won't be there
  125. gitRepo, err := gitrepo.OpenRepository(ctx, repo)
  126. if err != nil {
  127. return fmt.Errorf("openRepository: %w", err)
  128. }
  129. defer gitRepo.Close()
  130. if _, err = repo_module.SyncRepoBranchesWithRepo(ctx, repo, gitRepo, 0); err != nil {
  131. return fmt.Errorf("SyncRepoBranchesWithRepo: %w", err)
  132. }
  133. if err = repo_module.SyncReleasesWithTags(ctx, repo, gitRepo); err != nil {
  134. return fmt.Errorf("SyncReleasesWithTags: %w", err)
  135. }
  136. branches, _ := git_model.FindBranchNames(ctx, git_model.FindBranchOptions{
  137. RepoID: repo.ID,
  138. ListOptions: db.ListOptionsAll,
  139. IsDeletedBranch: optional.Some(false),
  140. })
  141. found := false
  142. hasDefault := false
  143. hasMaster := false
  144. hasMain := false
  145. for _, branch := range branches {
  146. if branch == repo.DefaultBranch {
  147. found = true
  148. break
  149. } else if branch == setting.Repository.DefaultBranch {
  150. hasDefault = true
  151. } else if branch == "master" {
  152. hasMaster = true
  153. } else if branch == "main" {
  154. hasMain = true
  155. }
  156. }
  157. if !found {
  158. if hasDefault {
  159. repo.DefaultBranch = setting.Repository.DefaultBranch
  160. } else if hasMaster {
  161. repo.DefaultBranch = "master"
  162. } else if hasMain {
  163. repo.DefaultBranch = "main"
  164. } else if len(branches) > 0 {
  165. repo.DefaultBranch = branches[0]
  166. } else {
  167. repo.IsEmpty = true
  168. repo.DefaultBranch = setting.Repository.DefaultBranch
  169. }
  170. if err = gitrepo.SetDefaultBranch(ctx, repo, repo.DefaultBranch); err != nil {
  171. return fmt.Errorf("setDefaultBranch: %w", err)
  172. }
  173. }
  174. if err = repo_model.UpdateRepositoryColsNoAutoTime(ctx, repo, "is_empty", "default_branch"); err != nil {
  175. return fmt.Errorf("UpdateRepositoryCols: %w", err)
  176. }
  177. if err = repo_module.UpdateRepoSize(ctx, repo); err != nil {
  178. log.Error("Failed to update size for repository: %v", err)
  179. }
  180. return nil
  181. }
  182. // DeleteUnadoptedRepository deletes unadopted repository files from the filesystem
  183. func DeleteUnadoptedRepository(ctx context.Context, doer, u *user_model.User, repoName string) error {
  184. if err := repo_model.IsUsableRepoName(repoName); err != nil {
  185. return err
  186. }
  187. repoPath := repo_model.RepoPath(u.Name, repoName)
  188. isExist, err := util.IsExist(repoPath)
  189. if err != nil {
  190. log.Error("Unable to check if %s exists. Error: %v", repoPath, err)
  191. return err
  192. }
  193. if !isExist {
  194. return repo_model.ErrRepoNotExist{
  195. OwnerName: u.Name,
  196. Name: repoName,
  197. }
  198. }
  199. if exist, err := repo_model.IsRepositoryModelExist(ctx, u, repoName); err != nil {
  200. return err
  201. } else if exist {
  202. return repo_model.ErrRepoAlreadyExist{
  203. Uname: u.Name,
  204. Name: repoName,
  205. }
  206. }
  207. return util.RemoveAll(repoPath)
  208. }
  209. type unadoptedRepositories struct {
  210. repositories []string
  211. index int
  212. start int
  213. end int
  214. }
  215. func (unadopted *unadoptedRepositories) add(repository string) {
  216. if unadopted.index >= unadopted.start && unadopted.index < unadopted.end {
  217. unadopted.repositories = append(unadopted.repositories, repository)
  218. }
  219. unadopted.index++
  220. }
  221. func checkUnadoptedRepositories(ctx context.Context, userName string, repoNamesToCheck []string, unadopted *unadoptedRepositories) error {
  222. if len(repoNamesToCheck) == 0 {
  223. return nil
  224. }
  225. ctxUser, err := user_model.GetUserByName(ctx, userName)
  226. if err != nil {
  227. if user_model.IsErrUserNotExist(err) {
  228. log.Debug("Missing user: %s", userName)
  229. return nil
  230. }
  231. return err
  232. }
  233. repos, _, err := repo_model.GetUserRepositories(ctx, repo_model.SearchRepoOptions{
  234. Actor: ctxUser,
  235. Private: true,
  236. ListOptions: db.ListOptions{
  237. Page: 1,
  238. PageSize: len(repoNamesToCheck),
  239. }, LowerNames: repoNamesToCheck,
  240. })
  241. if err != nil {
  242. return err
  243. }
  244. if len(repos) == len(repoNamesToCheck) {
  245. return nil
  246. }
  247. repoNames := make(container.Set[string], len(repos))
  248. for _, repo := range repos {
  249. repoNames.Add(repo.LowerName)
  250. }
  251. for _, repoName := range repoNamesToCheck {
  252. if !repoNames.Contains(repoName) {
  253. unadopted.add(path.Join(userName, repoName)) // These are not used as filepaths - but as reponames - therefore use path.Join not filepath.Join
  254. }
  255. }
  256. return nil
  257. }
  258. // ListUnadoptedRepositories lists all the unadopted repositories that match the provided query
  259. func ListUnadoptedRepositories(ctx context.Context, query string, opts *db.ListOptions) ([]string, int, error) {
  260. globUser, _ := glob.Compile("*")
  261. globRepo, _ := glob.Compile("*")
  262. qsplit := strings.SplitN(query, "/", 2)
  263. if len(qsplit) > 0 && len(query) > 0 {
  264. var err error
  265. globUser, err = glob.Compile(qsplit[0])
  266. if err != nil {
  267. log.Info("Invalid glob expression '%s' (skipped): %v", qsplit[0], err)
  268. }
  269. if len(qsplit) > 1 {
  270. globRepo, err = glob.Compile(qsplit[1])
  271. if err != nil {
  272. log.Info("Invalid glob expression '%s' (skipped): %v", qsplit[1], err)
  273. }
  274. }
  275. }
  276. var repoNamesToCheck []string
  277. start := (opts.Page - 1) * opts.PageSize
  278. unadopted := &unadoptedRepositories{
  279. repositories: make([]string, 0, opts.PageSize),
  280. start: start,
  281. end: start + opts.PageSize,
  282. index: 0,
  283. }
  284. var userName string
  285. // We're going to iterate by pagesize.
  286. root := filepath.Clean(setting.RepoRootPath)
  287. if err := filepath.WalkDir(root, func(path string, d os.DirEntry, err error) error {
  288. if err != nil {
  289. return err
  290. }
  291. if !d.IsDir() || path == root {
  292. return nil
  293. }
  294. name := d.Name()
  295. if !strings.ContainsRune(path[len(root)+1:], filepath.Separator) {
  296. // Got a new user
  297. if err = checkUnadoptedRepositories(ctx, userName, repoNamesToCheck, unadopted); err != nil {
  298. return err
  299. }
  300. repoNamesToCheck = repoNamesToCheck[:0]
  301. if !globUser.Match(name) {
  302. return filepath.SkipDir
  303. }
  304. userName = name
  305. return nil
  306. }
  307. if !strings.HasSuffix(name, ".git") {
  308. return filepath.SkipDir
  309. }
  310. name = name[:len(name)-4]
  311. if repo_model.IsUsableRepoName(name) != nil || strings.ToLower(name) != name || !globRepo.Match(name) {
  312. return filepath.SkipDir
  313. }
  314. repoNamesToCheck = append(repoNamesToCheck, name)
  315. if len(repoNamesToCheck) >= setting.Database.IterateBufferSize {
  316. if err = checkUnadoptedRepositories(ctx, userName, repoNamesToCheck, unadopted); err != nil {
  317. return err
  318. }
  319. repoNamesToCheck = repoNamesToCheck[:0]
  320. }
  321. return filepath.SkipDir
  322. }); err != nil {
  323. return nil, 0, err
  324. }
  325. if err := checkUnadoptedRepositories(ctx, userName, repoNamesToCheck, unadopted); err != nil {
  326. return nil, 0, err
  327. }
  328. return unadopted.repositories, unadopted.index, nil
  329. }