repo.go 10 KB

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