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.

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