release.go 9.0 KB

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