repo.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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. "path"
  7. log "gopkg.in/clog.v1"
  8. api "github.com/gogs/go-gogs-client"
  9. "github.com/gogs/gogs/models"
  10. "github.com/gogs/gogs/models/errors"
  11. "github.com/gogs/gogs/pkg/context"
  12. "github.com/gogs/gogs/pkg/form"
  13. "github.com/gogs/gogs/pkg/setting"
  14. "github.com/gogs/gogs/routes/api/v1/convert"
  15. )
  16. // https://github.com/gogs/go-gogs-client/wiki/Repositories#search-repositories
  17. func Search(c *context.APIContext) {
  18. opts := &models.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 := models.GetUserByID(opts.OwnerID)
  30. if err != nil {
  31. c.JSON(500, 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 := models.SearchRepositoryByName(opts)
  44. if err != nil {
  45. c.JSON(500, map[string]interface{}{
  46. "ok": false,
  47. "error": err.Error(),
  48. })
  49. return
  50. }
  51. if err = models.RepositoryList(repos).LoadAttributes(); err != nil {
  52. c.JSON(500, 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.JSON(200, map[string]interface{}{
  64. "ok": true,
  65. "data": results,
  66. })
  67. }
  68. func listUserRepositories(c *context.APIContext, username string) {
  69. user, err := models.GetUserByName(username)
  70. if err != nil {
  71. c.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err)
  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 []*models.Repository
  77. if user.IsOrganization() {
  78. ownRepos, _, err = user.GetUserRepositories(c.User.ID, 1, user.NumRepos)
  79. } else {
  80. ownRepos, err = models.GetUserRepositories(&models.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(500, "GetUserRepositories", err)
  89. return
  90. }
  91. if err = models.RepositoryList(ownRepos).LoadAttributes(); err != nil {
  92. c.Error(500, "LoadAttributes(ownRepos)", err)
  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{true, true, true})
  100. }
  101. c.JSON(200, &repos)
  102. return
  103. }
  104. accessibleRepos, err := user.GetRepositoryAccesses()
  105. if err != nil {
  106. c.Error(500, "GetRepositoryAccesses", err)
  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{true, true, true})
  113. }
  114. i := numOwnRepos
  115. for repo, access := range accessibleRepos {
  116. repos[i] = repo.APIFormat(&api.Permission{
  117. Admin: access >= models.ACCESS_MODE_ADMIN,
  118. Push: access >= models.ACCESS_MODE_WRITE,
  119. Pull: true,
  120. })
  121. i++
  122. }
  123. c.JSON(200, &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 *models.User, opt api.CreateRepoOption) {
  135. repo, err := models.CreateRepository(c.User, owner, models.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 models.IsErrRepoAlreadyExist(err) ||
  146. models.IsErrNameReserved(err) ||
  147. models.IsErrNamePatternNotAllowed(err) {
  148. c.Error(422, "", err)
  149. } else {
  150. if repo != nil {
  151. if err = models.DeleteRepository(c.User.ID, repo.ID); err != nil {
  152. log.Error(2, "DeleteRepository: %v", err)
  153. }
  154. }
  155. c.Error(500, "CreateRepository", err)
  156. }
  157. return
  158. }
  159. c.JSON(201, repo.APIFormat(&api.Permission{true, true, true}))
  160. }
  161. // https://github.com/gogs/go-gogs-client/wiki/Repositories#create
  162. func Create(c *context.APIContext, opt api.CreateRepoOption) {
  163. // Shouldn't reach this condition, but just in case.
  164. if c.User.IsOrganization() {
  165. c.Error(422, "", "not allowed creating repository for organization")
  166. return
  167. }
  168. CreateUserRepo(c, c.User, opt)
  169. }
  170. func CreateOrgRepo(c *context.APIContext, opt api.CreateRepoOption) {
  171. org, err := models.GetOrgByName(c.Params(":org"))
  172. if err != nil {
  173. if errors.IsUserNotExist(err) {
  174. c.Error(422, "", err)
  175. } else {
  176. c.Error(500, "GetOrgByName", err)
  177. }
  178. return
  179. }
  180. if !org.IsOwnedBy(c.User.ID) {
  181. c.Error(403, "", "Given user is not owner of organization.")
  182. return
  183. }
  184. CreateUserRepo(c, org, opt)
  185. }
  186. // https://github.com/gogs/go-gogs-client/wiki/Repositories#migrate
  187. func Migrate(c *context.APIContext, f form.MigrateRepo) {
  188. ctxUser := c.User
  189. // Not equal means context user is an organization,
  190. // or is another user/organization if current user is admin.
  191. if f.Uid != ctxUser.ID {
  192. org, err := models.GetUserByID(f.Uid)
  193. if err != nil {
  194. if errors.IsUserNotExist(err) {
  195. c.Error(422, "", err)
  196. } else {
  197. c.Error(500, "GetUserByID", err)
  198. }
  199. return
  200. } else if !org.IsOrganization() && !c.User.IsAdmin {
  201. c.Error(403, "", "Given user is not an organization")
  202. return
  203. }
  204. ctxUser = org
  205. }
  206. if c.HasError() {
  207. c.Error(422, "", c.GetErrMsg())
  208. return
  209. }
  210. if ctxUser.IsOrganization() && !c.User.IsAdmin {
  211. // Check ownership of organization.
  212. if !ctxUser.IsOwnedBy(c.User.ID) {
  213. c.Error(403, "", "Given user is not owner of organization")
  214. return
  215. }
  216. }
  217. remoteAddr, err := f.ParseRemoteAddr(c.User)
  218. if err != nil {
  219. if models.IsErrInvalidCloneAddr(err) {
  220. addrErr := err.(models.ErrInvalidCloneAddr)
  221. switch {
  222. case addrErr.IsURLError:
  223. c.Error(422, "", err)
  224. case addrErr.IsPermissionDenied:
  225. c.Error(422, "", "You are not allowed to import local repositories")
  226. case addrErr.IsInvalidPath:
  227. c.Error(422, "", "Invalid local path, it does not exist or not a directory")
  228. default:
  229. c.Error(500, "ParseRemoteAddr", "Unknown error type (ErrInvalidCloneAddr): "+err.Error())
  230. }
  231. } else {
  232. c.Error(500, "ParseRemoteAddr", err)
  233. }
  234. return
  235. }
  236. repo, err := models.MigrateRepository(c.User, ctxUser, models.MigrateRepoOptions{
  237. Name: f.RepoName,
  238. Description: f.Description,
  239. IsPrivate: f.Private || setting.Repository.ForcePrivate,
  240. IsMirror: f.Mirror,
  241. RemoteAddr: remoteAddr,
  242. })
  243. if err != nil {
  244. if repo != nil {
  245. if errDelete := models.DeleteRepository(ctxUser.ID, repo.ID); errDelete != nil {
  246. log.Error(2, "DeleteRepository: %v", errDelete)
  247. }
  248. }
  249. if errors.IsReachLimitOfRepo(err) {
  250. c.Error(422, "", err)
  251. } else {
  252. c.Error(500, "MigrateRepository", models.HandleMirrorCredentials(err.Error(), true))
  253. }
  254. return
  255. }
  256. log.Trace("Repository migrated: %s/%s", ctxUser.Name, f.RepoName)
  257. c.JSON(201, repo.APIFormat(&api.Permission{true, true, true}))
  258. }
  259. // FIXME: Inject to *context.APIContext
  260. func parseOwnerAndRepo(c *context.APIContext) (*models.User, *models.Repository) {
  261. owner, err := models.GetUserByName(c.Params(":username"))
  262. if err != nil {
  263. if errors.IsUserNotExist(err) {
  264. c.Error(422, "", err)
  265. } else {
  266. c.Error(500, "GetUserByName", err)
  267. }
  268. return nil, nil
  269. }
  270. repo, err := models.GetRepositoryByName(owner.ID, c.Params(":reponame"))
  271. if err != nil {
  272. if errors.IsRepoNotExist(err) {
  273. c.Status(404)
  274. } else {
  275. c.Error(500, "GetRepositoryByName", err)
  276. }
  277. return nil, nil
  278. }
  279. return owner, repo
  280. }
  281. // https://github.com/gogs/go-gogs-client/wiki/Repositories#get
  282. func Get(c *context.APIContext) {
  283. _, repo := parseOwnerAndRepo(c)
  284. if c.Written() {
  285. return
  286. }
  287. c.JSON(200, repo.APIFormat(&api.Permission{
  288. Admin: c.Repo.IsAdmin(),
  289. Push: c.Repo.IsWriter(),
  290. Pull: true,
  291. }))
  292. }
  293. // https://github.com/gogs/go-gogs-client/wiki/Repositories#delete
  294. func Delete(c *context.APIContext) {
  295. owner, repo := parseOwnerAndRepo(c)
  296. if c.Written() {
  297. return
  298. }
  299. if owner.IsOrganization() && !owner.IsOwnedBy(c.User.ID) {
  300. c.Error(403, "", "Given user is not owner of organization.")
  301. return
  302. }
  303. if err := models.DeleteRepository(owner.ID, repo.ID); err != nil {
  304. c.Error(500, "DeleteRepository", err)
  305. return
  306. }
  307. log.Trace("Repository deleted: %s/%s", owner.Name, repo.Name)
  308. c.Status(204)
  309. }
  310. func ListForks(c *context.APIContext) {
  311. forks, err := c.Repo.Repository.GetForks()
  312. if err != nil {
  313. c.Error(500, "GetForks", err)
  314. return
  315. }
  316. apiForks := make([]*api.Repository, len(forks))
  317. for i := range forks {
  318. if err := forks[i].GetOwner(); err != nil {
  319. c.Error(500, "GetOwner", err)
  320. return
  321. }
  322. apiForks[i] = forks[i].APIFormat(&api.Permission{
  323. Admin: c.User.IsAdminOfRepo(forks[i]),
  324. Push: c.User.IsWriterOfRepo(forks[i]),
  325. Pull: true,
  326. })
  327. }
  328. c.JSON(200, &apiForks)
  329. }
  330. func IssueTracker(c *context.APIContext, form api.EditIssueTrackerOption) {
  331. _, repo := parseOwnerAndRepo(c)
  332. if c.Written() {
  333. return
  334. }
  335. if form.EnableIssues != nil {
  336. repo.EnableIssues = *form.EnableIssues
  337. }
  338. if form.EnableExternalTracker != nil {
  339. repo.EnableExternalTracker = *form.EnableExternalTracker
  340. }
  341. if form.ExternalTrackerURL != nil {
  342. repo.ExternalTrackerURL = *form.ExternalTrackerURL
  343. }
  344. if form.TrackerURLFormat != nil {
  345. repo.ExternalTrackerFormat = *form.TrackerURLFormat
  346. }
  347. if form.TrackerIssueStyle != nil {
  348. repo.ExternalTrackerStyle = *form.TrackerIssueStyle
  349. }
  350. if err := models.UpdateRepository(repo, false); err != nil {
  351. c.ServerError("UpdateRepository", err)
  352. return
  353. }
  354. c.NoContent()
  355. }
  356. func MirrorSync(c *context.APIContext) {
  357. _, repo := parseOwnerAndRepo(c)
  358. if c.Written() {
  359. return
  360. } else if !repo.IsMirror {
  361. c.Status(404)
  362. return
  363. }
  364. go models.MirrorQueue.Add(repo.ID)
  365. c.Status(202)
  366. }