release.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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/errutil"
  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 IsErrUserNotExist(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. var _ errutil.NotFound = (*ErrReleaseNotExist)(nil)
  180. type ErrReleaseNotExist struct {
  181. args map[string]interface{}
  182. }
  183. func IsErrReleaseNotExist(err error) bool {
  184. _, ok := err.(ErrReleaseNotExist)
  185. return ok
  186. }
  187. func (err ErrReleaseNotExist) Error() string {
  188. return fmt.Sprintf("release does not exist: %v", err.args)
  189. }
  190. func (ErrReleaseNotExist) NotFound() bool {
  191. return true
  192. }
  193. // GetRelease returns release by given ID.
  194. func GetRelease(repoID int64, tagName string) (*Release, error) {
  195. isExist, err := IsReleaseExist(repoID, tagName)
  196. if err != nil {
  197. return nil, err
  198. } else if !isExist {
  199. return nil, ErrReleaseNotExist{args: map[string]interface{}{"tag": tagName}}
  200. }
  201. r := &Release{RepoID: repoID, LowerTagName: strings.ToLower(tagName)}
  202. if _, err = x.Get(r); err != nil {
  203. return nil, fmt.Errorf("Get: %v", err)
  204. }
  205. return r, r.LoadAttributes()
  206. }
  207. // GetReleaseByID returns release with given ID.
  208. func GetReleaseByID(id int64) (*Release, error) {
  209. r := new(Release)
  210. has, err := x.Id(id).Get(r)
  211. if err != nil {
  212. return nil, err
  213. } else if !has {
  214. return nil, ErrReleaseNotExist{args: map[string]interface{}{"releaseID": id}}
  215. }
  216. return r, r.LoadAttributes()
  217. }
  218. // GetPublishedReleasesByRepoID returns a list of published releases of repository.
  219. // If matches is not empty, only published releases in matches will be returned.
  220. // In any case, drafts won't be returned by this function.
  221. func GetPublishedReleasesByRepoID(repoID int64, matches ...string) ([]*Release, error) {
  222. sess := x.Where("repo_id = ?", repoID).And("is_draft = ?", false).Desc("created_unix")
  223. if len(matches) > 0 {
  224. sess.In("tag_name", matches)
  225. }
  226. releases := make([]*Release, 0, 5)
  227. return releases, sess.Find(&releases, new(Release))
  228. }
  229. // GetReleasesByRepoID returns a list of all releases (including drafts) of given repository.
  230. func GetReleasesByRepoID(repoID int64) ([]*Release, error) {
  231. releases := make([]*Release, 0)
  232. return releases, x.Where("repo_id = ?", repoID).Find(&releases)
  233. }
  234. // GetDraftReleasesByRepoID returns all draft releases of repository.
  235. func GetDraftReleasesByRepoID(repoID int64) ([]*Release, error) {
  236. releases := make([]*Release, 0)
  237. return releases, x.Where("repo_id = ?", repoID).And("is_draft = ?", true).Find(&releases)
  238. }
  239. type ReleaseSorter struct {
  240. releases []*Release
  241. }
  242. func (rs *ReleaseSorter) Len() int {
  243. return len(rs.releases)
  244. }
  245. func (rs *ReleaseSorter) Less(i, j int) bool {
  246. diffNum := rs.releases[i].NumCommits - rs.releases[j].NumCommits
  247. if diffNum != 0 {
  248. return diffNum > 0
  249. }
  250. return rs.releases[i].Created.After(rs.releases[j].Created)
  251. }
  252. func (rs *ReleaseSorter) Swap(i, j int) {
  253. rs.releases[i], rs.releases[j] = rs.releases[j], rs.releases[i]
  254. }
  255. // SortReleases sorts releases by number of commits and created time.
  256. func SortReleases(rels []*Release) {
  257. sorter := &ReleaseSorter{releases: rels}
  258. sort.Sort(sorter)
  259. }
  260. // UpdateRelease updates information of a release.
  261. func UpdateRelease(doer *User, gitRepo *git.Repository, r *Release, isPublish bool, uuids []string) (err error) {
  262. if err = createTag(gitRepo, r); err != nil {
  263. return fmt.Errorf("createTag: %v", err)
  264. }
  265. r.PublisherID = doer.ID
  266. sess := x.NewSession()
  267. defer sess.Close()
  268. if err = sess.Begin(); err != nil {
  269. return err
  270. }
  271. if _, err = sess.ID(r.ID).AllCols().Update(r); err != nil {
  272. return fmt.Errorf("Update: %v", err)
  273. }
  274. // Unlink all current attachments and link back later if still valid
  275. if _, err = sess.Exec("UPDATE attachment SET release_id = 0 WHERE release_id = ?", r.ID); err != nil {
  276. return fmt.Errorf("unlink current attachments: %v", err)
  277. }
  278. if len(uuids) > 0 {
  279. if _, err = sess.In("uuid", uuids).Cols("release_id").Update(&Attachment{ReleaseID: r.ID}); err != nil {
  280. return fmt.Errorf("link attachments: %v", err)
  281. }
  282. }
  283. if err = sess.Commit(); err != nil {
  284. return fmt.Errorf("Commit: %v", err)
  285. }
  286. if !isPublish {
  287. return nil
  288. }
  289. r.Publisher = doer
  290. r.preparePublishWebhooks()
  291. return nil
  292. }
  293. // DeleteReleaseOfRepoByID deletes a release and corresponding Git tag by given ID.
  294. func DeleteReleaseOfRepoByID(repoID, id int64) error {
  295. rel, err := GetReleaseByID(id)
  296. if err != nil {
  297. return fmt.Errorf("GetReleaseByID: %v", err)
  298. }
  299. // Mark sure the delete operation againsts same repository.
  300. if repoID != rel.RepoID {
  301. return nil
  302. }
  303. repo, err := GetRepositoryByID(rel.RepoID)
  304. if err != nil {
  305. return fmt.Errorf("GetRepositoryByID: %v", err)
  306. }
  307. _, stderr, err := process.ExecDir(-1, repo.RepoPath(),
  308. fmt.Sprintf("DeleteReleaseByID (git tag -d): %d", rel.ID),
  309. "git", "tag", "-d", rel.TagName)
  310. if err != nil && !strings.Contains(stderr, "not found") {
  311. return fmt.Errorf("git tag -d: %v - %s", err, stderr)
  312. }
  313. if _, err = x.Id(rel.ID).Delete(new(Release)); err != nil {
  314. return fmt.Errorf("Delete: %v", err)
  315. }
  316. return nil
  317. }