release.go 9.0 KB

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