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.

366 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. IsDraft bool `xorm:"NOT NULL DEFAULT false"`
  34. IsPrerelease bool `xorm:"NOT NULL DEFAULT false"`
  35. IsTag bool `xorm:"NOT NULL DEFAULT false"`
  36. Attachments []*Attachment `xorm:"-"`
  37. CreatedUnix timeutil.TimeStamp `xorm:"INDEX"`
  38. }
  39. func (r *Release) loadAttributes(e Engine) error {
  40. var err error
  41. if r.Repo == nil {
  42. r.Repo, err = GetRepositoryByID(r.RepoID)
  43. if err != nil {
  44. return err
  45. }
  46. }
  47. if r.Publisher == nil {
  48. r.Publisher, err = getUserByID(e, r.PublisherID)
  49. if err != nil {
  50. return err
  51. }
  52. }
  53. return getReleaseAttachments(e, r)
  54. }
  55. // LoadAttributes load repo and publisher attributes for a release
  56. func (r *Release) LoadAttributes() error {
  57. return r.loadAttributes(x)
  58. }
  59. // APIURL the api url for a release. release must have attributes loaded
  60. func (r *Release) APIURL() string {
  61. return fmt.Sprintf("%sapi/v1/repos/%s/releases/%d",
  62. setting.AppURL, r.Repo.FullName(), r.ID)
  63. }
  64. // ZipURL the zip url for a release. release must have attributes loaded
  65. func (r *Release) ZipURL() string {
  66. return fmt.Sprintf("%s/archive/%s.zip", r.Repo.HTMLURL(), r.TagName)
  67. }
  68. // TarURL the tar.gz url for a release. release must have attributes loaded
  69. func (r *Release) TarURL() string {
  70. return fmt.Sprintf("%s/archive/%s.tar.gz", r.Repo.HTMLURL(), r.TagName)
  71. }
  72. // HTMLURL the url for a release on the web UI. release must have attributes loaded
  73. func (r *Release) HTMLURL() string {
  74. return fmt.Sprintf("%s/releases/tag/%s", r.Repo.HTMLURL(), r.TagName)
  75. }
  76. // APIFormat convert a Release to api.Release
  77. func (r *Release) APIFormat() *api.Release {
  78. assets := make([]*api.Attachment, 0)
  79. for _, att := range r.Attachments {
  80. assets = append(assets, att.APIFormat())
  81. }
  82. return &api.Release{
  83. ID: r.ID,
  84. TagName: r.TagName,
  85. Target: r.Target,
  86. Title: r.Title,
  87. Note: r.Note,
  88. URL: r.APIURL(),
  89. HTMLURL: r.HTMLURL(),
  90. TarURL: r.TarURL(),
  91. ZipURL: r.ZipURL(),
  92. IsDraft: r.IsDraft,
  93. IsPrerelease: r.IsPrerelease,
  94. CreatedAt: r.CreatedUnix.AsTime(),
  95. PublishedAt: r.CreatedUnix.AsTime(),
  96. Publisher: r.Publisher.APIFormat(),
  97. Attachments: assets,
  98. }
  99. }
  100. // IsReleaseExist returns true if release with given tag name already exists.
  101. func IsReleaseExist(repoID int64, tagName string) (bool, error) {
  102. if len(tagName) == 0 {
  103. return false, nil
  104. }
  105. return x.Get(&Release{RepoID: repoID, LowerTagName: strings.ToLower(tagName)})
  106. }
  107. // InsertRelease inserts a release
  108. func InsertRelease(rel *Release) error {
  109. _, err := x.Insert(rel)
  110. return err
  111. }
  112. // InsertReleasesContext insert releases
  113. func InsertReleasesContext(ctx DBContext, rels []*Release) error {
  114. _, err := ctx.e.Insert(rels)
  115. return err
  116. }
  117. // UpdateRelease updates all columns of a release
  118. func UpdateRelease(ctx DBContext, rel *Release) error {
  119. _, err := ctx.e.ID(rel.ID).AllCols().Update(rel)
  120. return err
  121. }
  122. // AddReleaseAttachments adds a release attachments
  123. func AddReleaseAttachments(releaseID int64, attachmentUUIDs []string) (err error) {
  124. // Check attachments
  125. attachments, err := GetAttachmentsByUUIDs(attachmentUUIDs)
  126. if err != nil {
  127. return fmt.Errorf("GetAttachmentsByUUIDs [uuids: %v]: %v", attachmentUUIDs, err)
  128. }
  129. for i := range attachments {
  130. attachments[i].ReleaseID = releaseID
  131. // No assign value could be 0, so ignore AllCols().
  132. if _, err = x.ID(attachments[i].ID).Update(attachments[i]); err != nil {
  133. return fmt.Errorf("update attachment [%d]: %v", attachments[i].ID, err)
  134. }
  135. }
  136. return
  137. }
  138. // GetRelease returns release by given ID.
  139. func GetRelease(repoID int64, tagName string) (*Release, error) {
  140. isExist, err := IsReleaseExist(repoID, tagName)
  141. if err != nil {
  142. return nil, err
  143. } else if !isExist {
  144. return nil, ErrReleaseNotExist{0, tagName}
  145. }
  146. rel := &Release{RepoID: repoID, LowerTagName: strings.ToLower(tagName)}
  147. _, err = x.Get(rel)
  148. return rel, err
  149. }
  150. // GetReleaseByID returns release with given ID.
  151. func GetReleaseByID(id int64) (*Release, error) {
  152. rel := new(Release)
  153. has, err := x.
  154. ID(id).
  155. Get(rel)
  156. if err != nil {
  157. return nil, err
  158. } else if !has {
  159. return nil, ErrReleaseNotExist{id, ""}
  160. }
  161. return rel, nil
  162. }
  163. // FindReleasesOptions describes the conditions to Find releases
  164. type FindReleasesOptions struct {
  165. ListOptions
  166. IncludeDrafts bool
  167. IncludeTags bool
  168. TagNames []string
  169. }
  170. func (opts *FindReleasesOptions) toConds(repoID int64) builder.Cond {
  171. var cond = builder.NewCond()
  172. cond = cond.And(builder.Eq{"repo_id": repoID})
  173. if !opts.IncludeDrafts {
  174. cond = cond.And(builder.Eq{"is_draft": false})
  175. }
  176. if !opts.IncludeTags {
  177. cond = cond.And(builder.Eq{"is_tag": false})
  178. }
  179. if len(opts.TagNames) > 0 {
  180. cond = cond.And(builder.In("tag_name", opts.TagNames))
  181. }
  182. return cond
  183. }
  184. // GetReleasesByRepoID returns a list of releases of repository.
  185. func GetReleasesByRepoID(repoID int64, opts FindReleasesOptions) ([]*Release, error) {
  186. sess := x.
  187. Desc("created_unix", "id").
  188. Where(opts.toConds(repoID))
  189. if opts.PageSize != 0 {
  190. sess = opts.setSessionPagination(sess)
  191. }
  192. rels := make([]*Release, 0, opts.PageSize)
  193. return rels, sess.Find(&rels)
  194. }
  195. // GetLatestReleaseByRepoID returns the latest release for a repository
  196. func GetLatestReleaseByRepoID(repoID int64) (*Release, error) {
  197. cond := builder.NewCond().
  198. And(builder.Eq{"repo_id": repoID}).
  199. And(builder.Eq{"is_draft": false}).
  200. And(builder.Eq{"is_prerelease": false}).
  201. And(builder.Eq{"is_tag": false})
  202. rel := new(Release)
  203. has, err := x.
  204. Desc("created_unix", "id").
  205. Where(cond).
  206. Get(rel)
  207. if err != nil {
  208. return nil, err
  209. } else if !has {
  210. return nil, ErrReleaseNotExist{0, "latest"}
  211. }
  212. return rel, nil
  213. }
  214. // GetReleasesByRepoIDAndNames returns a list of releases of repository according repoID and tagNames.
  215. func GetReleasesByRepoIDAndNames(ctx DBContext, repoID int64, tagNames []string) (rels []*Release, err error) {
  216. err = ctx.e.
  217. In("tag_name", tagNames).
  218. Desc("created_unix").
  219. Find(&rels, Release{RepoID: repoID})
  220. return rels, err
  221. }
  222. // GetReleaseCountByRepoID returns the count of releases of repository
  223. func GetReleaseCountByRepoID(repoID int64, opts FindReleasesOptions) (int64, error) {
  224. return x.Where(opts.toConds(repoID)).Count(&Release{})
  225. }
  226. type releaseMetaSearch struct {
  227. ID []int64
  228. Rel []*Release
  229. }
  230. func (s releaseMetaSearch) Len() int {
  231. return len(s.ID)
  232. }
  233. func (s releaseMetaSearch) Swap(i, j int) {
  234. s.ID[i], s.ID[j] = s.ID[j], s.ID[i]
  235. s.Rel[i], s.Rel[j] = s.Rel[j], s.Rel[i]
  236. }
  237. func (s releaseMetaSearch) Less(i, j int) bool {
  238. return s.ID[i] < s.ID[j]
  239. }
  240. // GetReleaseAttachments retrieves the attachments for releases
  241. func GetReleaseAttachments(rels ...*Release) (err error) {
  242. return getReleaseAttachments(x, rels...)
  243. }
  244. func getReleaseAttachments(e Engine, rels ...*Release) (err error) {
  245. if len(rels) == 0 {
  246. return
  247. }
  248. // To keep this efficient as possible sort all releases by id,
  249. // select attachments by release id,
  250. // then merge join them
  251. // Sort
  252. var sortedRels = releaseMetaSearch{ID: make([]int64, len(rels)), Rel: make([]*Release, len(rels))}
  253. var attachments []*Attachment
  254. for index, element := range rels {
  255. element.Attachments = []*Attachment{}
  256. sortedRels.ID[index] = element.ID
  257. sortedRels.Rel[index] = element
  258. }
  259. sort.Sort(sortedRels)
  260. // Select attachments
  261. err = e.
  262. Asc("release_id").
  263. In("release_id", sortedRels.ID).
  264. Find(&attachments, Attachment{})
  265. if err != nil {
  266. return err
  267. }
  268. // merge join
  269. var currentIndex = 0
  270. for _, attachment := range attachments {
  271. for sortedRels.ID[currentIndex] < attachment.ReleaseID {
  272. currentIndex++
  273. }
  274. sortedRels.Rel[currentIndex].Attachments = append(sortedRels.Rel[currentIndex].Attachments, attachment)
  275. }
  276. return
  277. }
  278. type releaseSorter struct {
  279. rels []*Release
  280. }
  281. func (rs *releaseSorter) Len() int {
  282. return len(rs.rels)
  283. }
  284. func (rs *releaseSorter) Less(i, j int) bool {
  285. diffNum := rs.rels[i].NumCommits - rs.rels[j].NumCommits
  286. if diffNum != 0 {
  287. return diffNum > 0
  288. }
  289. return rs.rels[i].CreatedUnix > rs.rels[j].CreatedUnix
  290. }
  291. func (rs *releaseSorter) Swap(i, j int) {
  292. rs.rels[i], rs.rels[j] = rs.rels[j], rs.rels[i]
  293. }
  294. // SortReleases sorts releases by number of commits and created time.
  295. func SortReleases(rels []*Release) {
  296. sorter := &releaseSorter{rels: rels}
  297. sort.Sort(sorter)
  298. }
  299. // DeleteReleaseByID deletes a release from database by given ID.
  300. func DeleteReleaseByID(id int64) error {
  301. _, err := x.ID(id).Delete(new(Release))
  302. return err
  303. }
  304. // UpdateReleasesMigrationsByType updates all migrated repositories' releases from gitServiceType to replace originalAuthorID to posterID
  305. func UpdateReleasesMigrationsByType(gitServiceType structs.GitServiceType, originalAuthorID string, posterID int64) error {
  306. _, err := x.Table("release").
  307. Where("repo_id IN (SELECT id FROM repository WHERE original_service_type = ?)", gitServiceType).
  308. And("original_author_id = ?", originalAuthorID).
  309. Update(map[string]interface{}{
  310. "publisher_id": posterID,
  311. "original_author": "",
  312. "original_author_id": 0,
  313. })
  314. return err
  315. }