You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

repository.go 8.9 kB

3 years ago
3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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. "fmt"
  7. "io/ioutil"
  8. "net/http"
  9. "os"
  10. "strings"
  11. "code.gitea.io/gitea/models"
  12. "code.gitea.io/gitea/modules/log"
  13. "code.gitea.io/gitea/modules/notification"
  14. repo_module "code.gitea.io/gitea/modules/repository"
  15. "code.gitea.io/gitea/modules/setting"
  16. pull_service "code.gitea.io/gitea/services/pull"
  17. )
  18. const SHELL_FLAG_ON = 1
  19. // CreateRepository creates a repository for the user/organization.
  20. func CreateRepository(doer, owner *models.User, opts models.CreateRepoOptions) (*models.Repository, error) {
  21. repo, err := repo_module.CreateRepository(doer, owner, opts)
  22. if err != nil {
  23. if repo != nil {
  24. if errDelete := models.DeleteRepository(doer, owner.ID, repo.ID); errDelete != nil {
  25. log.Error("Rollback deleteRepository: %v", errDelete)
  26. }
  27. }
  28. return nil, err
  29. }
  30. notification.NotifyCreateRepository(doer, owner, repo)
  31. return repo, nil
  32. }
  33. // ForkRepository forks a repository
  34. func ForkRepository(doer, u *models.User, oldRepo *models.Repository, name, desc, alias string) (*models.Repository, error) {
  35. repo, err := repo_module.ForkRepository(doer, u, oldRepo, name, desc, alias)
  36. if err != nil {
  37. if repo != nil {
  38. if errDelete := models.DeleteRepository(doer, u.ID, repo.ID); errDelete != nil {
  39. log.Error("Rollback deleteRepository: %v", errDelete)
  40. }
  41. }
  42. return nil, err
  43. }
  44. notification.NotifyForkRepository(doer, oldRepo, repo)
  45. return repo, nil
  46. }
  47. // DeleteRepository deletes a repository for a user or organization.
  48. func DeleteRepository(doer *models.User, repo *models.Repository) error {
  49. if err := pull_service.CloseRepoBranchesPulls(doer, repo); err != nil {
  50. log.Error("CloseRepoBranchesPulls failed: %v", err)
  51. }
  52. if err := models.DeleteRepository(doer, repo.OwnerID, repo.ID); err != nil {
  53. return err
  54. }
  55. notification.NotifyDeleteRepository(doer, repo)
  56. return nil
  57. }
  58. // PushCreateRepo creates a repository when a new repository is pushed to an appropriate namespace
  59. func PushCreateRepo(authUser, owner *models.User, repoName string) (*models.Repository, error) {
  60. if !authUser.IsAdmin {
  61. if owner.IsOrganization() {
  62. if ok, err := owner.CanCreateOrgRepo(authUser.ID); err != nil {
  63. return nil, err
  64. } else if !ok {
  65. return nil, fmt.Errorf("cannot push-create repository for org")
  66. }
  67. } else if authUser.ID != owner.ID {
  68. return nil, fmt.Errorf("cannot push-create repository for another user")
  69. }
  70. }
  71. repo, err := CreateRepository(authUser, owner, models.CreateRepoOptions{
  72. Name: repoName,
  73. IsPrivate: true,
  74. })
  75. if err != nil {
  76. return nil, err
  77. }
  78. return repo, nil
  79. }
  80. func GetRecommendCourseKeyWords() ([]string, error) {
  81. url := setting.RecommentRepoAddr + "course_keywords"
  82. result, err := RecommendFromPromote(url)
  83. if err != nil {
  84. return []string{}, err
  85. }
  86. return result, err
  87. }
  88. func GetRecommendRepoFromPromote(filename string) ([]map[string]interface{}, error) {
  89. resultRepo := make([]map[string]interface{}, 0)
  90. url := setting.RecommentRepoAddr + filename
  91. result, err := RecommendFromPromote(url)
  92. if err != nil {
  93. return resultRepo, err
  94. }
  95. //resultRepo := make([]*models.Repository, 0)
  96. for _, repoName := range result {
  97. tmpIndex1 := strings.Index(repoName, "##")
  98. //log.Info("repoName=" + repoName + " tmpIndex1=" + fmt.Sprint(tmpIndex1) + " len(repoName)=" + fmt.Sprint(len(repoName)))
  99. repoLabel := ""
  100. if tmpIndex1 != -1 {
  101. repoLabel = strings.Trim(repoName[tmpIndex1+2:], " ")
  102. repoName = strings.Trim(repoName[0:tmpIndex1], " ")
  103. }
  104. tmpIndex := strings.Index(repoName, "/")
  105. if tmpIndex == -1 {
  106. log.Info("error repo name format.")
  107. } else {
  108. ownerName := strings.Trim(repoName[0:tmpIndex], " ")
  109. repoName := strings.Trim(repoName[tmpIndex+1:], " ")
  110. repo, err := models.GetRepositoryByOwnerAndAlias(ownerName, repoName)
  111. if err == nil {
  112. repoMap := make(map[string]interface{})
  113. repoMap["ID"] = fmt.Sprint(repo.ID)
  114. repoMap["Name"] = repo.Name
  115. repoMap["Alias"] = repo.Alias
  116. repoMap["Label"] = repoLabel
  117. repoMap["OwnerName"] = repo.OwnerName
  118. repoMap["NumStars"] = repo.NumStars
  119. repoMap["NumForks"] = repo.NumForks
  120. repoMap["Description"] = repo.Description
  121. repoMap["NumWatchs"] = repo.NumWatches
  122. repoMap["Topics"] = repo.Topics
  123. repoMap["Avatar"] = repo.RelAvatarLink()
  124. resultRepo = append(resultRepo, repoMap)
  125. } else {
  126. log.Info("query repo error," + err.Error())
  127. }
  128. }
  129. }
  130. return resultRepo, nil
  131. }
  132. func RecommendContentFromPromote(url string) (string, error) {
  133. defer func() {
  134. if err := recover(); err != nil {
  135. log.Info("not error.", err)
  136. return
  137. }
  138. }()
  139. resp, err := http.Get(url)
  140. if err != nil || resp.StatusCode != 200 {
  141. log.Info("Get organizations url error=" + err.Error())
  142. return "", err
  143. }
  144. bytes, err := ioutil.ReadAll(resp.Body)
  145. resp.Body.Close()
  146. if err != nil {
  147. log.Info("Get organizations url error=" + err.Error())
  148. return "", err
  149. }
  150. allLineStr := string(bytes)
  151. return allLineStr, nil
  152. }
  153. func RecommendFromPromote(url string) ([]string, error) {
  154. defer func() {
  155. if err := recover(); err != nil {
  156. log.Info("not error.", err)
  157. return
  158. }
  159. }()
  160. resp, err := http.Get(url)
  161. if err != nil || resp.StatusCode != 200 {
  162. log.Info("Get organizations url error=" + err.Error())
  163. return nil, err
  164. }
  165. bytes, err := ioutil.ReadAll(resp.Body)
  166. resp.Body.Close()
  167. if err != nil {
  168. log.Info("Get organizations url error=" + err.Error())
  169. return nil, err
  170. }
  171. allLineStr := string(bytes)
  172. lines := strings.Split(allLineStr, "\n")
  173. result := make([]string, len(lines))
  174. for i, line := range lines {
  175. log.Info("i=" + fmt.Sprint(i) + " line=" + line)
  176. result[i] = strings.Trim(line, " ")
  177. }
  178. return result, nil
  179. }
  180. func CheckPushSizeLimit4Web(repo *models.Repository, fileIds []string) error {
  181. if err := CheckRepoNumOnceLimit(len(fileIds)); err != nil {
  182. return err
  183. }
  184. totalSize, err := CountUploadFileSizeByIds(fileIds)
  185. if err != nil {
  186. return UploadFileInvalidErr{}
  187. }
  188. if err := CheckRepoTotalSizeLimit(repo, totalSize); err != nil {
  189. return err
  190. }
  191. return nil
  192. }
  193. func CheckPushSizeLimit4Http(repo *models.Repository, uploadFileSize int64) error {
  194. if err := CheckRepoOnceTotalSizeLimit(uploadFileSize); err != nil {
  195. return err
  196. }
  197. if err := CheckRepoTotalSizeLimit(repo, uploadFileSize); err != nil {
  198. return err
  199. }
  200. return nil
  201. }
  202. func CheckRepoTotalSizeLimit(repo *models.Repository, uploadFileSize int64) error {
  203. if repo.Size+uploadFileSize > setting.Repository.RepoMaxSize*1024*1024 {
  204. return RepoTooLargeErr{}
  205. }
  206. return nil
  207. }
  208. func CheckRepoOnceTotalSizeLimit(uploadFileSize int64) error {
  209. if uploadFileSize > setting.Repository.Upload.TotalMaxSize*1024*1024 {
  210. return UploadFileTooLargeErr{}
  211. }
  212. return nil
  213. }
  214. func CheckRepoNumOnceLimit(uploadFileNum int) error {
  215. if uploadFileNum > setting.Repository.Upload.MaxFiles {
  216. return UploadFileTooMuchErr{}
  217. }
  218. return nil
  219. }
  220. func CountUploadFileSizeByIds(fileIds []string) (int64, error) {
  221. if len(fileIds) == 0 {
  222. return 0, nil
  223. }
  224. uploads, err := models.GetUploadsByUUIDs(fileIds)
  225. if err != nil {
  226. return 0, fmt.Errorf("CountUploadFileSizeByIds error [uuids: %v]: %v", fileIds, err)
  227. }
  228. var totalSize int64
  229. for _, upload := range uploads {
  230. size, err := GetUploadFileSize(upload)
  231. if err != nil {
  232. return 0, err
  233. }
  234. totalSize += size
  235. }
  236. return totalSize, nil
  237. }
  238. func GetUploadFileSize(upload *models.Upload) (int64, error) {
  239. info, err := os.Lstat(upload.LocalPath())
  240. if err != nil {
  241. return 0, err
  242. }
  243. return info.Size(), nil
  244. }
  245. type RepoTooLargeErr struct {
  246. }
  247. func (RepoTooLargeErr) Error() string {
  248. return fmt.Sprintf("Repository can not exceed %d MB. Please remove some unnecessary files and try again", setting.Repository.RepoMaxSize)
  249. }
  250. func IsRepoTooLargeErr(err error) bool {
  251. _, ok := err.(RepoTooLargeErr)
  252. return ok
  253. }
  254. type UploadFileTooLargeErr struct {
  255. }
  256. func (UploadFileTooLargeErr) Error() string {
  257. return fmt.Sprintf("Upload files can not exceed %d MB at a time", setting.Repository.Upload.TotalMaxSize)
  258. }
  259. func IsUploadFileTooLargeErr(err error) bool {
  260. _, ok := err.(UploadFileTooLargeErr)
  261. return ok
  262. }
  263. type RepoFileTooLargeErr struct {
  264. }
  265. func (RepoFileTooLargeErr) Error() string {
  266. return "repository file is too large"
  267. }
  268. func IsRepoFileTooLargeErr(err error) bool {
  269. _, ok := err.(RepoFileTooLargeErr)
  270. return ok
  271. }
  272. type UploadFileTooMuchErr struct {
  273. }
  274. func (UploadFileTooMuchErr) Error() string {
  275. return "upload files are too lmuch"
  276. }
  277. func IsUploadFileTooMuchErr(err error) bool {
  278. _, ok := err.(UploadFileTooMuchErr)
  279. return ok
  280. }
  281. type UploadFileInvalidErr struct {
  282. }
  283. func (UploadFileInvalidErr) Error() string {
  284. return "upload files are invalid"
  285. }
  286. func IsUploadFileInvalidErr(err error) bool {
  287. _, ok := err.(UploadFileInvalidErr)
  288. return ok
  289. }