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.

407 lines
10 KiB

10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
10 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
10 years ago
10 years ago
9 years ago
10 years ago
9 years ago
9 years ago
9 years ago
  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 models
  5. import (
  6. "fmt"
  7. "sort"
  8. "strings"
  9. "time"
  10. "code.gitea.io/git"
  11. "code.gitea.io/gitea/modules/process"
  12. "code.gitea.io/gitea/modules/setting"
  13. api "code.gitea.io/sdk/gitea"
  14. "github.com/go-xorm/builder"
  15. "github.com/go-xorm/xorm"
  16. )
  17. // Release represents a release of repository.
  18. type Release struct {
  19. ID int64 `xorm:"pk autoincr"`
  20. RepoID int64 `xorm:"INDEX UNIQUE(n)"`
  21. Repo *Repository `xorm:"-"`
  22. PublisherID int64 `xorm:"INDEX"`
  23. Publisher *User `xorm:"-"`
  24. TagName string `xorm:"INDEX UNIQUE(n)"`
  25. LowerTagName string
  26. Target string
  27. Title string
  28. Sha1 string `xorm:"VARCHAR(40)"`
  29. NumCommits int64
  30. NumCommitsBehind int64 `xorm:"-"`
  31. Note string `xorm:"TEXT"`
  32. IsDraft bool `xorm:"NOT NULL DEFAULT false"`
  33. IsPrerelease bool
  34. Attachments []*Attachment `xorm:"-"`
  35. Created time.Time `xorm:"-"`
  36. CreatedUnix int64 `xorm:"INDEX"`
  37. }
  38. // BeforeInsert is invoked from XORM before inserting an object of this type.
  39. func (r *Release) BeforeInsert() {
  40. if r.CreatedUnix == 0 {
  41. r.CreatedUnix = time.Now().Unix()
  42. }
  43. }
  44. // AfterSet is invoked from XORM after setting the value of a field of this object.
  45. func (r *Release) AfterSet(colName string, _ xorm.Cell) {
  46. switch colName {
  47. case "created_unix":
  48. r.Created = time.Unix(r.CreatedUnix, 0).Local()
  49. }
  50. }
  51. func (r *Release) loadAttributes(e Engine) error {
  52. var err error
  53. if r.Repo == nil {
  54. r.Repo, err = GetRepositoryByID(r.RepoID)
  55. if err != nil {
  56. return err
  57. }
  58. }
  59. if r.Publisher == nil {
  60. r.Publisher, err = GetUserByID(r.PublisherID)
  61. if err != nil {
  62. return err
  63. }
  64. }
  65. return nil
  66. }
  67. // LoadAttributes load repo and publisher attributes for a release
  68. func (r *Release) LoadAttributes() error {
  69. return r.loadAttributes(x)
  70. }
  71. // APIURL the api url for a release. release must have attributes loaded
  72. func (r *Release) APIURL() string {
  73. return fmt.Sprintf("%sapi/v1/%s/releases/%d",
  74. setting.AppURL, r.Repo.FullName(), r.ID)
  75. }
  76. // ZipURL the zip url for a release. release must have attributes loaded
  77. func (r *Release) ZipURL() string {
  78. return fmt.Sprintf("%s/archive/%s.zip", r.Repo.HTMLURL(), r.TagName)
  79. }
  80. // TarURL the tar.gz url for a release. release must have attributes loaded
  81. func (r *Release) TarURL() string {
  82. return fmt.Sprintf("%s/archive/%s.tar.gz", r.Repo.HTMLURL(), r.TagName)
  83. }
  84. // APIFormat convert a Release to api.Release
  85. func (r *Release) APIFormat() *api.Release {
  86. return &api.Release{
  87. ID: r.ID,
  88. TagName: r.TagName,
  89. Target: r.Target,
  90. Note: r.Note,
  91. URL: r.APIURL(),
  92. TarURL: r.TarURL(),
  93. ZipURL: r.ZipURL(),
  94. IsDraft: r.IsDraft,
  95. IsPrerelease: r.IsPrerelease,
  96. CreatedAt: r.Created,
  97. PublishedAt: r.Created,
  98. Publisher: r.Publisher.APIFormat(),
  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. func createTag(gitRepo *git.Repository, rel *Release) error {
  109. // Only actual create when publish.
  110. if !rel.IsDraft {
  111. if !gitRepo.IsTagExist(rel.TagName) {
  112. commit, err := gitRepo.GetBranchCommit(rel.Target)
  113. if err != nil {
  114. return fmt.Errorf("GetBranchCommit: %v", err)
  115. }
  116. // Trim '--' prefix to prevent command line argument vulnerability.
  117. rel.TagName = strings.TrimPrefix(rel.TagName, "--")
  118. if err = gitRepo.CreateTag(rel.TagName, commit.ID.String()); err != nil {
  119. if strings.Contains(err.Error(), "is not a valid tag name") {
  120. return ErrInvalidTagName{rel.TagName}
  121. }
  122. return err
  123. }
  124. } else {
  125. commit, err := gitRepo.GetTagCommit(rel.TagName)
  126. if err != nil {
  127. return fmt.Errorf("GetTagCommit: %v", err)
  128. }
  129. rel.Sha1 = commit.ID.String()
  130. rel.NumCommits, err = commit.CommitsCount()
  131. if err != nil {
  132. return fmt.Errorf("CommitsCount: %v", err)
  133. }
  134. }
  135. }
  136. return nil
  137. }
  138. func addReleaseAttachments(releaseID int64, attachmentUUIDs []string) (err error) {
  139. // Check attachments
  140. var attachments = make([]*Attachment, 0)
  141. for _, uuid := range attachmentUUIDs {
  142. attach, err := getAttachmentByUUID(x, uuid)
  143. if err != nil {
  144. if IsErrAttachmentNotExist(err) {
  145. continue
  146. }
  147. return fmt.Errorf("getAttachmentByUUID [%s]: %v", uuid, err)
  148. }
  149. attachments = append(attachments, attach)
  150. }
  151. for i := range attachments {
  152. attachments[i].ReleaseID = releaseID
  153. // No assign value could be 0, so ignore AllCols().
  154. if _, err = x.Id(attachments[i].ID).Update(attachments[i]); err != nil {
  155. return fmt.Errorf("update attachment [%d]: %v", attachments[i].ID, err)
  156. }
  157. }
  158. return
  159. }
  160. // CreateRelease creates a new release of repository.
  161. func CreateRelease(gitRepo *git.Repository, rel *Release, attachmentUUIDs []string) error {
  162. isExist, err := IsReleaseExist(rel.RepoID, rel.TagName)
  163. if err != nil {
  164. return err
  165. } else if isExist {
  166. return ErrReleaseAlreadyExist{rel.TagName}
  167. }
  168. if err = createTag(gitRepo, rel); err != nil {
  169. return err
  170. }
  171. rel.LowerTagName = strings.ToLower(rel.TagName)
  172. _, err = x.InsertOne(rel)
  173. if err != nil {
  174. return err
  175. }
  176. err = addReleaseAttachments(rel.ID, attachmentUUIDs)
  177. return err
  178. }
  179. // GetRelease returns release by given ID.
  180. func GetRelease(repoID int64, tagName string) (*Release, error) {
  181. isExist, err := IsReleaseExist(repoID, tagName)
  182. if err != nil {
  183. return nil, err
  184. } else if !isExist {
  185. return nil, ErrReleaseNotExist{0, tagName}
  186. }
  187. rel := &Release{RepoID: repoID, LowerTagName: strings.ToLower(tagName)}
  188. _, err = x.Get(rel)
  189. return rel, err
  190. }
  191. // GetReleaseByID returns release with given ID.
  192. func GetReleaseByID(id int64) (*Release, error) {
  193. rel := new(Release)
  194. has, err := x.
  195. Id(id).
  196. Get(rel)
  197. if err != nil {
  198. return nil, err
  199. } else if !has {
  200. return nil, ErrReleaseNotExist{id, ""}
  201. }
  202. return rel, nil
  203. }
  204. // FindReleasesOptions describes the conditions to Find releases
  205. type FindReleasesOptions struct {
  206. IncludeDrafts bool
  207. TagNames []string
  208. }
  209. func (opts *FindReleasesOptions) toConds(repoID int64) builder.Cond {
  210. var cond = builder.NewCond()
  211. cond = cond.And(builder.Eq{"repo_id": repoID})
  212. if !opts.IncludeDrafts {
  213. cond = cond.And(builder.Eq{"is_draft": false})
  214. }
  215. if len(opts.TagNames) > 0 {
  216. cond = cond.And(builder.In("tag_name", opts.TagNames))
  217. }
  218. return cond
  219. }
  220. // GetReleasesByRepoID returns a list of releases of repository.
  221. func GetReleasesByRepoID(repoID int64, opts FindReleasesOptions, page, pageSize int) (rels []*Release, err error) {
  222. if page <= 0 {
  223. page = 1
  224. }
  225. err = x.
  226. Desc("created_unix", "id").
  227. Limit(pageSize, (page-1)*pageSize).
  228. Where(opts.toConds(repoID)).
  229. Find(&rels)
  230. return rels, err
  231. }
  232. // GetReleaseCountByRepoID returns the count of releases of repository
  233. func GetReleaseCountByRepoID(repoID int64, opts FindReleasesOptions) (int64, error) {
  234. return x.Where(opts.toConds(repoID)).Count(&Release{})
  235. }
  236. type releaseMetaSearch struct {
  237. ID []int64
  238. Rel []*Release
  239. }
  240. func (s releaseMetaSearch) Len() int {
  241. return len(s.ID)
  242. }
  243. func (s releaseMetaSearch) Swap(i, j int) {
  244. s.ID[i], s.ID[j] = s.ID[j], s.ID[i]
  245. s.Rel[i], s.Rel[j] = s.Rel[j], s.Rel[i]
  246. }
  247. func (s releaseMetaSearch) Less(i, j int) bool {
  248. return s.ID[i] < s.ID[j]
  249. }
  250. // GetReleaseAttachments retrieves the attachments for releases
  251. func GetReleaseAttachments(rels ...*Release) (err error) {
  252. if len(rels) == 0 {
  253. return
  254. }
  255. // To keep this efficient as possible sort all releases by id,
  256. // select attachments by release id,
  257. // then merge join them
  258. // Sort
  259. var sortedRels = releaseMetaSearch{ID: make([]int64, len(rels)), Rel: make([]*Release, len(rels))}
  260. var attachments []*Attachment
  261. for index, element := range rels {
  262. element.Attachments = []*Attachment{}
  263. sortedRels.ID[index] = element.ID
  264. sortedRels.Rel[index] = element
  265. }
  266. sort.Sort(sortedRels)
  267. // Select attachments
  268. err = x.
  269. Asc("release_id").
  270. In("release_id", sortedRels.ID).
  271. Find(&attachments, Attachment{})
  272. if err != nil {
  273. return err
  274. }
  275. // merge join
  276. var currentIndex = 0
  277. for _, attachment := range attachments {
  278. for sortedRels.ID[currentIndex] < attachment.ReleaseID {
  279. currentIndex++
  280. }
  281. sortedRels.Rel[currentIndex].Attachments = append(sortedRels.Rel[currentIndex].Attachments, attachment)
  282. }
  283. return
  284. }
  285. type releaseSorter struct {
  286. rels []*Release
  287. }
  288. func (rs *releaseSorter) Len() int {
  289. return len(rs.rels)
  290. }
  291. func (rs *releaseSorter) Less(i, j int) bool {
  292. diffNum := rs.rels[i].NumCommits - rs.rels[j].NumCommits
  293. if diffNum != 0 {
  294. return diffNum > 0
  295. }
  296. return rs.rels[i].Created.After(rs.rels[j].Created)
  297. }
  298. func (rs *releaseSorter) Swap(i, j int) {
  299. rs.rels[i], rs.rels[j] = rs.rels[j], rs.rels[i]
  300. }
  301. // SortReleases sorts releases by number of commits and created time.
  302. func SortReleases(rels []*Release) {
  303. sorter := &releaseSorter{rels: rels}
  304. sort.Sort(sorter)
  305. }
  306. // UpdateRelease updates information of a release.
  307. func UpdateRelease(gitRepo *git.Repository, rel *Release, attachmentUUIDs []string) (err error) {
  308. if err = createTag(gitRepo, rel); err != nil {
  309. return err
  310. }
  311. _, err = x.Id(rel.ID).AllCols().Update(rel)
  312. if err != nil {
  313. return err
  314. }
  315. err = addReleaseAttachments(rel.ID, attachmentUUIDs)
  316. return err
  317. }
  318. // DeleteReleaseByID deletes a release and corresponding Git tag by given ID.
  319. func DeleteReleaseByID(id int64, u *User, delTag bool) error {
  320. rel, err := GetReleaseByID(id)
  321. if err != nil {
  322. return fmt.Errorf("GetReleaseByID: %v", err)
  323. }
  324. repo, err := GetRepositoryByID(rel.RepoID)
  325. if err != nil {
  326. return fmt.Errorf("GetRepositoryByID: %v", err)
  327. }
  328. has, err := HasAccess(u.ID, repo, AccessModeWrite)
  329. if err != nil {
  330. return fmt.Errorf("HasAccess: %v", err)
  331. } else if !has {
  332. return fmt.Errorf("DeleteReleaseByID: permission denied")
  333. }
  334. if delTag {
  335. _, stderr, err := process.GetManager().ExecDir(-1, repo.RepoPath(),
  336. fmt.Sprintf("DeleteReleaseByID (git tag -d): %d", rel.ID),
  337. "git", "tag", "-d", rel.TagName)
  338. if err != nil && !strings.Contains(stderr, "not found") {
  339. return fmt.Errorf("git tag -d: %v - %s", err, stderr)
  340. }
  341. }
  342. if _, err = x.Id(rel.ID).Delete(new(Release)); err != nil {
  343. return fmt.Errorf("Delete: %v", err)
  344. }
  345. return nil
  346. }