repo.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. // Copyright 2014 The Gogs 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 repo
  5. import (
  6. "net/http"
  7. "path"
  8. api "github.com/gogs/go-gogs-client"
  9. "github.com/pkg/errors"
  10. log "unknwon.dev/clog/v2"
  11. "gogs.io/gogs/internal/conf"
  12. "gogs.io/gogs/internal/context"
  13. "gogs.io/gogs/internal/db"
  14. "gogs.io/gogs/internal/form"
  15. "gogs.io/gogs/internal/route/api/v1/convert"
  16. )
  17. func Search(c *context.APIContext) {
  18. opts := &db.SearchRepoOptions{
  19. Keyword: path.Base(c.Query("q")),
  20. OwnerID: c.QueryInt64("uid"),
  21. PageSize: convert.ToCorrectPageSize(c.QueryInt("limit")),
  22. Page: c.QueryInt("page"),
  23. }
  24. // Check visibility.
  25. if c.IsLogged && opts.OwnerID > 0 {
  26. if c.User.ID == opts.OwnerID {
  27. opts.Private = true
  28. } else {
  29. u, err := db.GetUserByID(opts.OwnerID)
  30. if err != nil {
  31. c.JSON(http.StatusInternalServerError, map[string]interface{}{
  32. "ok": false,
  33. "error": err.Error(),
  34. })
  35. return
  36. }
  37. if u.IsOrganization() && u.IsOwnedBy(c.User.ID) {
  38. opts.Private = true
  39. }
  40. // FIXME: how about collaborators?
  41. }
  42. }
  43. repos, count, err := db.SearchRepositoryByName(opts)
  44. if err != nil {
  45. c.JSON(http.StatusInternalServerError, map[string]interface{}{
  46. "ok": false,
  47. "error": err.Error(),
  48. })
  49. return
  50. }
  51. if err = db.RepositoryList(repos).LoadAttributes(); err != nil {
  52. c.JSON(http.StatusInternalServerError, map[string]interface{}{
  53. "ok": false,
  54. "error": err.Error(),
  55. })
  56. return
  57. }
  58. results := make([]*api.Repository, len(repos))
  59. for i := range repos {
  60. results[i] = repos[i].APIFormat(nil)
  61. }
  62. c.SetLinkHeader(int(count), opts.PageSize)
  63. c.JSONSuccess(map[string]interface{}{
  64. "ok": true,
  65. "data": results,
  66. })
  67. }
  68. func listUserRepositories(c *context.APIContext, username string) {
  69. user, err := db.GetUserByName(username)
  70. if err != nil {
  71. c.NotFoundOrError(err, "get user by name")
  72. return
  73. }
  74. // Only list public repositories if user requests someone else's repository list,
  75. // or an organization isn't a member of.
  76. var ownRepos []*db.Repository
  77. if user.IsOrganization() {
  78. ownRepos, _, err = user.GetUserRepositories(c.User.ID, 1, user.NumRepos)
  79. } else {
  80. ownRepos, err = db.GetUserRepositories(&db.UserRepoOptions{
  81. UserID: user.ID,
  82. Private: c.User.ID == user.ID,
  83. Page: 1,
  84. PageSize: user.NumRepos,
  85. })
  86. }
  87. if err != nil {
  88. c.Error(err, "get user repositories")
  89. return
  90. }
  91. if err = db.RepositoryList(ownRepos).LoadAttributes(); err != nil {
  92. c.Error(err, "load attributes")
  93. return
  94. }
  95. // Early return for querying other user's repositories
  96. if c.User.ID != user.ID {
  97. repos := make([]*api.Repository, len(ownRepos))
  98. for i := range ownRepos {
  99. repos[i] = ownRepos[i].APIFormat(&api.Permission{Admin: true, Push: true, Pull: true})
  100. }
  101. c.JSONSuccess(&repos)
  102. return
  103. }
  104. accessibleRepos, err := user.GetRepositoryAccesses()
  105. if err != nil {
  106. c.Error(err, "get repositories accesses")
  107. return
  108. }
  109. numOwnRepos := len(ownRepos)
  110. repos := make([]*api.Repository, numOwnRepos+len(accessibleRepos))
  111. for i := range ownRepos {
  112. repos[i] = ownRepos[i].APIFormat(&api.Permission{Admin: true, Push: true, Pull: true})
  113. }
  114. i := numOwnRepos
  115. for repo, access := range accessibleRepos {
  116. repos[i] = repo.APIFormat(&api.Permission{
  117. Admin: access >= db.AccessModeAdmin,
  118. Push: access >= db.AccessModeWrite,
  119. Pull: true,
  120. })
  121. i++
  122. }
  123. c.JSONSuccess(&repos)
  124. }
  125. func ListMyRepos(c *context.APIContext) {
  126. listUserRepositories(c, c.User.Name)
  127. }
  128. func ListUserRepositories(c *context.APIContext) {
  129. listUserRepositories(c, c.Params(":username"))
  130. }
  131. func ListOrgRepositories(c *context.APIContext) {
  132. listUserRepositories(c, c.Params(":org"))
  133. }
  134. func CreateUserRepo(c *context.APIContext, owner *db.User, opt api.CreateRepoOption) {
  135. repo, err := db.CreateRepository(c.User, owner, db.CreateRepoOptions{
  136. Name: opt.Name,
  137. Description: opt.Description,
  138. Gitignores: opt.Gitignores,
  139. License: opt.License,
  140. Readme: opt.Readme,
  141. IsPrivate: opt.Private,
  142. AutoInit: opt.AutoInit,
  143. })
  144. if err != nil {
  145. if db.IsErrRepoAlreadyExist(err) ||
  146. db.IsErrNameReserved(err) ||
  147. db.IsErrNamePatternNotAllowed(err) {
  148. c.ErrorStatus(http.StatusUnprocessableEntity, err)
  149. } else {
  150. if repo != nil {
  151. if err = db.DeleteRepository(c.User.ID, repo.ID); err != nil {
  152. log.Error("Failed to delete repository: %v", err)
  153. }
  154. }
  155. c.Error(err, "create repository")
  156. }
  157. return
  158. }
  159. c.JSON(201, repo.APIFormat(&api.Permission{Admin: true, Push: true, Pull: true}))
  160. }
  161. func Create(c *context.APIContext, opt api.CreateRepoOption) {
  162. // Shouldn't reach this condition, but just in case.
  163. if c.User.IsOrganization() {
  164. c.ErrorStatus(http.StatusUnprocessableEntity, errors.New("Not allowed to create repository for organization."))
  165. return
  166. }
  167. CreateUserRepo(c, c.User, opt)
  168. }
  169. func CreateOrgRepo(c *context.APIContext, opt api.CreateRepoOption) {
  170. org, err := db.GetOrgByName(c.Params(":org"))
  171. if err != nil {
  172. c.NotFoundOrError(err, "get organization by name")
  173. return
  174. }
  175. if !org.IsOwnedBy(c.User.ID) {
  176. c.ErrorStatus(http.StatusForbidden, errors.New("Given user is not owner of organization."))
  177. return
  178. }
  179. CreateUserRepo(c, org, opt)
  180. }
  181. func Migrate(c *context.APIContext, f form.MigrateRepo) {
  182. ctxUser := c.User
  183. // Not equal means context user is an organization,
  184. // or is another user/organization if current user is admin.
  185. if f.Uid != ctxUser.ID {
  186. org, err := db.GetUserByID(f.Uid)
  187. if err != nil {
  188. if db.IsErrUserNotExist(err) {
  189. c.ErrorStatus(http.StatusUnprocessableEntity, err)
  190. } else {
  191. c.Error(err, "get user by ID")
  192. }
  193. return
  194. } else if !org.IsOrganization() && !c.User.IsAdmin {
  195. c.ErrorStatus(http.StatusForbidden, errors.New("Given user is not an organization."))
  196. return
  197. }
  198. ctxUser = org
  199. }
  200. if c.HasError() {
  201. c.ErrorStatus(http.StatusUnprocessableEntity, errors.New(c.GetErrMsg()))
  202. return
  203. }
  204. if ctxUser.IsOrganization() && !c.User.IsAdmin {
  205. // Check ownership of organization.
  206. if !ctxUser.IsOwnedBy(c.User.ID) {
  207. c.ErrorStatus(http.StatusForbidden, errors.New("Given user is not owner of organization."))
  208. return
  209. }
  210. }
  211. remoteAddr, err := f.ParseRemoteAddr(c.User)
  212. if err != nil {
  213. if db.IsErrInvalidCloneAddr(err) {
  214. addrErr := err.(db.ErrInvalidCloneAddr)
  215. switch {
  216. case addrErr.IsURLError:
  217. c.ErrorStatus(http.StatusUnprocessableEntity, err)
  218. case addrErr.IsPermissionDenied:
  219. c.ErrorStatus(http.StatusUnprocessableEntity, errors.New("You are not allowed to import local repositories."))
  220. case addrErr.IsInvalidPath:
  221. c.ErrorStatus(http.StatusUnprocessableEntity, errors.New("Invalid local path, it does not exist or not a directory."))
  222. default:
  223. c.Error(err, "unexpected error")
  224. }
  225. } else {
  226. c.Error(err, "parse remote address")
  227. }
  228. return
  229. }
  230. repo, err := db.MigrateRepository(c.User, ctxUser, db.MigrateRepoOptions{
  231. Name: f.RepoName,
  232. Description: f.Description,
  233. IsPrivate: f.Private || conf.Repository.ForcePrivate,
  234. IsMirror: f.Mirror,
  235. RemoteAddr: remoteAddr,
  236. })
  237. if err != nil {
  238. if repo != nil {
  239. if errDelete := db.DeleteRepository(ctxUser.ID, repo.ID); errDelete != nil {
  240. log.Error("DeleteRepository: %v", errDelete)
  241. }
  242. }
  243. if db.IsErrReachLimitOfRepo(err) {
  244. c.ErrorStatus(http.StatusUnprocessableEntity, err)
  245. } else {
  246. c.Error(errors.New(db.HandleMirrorCredentials(err.Error(), true)), "migrate repository")
  247. }
  248. return
  249. }
  250. log.Trace("Repository migrated: %s/%s", ctxUser.Name, f.RepoName)
  251. c.JSON(201, repo.APIFormat(&api.Permission{Admin: true, Push: true, Pull: true}))
  252. }
  253. // FIXME: inject in the handler chain
  254. func parseOwnerAndRepo(c *context.APIContext) (*db.User, *db.Repository) {
  255. owner, err := db.GetUserByName(c.Params(":username"))
  256. if err != nil {
  257. if db.IsErrUserNotExist(err) {
  258. c.ErrorStatus(http.StatusUnprocessableEntity, err)
  259. } else {
  260. c.Error(err, "get user by name")
  261. }
  262. return nil, nil
  263. }
  264. repo, err := db.GetRepositoryByName(owner.ID, c.Params(":reponame"))
  265. if err != nil {
  266. c.NotFoundOrError(err, "get repository by name")
  267. return nil, nil
  268. }
  269. return owner, repo
  270. }
  271. func Get(c *context.APIContext) {
  272. _, repo := parseOwnerAndRepo(c)
  273. if c.Written() {
  274. return
  275. }
  276. c.JSONSuccess(repo.APIFormat(&api.Permission{
  277. Admin: c.Repo.IsAdmin(),
  278. Push: c.Repo.IsWriter(),
  279. Pull: true,
  280. }))
  281. }
  282. func Delete(c *context.APIContext) {
  283. owner, repo := parseOwnerAndRepo(c)
  284. if c.Written() {
  285. return
  286. }
  287. if owner.IsOrganization() && !owner.IsOwnedBy(c.User.ID) {
  288. c.ErrorStatus(http.StatusForbidden, errors.New("Given user is not owner of organization."))
  289. return
  290. }
  291. if err := db.DeleteRepository(owner.ID, repo.ID); err != nil {
  292. c.Error(err, "delete repository")
  293. return
  294. }
  295. log.Trace("Repository deleted: %s/%s", owner.Name, repo.Name)
  296. c.NoContent()
  297. }
  298. func ListForks(c *context.APIContext) {
  299. forks, err := c.Repo.Repository.GetForks()
  300. if err != nil {
  301. c.Error(err, "get forks")
  302. return
  303. }
  304. apiForks := make([]*api.Repository, len(forks))
  305. for i := range forks {
  306. if err := forks[i].GetOwner(); err != nil {
  307. c.Error(err, "get owner")
  308. return
  309. }
  310. apiForks[i] = forks[i].APIFormat(&api.Permission{
  311. Admin: c.User.IsAdminOfRepo(forks[i]),
  312. Push: c.User.IsWriterOfRepo(forks[i]),
  313. Pull: true,
  314. })
  315. }
  316. c.JSONSuccess(&apiForks)
  317. }
  318. func IssueTracker(c *context.APIContext, form api.EditIssueTrackerOption) {
  319. _, repo := parseOwnerAndRepo(c)
  320. if c.Written() {
  321. return
  322. }
  323. if form.EnableIssues != nil {
  324. repo.EnableIssues = *form.EnableIssues
  325. }
  326. if form.EnableExternalTracker != nil {
  327. repo.EnableExternalTracker = *form.EnableExternalTracker
  328. }
  329. if form.ExternalTrackerURL != nil {
  330. repo.ExternalTrackerURL = *form.ExternalTrackerURL
  331. }
  332. if form.TrackerURLFormat != nil {
  333. repo.ExternalTrackerFormat = *form.TrackerURLFormat
  334. }
  335. if form.TrackerIssueStyle != nil {
  336. repo.ExternalTrackerStyle = *form.TrackerIssueStyle
  337. }
  338. if err := db.UpdateRepository(repo, false); err != nil {
  339. c.Error(err, "update repository")
  340. return
  341. }
  342. c.NoContent()
  343. }
  344. func MirrorSync(c *context.APIContext) {
  345. _, repo := parseOwnerAndRepo(c)
  346. if c.Written() {
  347. return
  348. } else if !repo.IsMirror {
  349. c.NotFound()
  350. return
  351. }
  352. go db.MirrorQueue.Add(repo.ID)
  353. c.Status(http.StatusAccepted)
  354. }
  355. func Releases(c *context.APIContext) {
  356. _, repo := parseOwnerAndRepo(c)
  357. releases, err := db.GetReleasesByRepoID(repo.ID)
  358. if err != nil {
  359. c.Error(err, "get releases by repository ID")
  360. return
  361. }
  362. apiReleases := make([]*api.Release, 0, len(releases))
  363. for _, r := range releases {
  364. publisher, err := db.GetUserByID(r.PublisherID)
  365. if err != nil {
  366. c.Error(err, "get release publisher")
  367. return
  368. }
  369. r.Publisher = publisher
  370. }
  371. for _, r := range releases {
  372. apiReleases = append(apiReleases, r.APIFormat())
  373. }
  374. c.JSONSuccess(&apiReleases)
  375. }