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.

adopt.go 11KB

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