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.

367 lines
10 KiB

10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
Add Attachment API (#3478) * Add Attachment API * repos/:owner/:repo/releases (add attachments) * repos/:owner/:repo/releases/:id (add attachments) * repos/:owner/:repo/releases/:id/attachments * repos/:owner/:repo/releases/:id/attachments/:attachment_id Signed-off-by: Jonas Franz <info@jonasfranz.de> * Add unit tests for new attachment functions Fix comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * fix lint * Update vendor.json Signed-off-by: Jonas Franz <info@jonasfranz.software> * remove version of sdk Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit tests Add missing license header Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add CreateReleaseAttachment Add EditReleaseAttachment Add DeleteReleaseAttachment Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add filename query parameter for choosing another name for an attachment Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix order of imports Signed-off-by: Jonas Franz <info@jonasfranz.software> * Restricting updatable attachment columns Signed-off-by: Jonas Franz <info@jonasfranz.software> * gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update go-sdk Replace Attachments with Assets Signed-off-by: Jonas Franz <info@jonasfranz.de> * Update go-sdk Signed-off-by: Jonas Franz <info@jonasfranz.de> * Updating go-sdk and regenerating swagger Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add missing file of go-sdk Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change origin of code.gitea.io/sdk to code.gitea.io/sdk Update code.gitea.io/sdk Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update swagger Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update updateAttachment
6 years ago
Add Attachment API (#3478) * Add Attachment API * repos/:owner/:repo/releases (add attachments) * repos/:owner/:repo/releases/:id (add attachments) * repos/:owner/:repo/releases/:id/attachments * repos/:owner/:repo/releases/:id/attachments/:attachment_id Signed-off-by: Jonas Franz <info@jonasfranz.de> * Add unit tests for new attachment functions Fix comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * fix lint * Update vendor.json Signed-off-by: Jonas Franz <info@jonasfranz.software> * remove version of sdk Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit tests Add missing license header Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add CreateReleaseAttachment Add EditReleaseAttachment Add DeleteReleaseAttachment Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add filename query parameter for choosing another name for an attachment Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix order of imports Signed-off-by: Jonas Franz <info@jonasfranz.software> * Restricting updatable attachment columns Signed-off-by: Jonas Franz <info@jonasfranz.software> * gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update go-sdk Replace Attachments with Assets Signed-off-by: Jonas Franz <info@jonasfranz.de> * Update go-sdk Signed-off-by: Jonas Franz <info@jonasfranz.de> * Updating go-sdk and regenerating swagger Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add missing file of go-sdk Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change origin of code.gitea.io/sdk to code.gitea.io/sdk Update code.gitea.io/sdk Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update swagger Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update updateAttachment
6 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
9 years ago
9 years ago
10 years ago
9 years ago
10 years ago
9 years ago
9 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
4 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
4 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
4 years ago
10 years ago
10 years ago
9 years ago
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package models
  6. import (
  7. "fmt"
  8. "sort"
  9. "strings"
  10. "code.gitea.io/gitea/modules/setting"
  11. "code.gitea.io/gitea/modules/structs"
  12. api "code.gitea.io/gitea/modules/structs"
  13. "code.gitea.io/gitea/modules/timeutil"
  14. "xorm.io/builder"
  15. )
  16. // Release represents a release of repository.
  17. type Release struct {
  18. ID int64 `xorm:"pk autoincr"`
  19. RepoID int64 `xorm:"INDEX UNIQUE(n)"`
  20. Repo *Repository `xorm:"-"`
  21. PublisherID int64 `xorm:"INDEX"`
  22. Publisher *User `xorm:"-"`
  23. TagName string `xorm:"INDEX UNIQUE(n)"`
  24. OriginalAuthor string
  25. OriginalAuthorID int64 `xorm:"index"`
  26. LowerTagName string
  27. Target string
  28. Title string
  29. Sha1 string `xorm:"VARCHAR(40)"`
  30. NumCommits int64
  31. NumCommitsBehind int64 `xorm:"-"`
  32. Note string `xorm:"TEXT"`
  33. RenderedNote string `xorm:"-"`
  34. IsDraft bool `xorm:"NOT NULL DEFAULT false"`
  35. IsPrerelease bool `xorm:"NOT NULL DEFAULT false"`
  36. IsTag bool `xorm:"NOT NULL DEFAULT false"`
  37. Attachments []*Attachment `xorm:"-"`
  38. CreatedUnix timeutil.TimeStamp `xorm:"INDEX"`
  39. }
  40. func (r *Release) loadAttributes(e Engine) error {
  41. var err error
  42. if r.Repo == nil {
  43. r.Repo, err = GetRepositoryByID(r.RepoID)
  44. if err != nil {
  45. return err
  46. }
  47. }
  48. if r.Publisher == nil {
  49. r.Publisher, err = getUserByID(e, r.PublisherID)
  50. if err != nil {
  51. return err
  52. }
  53. }
  54. return getReleaseAttachments(e, r)
  55. }
  56. // LoadAttributes load repo and publisher attributes for a release
  57. func (r *Release) LoadAttributes() error {
  58. return r.loadAttributes(x)
  59. }
  60. // APIURL the api url for a release. release must have attributes loaded
  61. func (r *Release) APIURL() string {
  62. return fmt.Sprintf("%sapi/v1/repos/%s/releases/%d",
  63. setting.AppURL, r.Repo.FullName(), r.ID)
  64. }
  65. // ZipURL the zip url for a release. release must have attributes loaded
  66. func (r *Release) ZipURL() string {
  67. return fmt.Sprintf("%s/archive/%s.zip", r.Repo.HTMLURL(), r.TagName)
  68. }
  69. // TarURL the tar.gz url for a release. release must have attributes loaded
  70. func (r *Release) TarURL() string {
  71. return fmt.Sprintf("%s/archive/%s.tar.gz", r.Repo.HTMLURL(), r.TagName)
  72. }
  73. // HTMLURL the url for a release on the web UI. release must have attributes loaded
  74. func (r *Release) HTMLURL() string {
  75. return fmt.Sprintf("%s/releases/tag/%s", r.Repo.HTMLURL(), r.TagName)
  76. }
  77. // APIFormat convert a Release to api.Release
  78. func (r *Release) APIFormat() *api.Release {
  79. assets := make([]*api.Attachment, 0)
  80. for _, att := range r.Attachments {
  81. assets = append(assets, att.APIFormat())
  82. }
  83. return &api.Release{
  84. ID: r.ID,
  85. TagName: r.TagName,
  86. Target: r.Target,
  87. Title: r.Title,
  88. Note: r.Note,
  89. URL: r.APIURL(),
  90. HTMLURL: r.HTMLURL(),
  91. TarURL: r.TarURL(),
  92. ZipURL: r.ZipURL(),
  93. IsDraft: r.IsDraft,
  94. IsPrerelease: r.IsPrerelease,
  95. CreatedAt: r.CreatedUnix.AsTime(),
  96. PublishedAt: r.CreatedUnix.AsTime(),
  97. Publisher: r.Publisher.APIFormat(),
  98. Attachments: assets,
  99. }
  100. }
  101. // IsReleaseExist returns true if release with given tag name already exists.
  102. func IsReleaseExist(repoID int64, tagName string) (bool, error) {
  103. if len(tagName) == 0 {
  104. return false, nil
  105. }
  106. return x.Get(&Release{RepoID: repoID, LowerTagName: strings.ToLower(tagName)})
  107. }
  108. // InsertRelease inserts a release
  109. func InsertRelease(rel *Release) error {
  110. _, err := x.Insert(rel)
  111. return err
  112. }
  113. // InsertReleasesContext insert releases
  114. func InsertReleasesContext(ctx DBContext, rels []*Release) error {
  115. _, err := ctx.e.Insert(rels)
  116. return err
  117. }
  118. // UpdateRelease updates all columns of a release
  119. func UpdateRelease(ctx DBContext, rel *Release) error {
  120. _, err := ctx.e.ID(rel.ID).AllCols().Update(rel)
  121. return err
  122. }
  123. // AddReleaseAttachments adds a release attachments
  124. func AddReleaseAttachments(releaseID int64, attachmentUUIDs []string) (err error) {
  125. // Check attachments
  126. attachments, err := GetAttachmentsByUUIDs(attachmentUUIDs)
  127. if err != nil {
  128. return fmt.Errorf("GetAttachmentsByUUIDs [uuids: %v]: %v", attachmentUUIDs, err)
  129. }
  130. for i := range attachments {
  131. attachments[i].ReleaseID = releaseID
  132. // No assign value could be 0, so ignore AllCols().
  133. if _, err = x.ID(attachments[i].ID).Update(attachments[i]); err != nil {
  134. return fmt.Errorf("update attachment [%d]: %v", attachments[i].ID, err)
  135. }
  136. }
  137. return
  138. }
  139. // GetRelease returns release by given ID.
  140. func GetRelease(repoID int64, tagName string) (*Release, error) {
  141. isExist, err := IsReleaseExist(repoID, tagName)
  142. if err != nil {
  143. return nil, err
  144. } else if !isExist {
  145. return nil, ErrReleaseNotExist{0, tagName}
  146. }
  147. rel := &Release{RepoID: repoID, LowerTagName: strings.ToLower(tagName)}
  148. _, err = x.Get(rel)
  149. return rel, err
  150. }
  151. // GetReleaseByID returns release with given ID.
  152. func GetReleaseByID(id int64) (*Release, error) {
  153. rel := new(Release)
  154. has, err := x.
  155. ID(id).
  156. Get(rel)
  157. if err != nil {
  158. return nil, err
  159. } else if !has {
  160. return nil, ErrReleaseNotExist{id, ""}
  161. }
  162. return rel, nil
  163. }
  164. // FindReleasesOptions describes the conditions to Find releases
  165. type FindReleasesOptions struct {
  166. ListOptions
  167. IncludeDrafts bool
  168. IncludeTags bool
  169. TagNames []string
  170. }
  171. func (opts *FindReleasesOptions) toConds(repoID int64) builder.Cond {
  172. var cond = builder.NewCond()
  173. cond = cond.And(builder.Eq{"repo_id": repoID})
  174. if !opts.IncludeDrafts {
  175. cond = cond.And(builder.Eq{"is_draft": false})
  176. }
  177. if !opts.IncludeTags {
  178. cond = cond.And(builder.Eq{"is_tag": false})
  179. }
  180. if len(opts.TagNames) > 0 {
  181. cond = cond.And(builder.In("tag_name", opts.TagNames))
  182. }
  183. return cond
  184. }
  185. // GetReleasesByRepoID returns a list of releases of repository.
  186. func GetReleasesByRepoID(repoID int64, opts FindReleasesOptions) ([]*Release, error) {
  187. sess := x.
  188. Desc("created_unix", "id").
  189. Where(opts.toConds(repoID))
  190. if opts.PageSize != 0 {
  191. sess = opts.setSessionPagination(sess)
  192. }
  193. rels := make([]*Release, 0, opts.PageSize)
  194. return rels, sess.Find(&rels)
  195. }
  196. // GetLatestReleaseByRepoID returns the latest release for a repository
  197. func GetLatestReleaseByRepoID(repoID int64) (*Release, error) {
  198. cond := builder.NewCond().
  199. And(builder.Eq{"repo_id": repoID}).
  200. And(builder.Eq{"is_draft": false}).
  201. And(builder.Eq{"is_prerelease": false}).
  202. And(builder.Eq{"is_tag": false})
  203. rel := new(Release)
  204. has, err := x.
  205. Desc("created_unix", "id").
  206. Where(cond).
  207. Get(rel)
  208. if err != nil {
  209. return nil, err
  210. } else if !has {
  211. return nil, ErrReleaseNotExist{0, "latest"}
  212. }
  213. return rel, nil
  214. }
  215. // GetReleasesByRepoIDAndNames returns a list of releases of repository according repoID and tagNames.
  216. func GetReleasesByRepoIDAndNames(ctx DBContext, repoID int64, tagNames []string) (rels []*Release, err error) {
  217. err = ctx.e.
  218. In("tag_name", tagNames).
  219. Desc("created_unix").
  220. Find(&rels, Release{RepoID: repoID})
  221. return rels, err
  222. }
  223. // GetReleaseCountByRepoID returns the count of releases of repository
  224. func GetReleaseCountByRepoID(repoID int64, opts FindReleasesOptions) (int64, error) {
  225. return x.Where(opts.toConds(repoID)).Count(&Release{})
  226. }
  227. type releaseMetaSearch struct {
  228. ID []int64
  229. Rel []*Release
  230. }
  231. func (s releaseMetaSearch) Len() int {
  232. return len(s.ID)
  233. }
  234. func (s releaseMetaSearch) Swap(i, j int) {
  235. s.ID[i], s.ID[j] = s.ID[j], s.ID[i]
  236. s.Rel[i], s.Rel[j] = s.Rel[j], s.Rel[i]
  237. }
  238. func (s releaseMetaSearch) Less(i, j int) bool {
  239. return s.ID[i] < s.ID[j]
  240. }
  241. // GetReleaseAttachments retrieves the attachments for releases
  242. func GetReleaseAttachments(rels ...*Release) (err error) {
  243. return getReleaseAttachments(x, rels...)
  244. }
  245. func getReleaseAttachments(e Engine, rels ...*Release) (err error) {
  246. if len(rels) == 0 {
  247. return
  248. }
  249. // To keep this efficient as possible sort all releases by id,
  250. // select attachments by release id,
  251. // then merge join them
  252. // Sort
  253. var sortedRels = releaseMetaSearch{ID: make([]int64, len(rels)), Rel: make([]*Release, len(rels))}
  254. var attachments []*Attachment
  255. for index, element := range rels {
  256. element.Attachments = []*Attachment{}
  257. sortedRels.ID[index] = element.ID
  258. sortedRels.Rel[index] = element
  259. }
  260. sort.Sort(sortedRels)
  261. // Select attachments
  262. err = e.
  263. Asc("release_id").
  264. In("release_id", sortedRels.ID).
  265. Find(&attachments, Attachment{})
  266. if err != nil {
  267. return err
  268. }
  269. // merge join
  270. var currentIndex = 0
  271. for _, attachment := range attachments {
  272. for sortedRels.ID[currentIndex] < attachment.ReleaseID {
  273. currentIndex++
  274. }
  275. sortedRels.Rel[currentIndex].Attachments = append(sortedRels.Rel[currentIndex].Attachments, attachment)
  276. }
  277. return
  278. }
  279. type releaseSorter struct {
  280. rels []*Release
  281. }
  282. func (rs *releaseSorter) Len() int {
  283. return len(rs.rels)
  284. }
  285. func (rs *releaseSorter) Less(i, j int) bool {
  286. diffNum := rs.rels[i].NumCommits - rs.rels[j].NumCommits
  287. if diffNum != 0 {
  288. return diffNum > 0
  289. }
  290. return rs.rels[i].CreatedUnix > rs.rels[j].CreatedUnix
  291. }
  292. func (rs *releaseSorter) Swap(i, j int) {
  293. rs.rels[i], rs.rels[j] = rs.rels[j], rs.rels[i]
  294. }
  295. // SortReleases sorts releases by number of commits and created time.
  296. func SortReleases(rels []*Release) {
  297. sorter := &releaseSorter{rels: rels}
  298. sort.Sort(sorter)
  299. }
  300. // DeleteReleaseByID deletes a release from database by given ID.
  301. func DeleteReleaseByID(id int64) error {
  302. _, err := x.ID(id).Delete(new(Release))
  303. return err
  304. }
  305. // UpdateReleasesMigrationsByType updates all migrated repositories' releases from gitServiceType to replace originalAuthorID to posterID
  306. func UpdateReleasesMigrationsByType(gitServiceType structs.GitServiceType, originalAuthorID string, posterID int64) error {
  307. _, err := x.Table("release").
  308. Where("repo_id IN (SELECT id FROM repository WHERE original_service_type = ?)", gitServiceType).
  309. And("original_author_id = ?", originalAuthorID).
  310. Update(map[string]interface{}{
  311. "publisher_id": posterID,
  312. "original_author": "",
  313. "original_author_id": 0,
  314. })
  315. return err
  316. }