release.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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. "github.com/go-xorm/xorm"
  11. log "gopkg.in/clog.v1"
  12. "github.com/gogits/git-module"
  13. api "github.com/gogits/go-gogs-client"
  14. "github.com/gogits/gogs/modules/process"
  15. )
  16. // Release represents a release of repository.
  17. type Release struct {
  18. ID int64 `xorm:"pk autoincr"`
  19. RepoID int64
  20. Repo *Repository `xorm:"-"`
  21. PublisherID int64
  22. Publisher *User `xorm:"-"`
  23. TagName string
  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. Created time.Time `xorm:"-"`
  34. CreatedUnix int64
  35. }
  36. func (r *Release) BeforeInsert() {
  37. if r.CreatedUnix == 0 {
  38. r.CreatedUnix = time.Now().Unix()
  39. }
  40. }
  41. func (r *Release) AfterSet(colName string, _ xorm.Cell) {
  42. switch colName {
  43. case "created_unix":
  44. r.Created = time.Unix(r.CreatedUnix, 0).Local()
  45. }
  46. }
  47. func (r *Release) loadAttributes(e Engine) (err error) {
  48. if r.Repo == nil {
  49. r.Repo, err = getRepositoryByID(e, r.RepoID)
  50. if err != nil {
  51. return fmt.Errorf("getRepositoryByID [repo_id: %d]: %v", r.RepoID, err)
  52. }
  53. }
  54. if r.Publisher == nil {
  55. r.Publisher, err = getUserByID(e, r.PublisherID)
  56. if err != nil {
  57. if IsErrUserNotExist(err) {
  58. r.PublisherID = -1
  59. r.Publisher = NewGhostUser()
  60. } else {
  61. return fmt.Errorf("getUserByID.(Publisher) [publisher_id: %d]: %v", r.PublisherID, err)
  62. }
  63. }
  64. }
  65. return nil
  66. }
  67. func (r *Release) LoadAttributes() error {
  68. return r.loadAttributes(x)
  69. }
  70. // This method assumes some fields assigned with values:
  71. // Required - Publisher
  72. func (r *Release) APIFormat() *api.Release {
  73. return &api.Release{
  74. ID: r.ID,
  75. TagName: r.TagName,
  76. TargetCommitish: r.Target,
  77. Name: r.Title,
  78. Body: r.Note,
  79. Draft: r.IsDraft,
  80. Prerelease: r.IsPrerelease,
  81. Author: r.Publisher.APIFormat(),
  82. Created: r.Created,
  83. }
  84. }
  85. // IsReleaseExist returns true if release with given tag name already exists.
  86. func IsReleaseExist(repoID int64, tagName string) (bool, error) {
  87. if len(tagName) == 0 {
  88. return false, nil
  89. }
  90. return x.Get(&Release{RepoID: repoID, LowerTagName: strings.ToLower(tagName)})
  91. }
  92. func createTag(gitRepo *git.Repository, r *Release) error {
  93. // Only actual create when publish.
  94. if !r.IsDraft {
  95. if !gitRepo.IsTagExist(r.TagName) {
  96. commit, err := gitRepo.GetBranchCommit(r.Target)
  97. if err != nil {
  98. return fmt.Errorf("GetBranchCommit: %v", err)
  99. }
  100. // Trim '--' prefix to prevent command line argument vulnerability.
  101. r.TagName = strings.TrimPrefix(r.TagName, "--")
  102. if err = gitRepo.CreateTag(r.TagName, commit.ID.String()); err != nil {
  103. if strings.Contains(err.Error(), "is not a valid tag name") {
  104. return ErrInvalidTagName{r.TagName}
  105. }
  106. return err
  107. }
  108. } else {
  109. commit, err := gitRepo.GetTagCommit(r.TagName)
  110. if err != nil {
  111. return fmt.Errorf("GetTagCommit: %v", err)
  112. }
  113. r.Sha1 = commit.ID.String()
  114. r.NumCommits, err = commit.CommitsCount()
  115. if err != nil {
  116. return fmt.Errorf("CommitsCount: %v", err)
  117. }
  118. }
  119. }
  120. return nil
  121. }
  122. func (r *Release) preparePublishWebhooks() {
  123. if err := PrepareWebhooks(r.Repo, HOOK_EVENT_RELEASE, &api.ReleasePayload{
  124. Action: api.HOOK_RELEASE_PUBLISHED,
  125. Release: r.APIFormat(),
  126. Repository: r.Repo.APIFormat(nil),
  127. Sender: r.Publisher.APIFormat(),
  128. }); err != nil {
  129. log.Error(2, "PrepareWebhooks: %v", err)
  130. }
  131. }
  132. // CreateRelease creates a new release of repository.
  133. func CreateRelease(gitRepo *git.Repository, r *Release) error {
  134. isExist, err := IsReleaseExist(r.RepoID, r.TagName)
  135. if err != nil {
  136. return err
  137. } else if isExist {
  138. return ErrReleaseAlreadyExist{r.TagName}
  139. }
  140. if err = createTag(gitRepo, r); err != nil {
  141. return err
  142. }
  143. r.LowerTagName = strings.ToLower(r.TagName)
  144. if _, err = x.Insert(r); err != nil {
  145. return fmt.Errorf("Insert: %v", err)
  146. }
  147. // Only send webhook when actually published, skip drafts
  148. if r.IsDraft {
  149. return nil
  150. }
  151. r, err = GetReleaseByID(r.ID)
  152. if err != nil {
  153. return fmt.Errorf("GetReleaseByID: %v", err)
  154. }
  155. r.preparePublishWebhooks()
  156. return nil
  157. }
  158. // GetRelease returns release by given ID.
  159. func GetRelease(repoID int64, tagName string) (*Release, error) {
  160. isExist, err := IsReleaseExist(repoID, tagName)
  161. if err != nil {
  162. return nil, err
  163. } else if !isExist {
  164. return nil, ErrReleaseNotExist{0, tagName}
  165. }
  166. r := &Release{RepoID: repoID, LowerTagName: strings.ToLower(tagName)}
  167. if _, err = x.Get(r); err != nil {
  168. return nil, fmt.Errorf("Get: %v", err)
  169. }
  170. return r, r.LoadAttributes()
  171. }
  172. // GetReleaseByID returns release with given ID.
  173. func GetReleaseByID(id int64) (*Release, error) {
  174. r := new(Release)
  175. has, err := x.Id(id).Get(r)
  176. if err != nil {
  177. return nil, err
  178. } else if !has {
  179. return nil, ErrReleaseNotExist{id, ""}
  180. }
  181. return r, r.LoadAttributes()
  182. }
  183. // GetPublishedReleasesByRepoID returns a list of published releases of repository.
  184. // If matches is not empty, only published releases in matches will be returned.
  185. // In any case, drafts won't be returned by this function.
  186. func GetPublishedReleasesByRepoID(repoID int64, matches ...string) ([]*Release, error) {
  187. sess := x.Where("repo_id = ?", repoID).And("is_draft = ?", false).Desc("created_unix")
  188. if len(matches) > 0 {
  189. sess.In("tag_name", matches)
  190. }
  191. releases := make([]*Release, 0, 5)
  192. return releases, sess.Find(&releases, new(Release))
  193. }
  194. // GetDraftReleasesByRepoID returns all draft releases of repository.
  195. func GetDraftReleasesByRepoID(repoID int64) ([]*Release, error) {
  196. releases := make([]*Release, 0)
  197. return releases, x.Where("repo_id = ?", repoID).And("is_draft = ?", true).Find(&releases)
  198. }
  199. type ReleaseSorter struct {
  200. releases []*Release
  201. }
  202. func (rs *ReleaseSorter) Len() int {
  203. return len(rs.releases)
  204. }
  205. func (rs *ReleaseSorter) Less(i, j int) bool {
  206. diffNum := rs.releases[i].NumCommits - rs.releases[j].NumCommits
  207. if diffNum != 0 {
  208. return diffNum > 0
  209. }
  210. return rs.releases[i].Created.After(rs.releases[j].Created)
  211. }
  212. func (rs *ReleaseSorter) Swap(i, j int) {
  213. rs.releases[i], rs.releases[j] = rs.releases[j], rs.releases[i]
  214. }
  215. // SortReleases sorts releases by number of commits and created time.
  216. func SortReleases(rels []*Release) {
  217. sorter := &ReleaseSorter{releases: rels}
  218. sort.Sort(sorter)
  219. }
  220. // UpdateRelease updates information of a release.
  221. func UpdateRelease(doer *User, gitRepo *git.Repository, r *Release, isPublish bool) (err error) {
  222. if err = createTag(gitRepo, r); err != nil {
  223. return fmt.Errorf("createTag: %v", err)
  224. }
  225. r.PublisherID = doer.ID
  226. if _, err = x.Id(r.ID).AllCols().Update(r); err != nil {
  227. return err
  228. }
  229. if !isPublish {
  230. return nil
  231. }
  232. r.Publisher = doer
  233. r.preparePublishWebhooks()
  234. return nil
  235. }
  236. // DeleteReleaseOfRepoByID deletes a release and corresponding Git tag by given ID.
  237. func DeleteReleaseOfRepoByID(repoID, id int64) error {
  238. rel, err := GetReleaseByID(id)
  239. if err != nil {
  240. return fmt.Errorf("GetReleaseByID: %v", err)
  241. }
  242. // Mark sure the delete operation againsts same repository.
  243. if repoID != rel.RepoID {
  244. return nil
  245. }
  246. repo, err := GetRepositoryByID(rel.RepoID)
  247. if err != nil {
  248. return fmt.Errorf("GetRepositoryByID: %v", err)
  249. }
  250. _, stderr, err := process.ExecDir(-1, repo.RepoPath(),
  251. fmt.Sprintf("DeleteReleaseByID (git tag -d): %d", rel.ID),
  252. "git", "tag", "-d", rel.TagName)
  253. if err != nil && !strings.Contains(stderr, "not found") {
  254. return fmt.Errorf("git tag -d: %v - %s", err, stderr)
  255. }
  256. if _, err = x.Id(rel.ID).Delete(new(Release)); err != nil {
  257. return fmt.Errorf("Delete: %v", err)
  258. }
  259. return nil
  260. }