Fork to maintain patches against the official gitea for https://code.ceondo.com https://github.com/go-gitea/gitea

release.go 12KB

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