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

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