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.

449 lines
12 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
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
10 years ago
9 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. "code.gitea.io/git"
  10. "code.gitea.io/gitea/modules/process"
  11. "code.gitea.io/gitea/modules/setting"
  12. "code.gitea.io/gitea/modules/util"
  13. api "code.gitea.io/sdk/gitea"
  14. "github.com/go-xorm/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. 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 `xorm:"NOT NULL DEFAULT false"`
  33. IsTag bool `xorm:"NOT NULL DEFAULT false"`
  34. Attachments []*Attachment `xorm:"-"`
  35. CreatedUnix util.TimeStamp `xorm:"created INDEX"`
  36. }
  37. func (r *Release) loadAttributes(e Engine) error {
  38. var err error
  39. if r.Repo == nil {
  40. r.Repo, err = GetRepositoryByID(r.RepoID)
  41. if err != nil {
  42. return err
  43. }
  44. }
  45. if r.Publisher == nil {
  46. r.Publisher, err = GetUserByID(r.PublisherID)
  47. if err != nil {
  48. return err
  49. }
  50. }
  51. return nil
  52. }
  53. // LoadAttributes load repo and publisher attributes for a release
  54. func (r *Release) LoadAttributes() error {
  55. return r.loadAttributes(x)
  56. }
  57. // APIURL the api url for a release. release must have attributes loaded
  58. func (r *Release) APIURL() string {
  59. return fmt.Sprintf("%sapi/v1/%s/releases/%d",
  60. setting.AppURL, r.Repo.FullName(), r.ID)
  61. }
  62. // ZipURL the zip url for a release. release must have attributes loaded
  63. func (r *Release) ZipURL() string {
  64. return fmt.Sprintf("%s/archive/%s.zip", r.Repo.HTMLURL(), r.TagName)
  65. }
  66. // TarURL the tar.gz url for a release. release must have attributes loaded
  67. func (r *Release) TarURL() string {
  68. return fmt.Sprintf("%s/archive/%s.tar.gz", r.Repo.HTMLURL(), r.TagName)
  69. }
  70. // APIFormat convert a Release to api.Release
  71. func (r *Release) APIFormat() *api.Release {
  72. return &api.Release{
  73. ID: r.ID,
  74. TagName: r.TagName,
  75. Target: r.Target,
  76. Note: r.Note,
  77. URL: r.APIURL(),
  78. TarURL: r.TarURL(),
  79. ZipURL: r.ZipURL(),
  80. IsDraft: r.IsDraft,
  81. IsPrerelease: r.IsPrerelease,
  82. CreatedAt: r.CreatedUnix.AsTime(),
  83. PublishedAt: r.CreatedUnix.AsTime(),
  84. Publisher: r.Publisher.APIFormat(),
  85. }
  86. }
  87. // IsReleaseExist returns true if release with given tag name already exists.
  88. func IsReleaseExist(repoID int64, tagName string) (bool, error) {
  89. if len(tagName) == 0 {
  90. return false, nil
  91. }
  92. return x.Get(&Release{RepoID: repoID, LowerTagName: strings.ToLower(tagName)})
  93. }
  94. func createTag(gitRepo *git.Repository, rel *Release) error {
  95. // Only actual create when publish.
  96. if !rel.IsDraft {
  97. if !gitRepo.IsTagExist(rel.TagName) {
  98. commit, err := gitRepo.GetBranchCommit(rel.Target)
  99. if err != nil {
  100. return fmt.Errorf("GetBranchCommit: %v", err)
  101. }
  102. // Trim '--' prefix to prevent command line argument vulnerability.
  103. rel.TagName = strings.TrimPrefix(rel.TagName, "--")
  104. if err = gitRepo.CreateTag(rel.TagName, commit.ID.String()); err != nil {
  105. if strings.Contains(err.Error(), "is not a valid tag name") {
  106. return ErrInvalidTagName{rel.TagName}
  107. }
  108. return err
  109. }
  110. rel.LowerTagName = strings.ToLower(rel.TagName)
  111. }
  112. commit, err := gitRepo.GetTagCommit(rel.TagName)
  113. if err != nil {
  114. return fmt.Errorf("GetTagCommit: %v", err)
  115. }
  116. rel.Sha1 = commit.ID.String()
  117. rel.CreatedUnix = util.TimeStamp(commit.Author.When.Unix())
  118. rel.NumCommits, err = commit.CommitsCount()
  119. if err != nil {
  120. return fmt.Errorf("CommitsCount: %v", err)
  121. }
  122. }
  123. return nil
  124. }
  125. func addReleaseAttachments(releaseID int64, attachmentUUIDs []string) (err error) {
  126. // Check attachments
  127. var attachments = make([]*Attachment, 0)
  128. for _, uuid := range attachmentUUIDs {
  129. attach, err := getAttachmentByUUID(x, uuid)
  130. if err != nil {
  131. if IsErrAttachmentNotExist(err) {
  132. continue
  133. }
  134. return fmt.Errorf("getAttachmentByUUID [%s]: %v", uuid, err)
  135. }
  136. attachments = append(attachments, attach)
  137. }
  138. for i := range attachments {
  139. attachments[i].ReleaseID = releaseID
  140. // No assign value could be 0, so ignore AllCols().
  141. if _, err = x.ID(attachments[i].ID).Update(attachments[i]); err != nil {
  142. return fmt.Errorf("update attachment [%d]: %v", attachments[i].ID, err)
  143. }
  144. }
  145. return
  146. }
  147. // CreateRelease creates a new release of repository.
  148. func CreateRelease(gitRepo *git.Repository, rel *Release, attachmentUUIDs []string) error {
  149. isExist, err := IsReleaseExist(rel.RepoID, rel.TagName)
  150. if err != nil {
  151. return err
  152. } else if isExist {
  153. return ErrReleaseAlreadyExist{rel.TagName}
  154. }
  155. if err = createTag(gitRepo, rel); err != nil {
  156. return err
  157. }
  158. rel.LowerTagName = strings.ToLower(rel.TagName)
  159. _, err = x.InsertOne(rel)
  160. if err != nil {
  161. return err
  162. }
  163. err = addReleaseAttachments(rel.ID, attachmentUUIDs)
  164. return err
  165. }
  166. // GetRelease returns release by given ID.
  167. func GetRelease(repoID int64, tagName string) (*Release, error) {
  168. isExist, err := IsReleaseExist(repoID, tagName)
  169. if err != nil {
  170. return nil, err
  171. } else if !isExist {
  172. return nil, ErrReleaseNotExist{0, tagName}
  173. }
  174. rel := &Release{RepoID: repoID, LowerTagName: strings.ToLower(tagName)}
  175. _, err = x.Get(rel)
  176. return rel, err
  177. }
  178. // GetReleaseByID returns release with given ID.
  179. func GetReleaseByID(id int64) (*Release, error) {
  180. rel := new(Release)
  181. has, err := x.
  182. ID(id).
  183. Get(rel)
  184. if err != nil {
  185. return nil, err
  186. } else if !has {
  187. return nil, ErrReleaseNotExist{id, ""}
  188. }
  189. return rel, nil
  190. }
  191. // FindReleasesOptions describes the conditions to Find releases
  192. type FindReleasesOptions struct {
  193. IncludeDrafts bool
  194. IncludeTags bool
  195. TagNames []string
  196. }
  197. func (opts *FindReleasesOptions) toConds(repoID int64) builder.Cond {
  198. var cond = builder.NewCond()
  199. cond = cond.And(builder.Eq{"repo_id": repoID})
  200. if !opts.IncludeDrafts {
  201. cond = cond.And(builder.Eq{"is_draft": false})
  202. }
  203. if !opts.IncludeTags {
  204. cond = cond.And(builder.Eq{"is_tag": false})
  205. }
  206. if len(opts.TagNames) > 0 {
  207. cond = cond.And(builder.In("tag_name", opts.TagNames))
  208. }
  209. return cond
  210. }
  211. // GetReleasesByRepoID returns a list of releases of repository.
  212. func GetReleasesByRepoID(repoID int64, opts FindReleasesOptions, page, pageSize int) (rels []*Release, err error) {
  213. if page <= 0 {
  214. page = 1
  215. }
  216. err = x.
  217. Desc("created_unix", "id").
  218. Limit(pageSize, (page-1)*pageSize).
  219. Where(opts.toConds(repoID)).
  220. Find(&rels)
  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. if len(rels) == 0 {
  244. return
  245. }
  246. // To keep this efficient as possible sort all releases by id,
  247. // select attachments by release id,
  248. // then merge join them
  249. // Sort
  250. var sortedRels = releaseMetaSearch{ID: make([]int64, len(rels)), Rel: make([]*Release, len(rels))}
  251. var attachments []*Attachment
  252. for index, element := range rels {
  253. element.Attachments = []*Attachment{}
  254. sortedRels.ID[index] = element.ID
  255. sortedRels.Rel[index] = element
  256. }
  257. sort.Sort(sortedRels)
  258. // Select attachments
  259. err = x.
  260. Asc("release_id").
  261. In("release_id", sortedRels.ID).
  262. Find(&attachments, Attachment{})
  263. if err != nil {
  264. return err
  265. }
  266. // merge join
  267. var currentIndex = 0
  268. for _, attachment := range attachments {
  269. for sortedRels.ID[currentIndex] < attachment.ReleaseID {
  270. currentIndex++
  271. }
  272. sortedRels.Rel[currentIndex].Attachments = append(sortedRels.Rel[currentIndex].Attachments, attachment)
  273. }
  274. return
  275. }
  276. type releaseSorter struct {
  277. rels []*Release
  278. }
  279. func (rs *releaseSorter) Len() int {
  280. return len(rs.rels)
  281. }
  282. func (rs *releaseSorter) Less(i, j int) bool {
  283. diffNum := rs.rels[i].NumCommits - rs.rels[j].NumCommits
  284. if diffNum != 0 {
  285. return diffNum > 0
  286. }
  287. return rs.rels[i].CreatedUnix > rs.rels[j].CreatedUnix
  288. }
  289. func (rs *releaseSorter) Swap(i, j int) {
  290. rs.rels[i], rs.rels[j] = rs.rels[j], rs.rels[i]
  291. }
  292. // SortReleases sorts releases by number of commits and created time.
  293. func SortReleases(rels []*Release) {
  294. sorter := &releaseSorter{rels: rels}
  295. sort.Sort(sorter)
  296. }
  297. // UpdateRelease updates information of a release.
  298. func UpdateRelease(gitRepo *git.Repository, rel *Release, attachmentUUIDs []string) (err error) {
  299. if err = createTag(gitRepo, rel); err != nil {
  300. return err
  301. }
  302. rel.LowerTagName = strings.ToLower(rel.TagName)
  303. _, err = x.ID(rel.ID).AllCols().Update(rel)
  304. if err != nil {
  305. return err
  306. }
  307. err = addReleaseAttachments(rel.ID, attachmentUUIDs)
  308. return err
  309. }
  310. // DeleteReleaseByID deletes a release and corresponding Git tag by given ID.
  311. func DeleteReleaseByID(id int64, u *User, delTag bool) error {
  312. rel, err := GetReleaseByID(id)
  313. if err != nil {
  314. return fmt.Errorf("GetReleaseByID: %v", err)
  315. }
  316. repo, err := GetRepositoryByID(rel.RepoID)
  317. if err != nil {
  318. return fmt.Errorf("GetRepositoryByID: %v", err)
  319. }
  320. has, err := HasAccess(u.ID, repo, AccessModeWrite)
  321. if err != nil {
  322. return fmt.Errorf("HasAccess: %v", err)
  323. } else if !has {
  324. return fmt.Errorf("DeleteReleaseByID: permission denied")
  325. }
  326. if delTag {
  327. _, stderr, err := process.GetManager().ExecDir(-1, repo.RepoPath(),
  328. fmt.Sprintf("DeleteReleaseByID (git tag -d): %d", rel.ID),
  329. "git", "tag", "-d", rel.TagName)
  330. if err != nil && !strings.Contains(stderr, "not found") {
  331. return fmt.Errorf("git tag -d: %v - %s", err, stderr)
  332. }
  333. if _, err = x.ID(rel.ID).Delete(new(Release)); err != nil {
  334. return fmt.Errorf("Delete: %v", err)
  335. }
  336. } else {
  337. rel.IsTag = true
  338. rel.IsDraft = false
  339. rel.IsPrerelease = false
  340. rel.Title = ""
  341. rel.Note = ""
  342. if _, err = x.ID(rel.ID).AllCols().Update(rel); err != nil {
  343. return fmt.Errorf("Update: %v", err)
  344. }
  345. }
  346. return nil
  347. }
  348. // SyncReleasesWithTags synchronizes release table with repository tags
  349. func SyncReleasesWithTags(repo *Repository, gitRepo *git.Repository) error {
  350. existingRelTags := make(map[string]struct{})
  351. opts := FindReleasesOptions{IncludeDrafts: true, IncludeTags: true}
  352. for page := 1; ; page++ {
  353. rels, err := GetReleasesByRepoID(repo.ID, opts, page, 100)
  354. if err != nil {
  355. return fmt.Errorf("GetReleasesByRepoID: %v", err)
  356. }
  357. if len(rels) == 0 {
  358. break
  359. }
  360. for _, rel := range rels {
  361. if rel.IsDraft {
  362. continue
  363. }
  364. commitID, err := gitRepo.GetTagCommitID(rel.TagName)
  365. if err != nil {
  366. return fmt.Errorf("GetTagCommitID: %v", err)
  367. }
  368. if !gitRepo.IsTagExist(rel.TagName) || commitID != rel.Sha1 {
  369. if err := pushUpdateDeleteTag(repo, gitRepo, rel.TagName); err != nil {
  370. return fmt.Errorf("pushUpdateDeleteTag: %v", err)
  371. }
  372. } else {
  373. existingRelTags[strings.ToLower(rel.TagName)] = struct{}{}
  374. }
  375. }
  376. }
  377. tags, err := gitRepo.GetTags()
  378. if err != nil {
  379. return fmt.Errorf("GetTags: %v", err)
  380. }
  381. for _, tagName := range tags {
  382. if _, ok := existingRelTags[strings.ToLower(tagName)]; !ok {
  383. if err := pushUpdateAddTag(repo, gitRepo, tagName); err != nil {
  384. return fmt.Errorf("pushUpdateAddTag: %v", err)
  385. }
  386. }
  387. }
  388. return nil
  389. }