You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

project.go 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. // Copyright 2020 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package project
  4. import (
  5. "context"
  6. "fmt"
  7. "code.gitea.io/gitea/models/db"
  8. repo_model "code.gitea.io/gitea/models/repo"
  9. user_model "code.gitea.io/gitea/models/user"
  10. "code.gitea.io/gitea/modules/log"
  11. "code.gitea.io/gitea/modules/setting"
  12. "code.gitea.io/gitea/modules/timeutil"
  13. "code.gitea.io/gitea/modules/util"
  14. "xorm.io/builder"
  15. )
  16. type (
  17. // BoardConfig is used to identify the type of board that is being created
  18. BoardConfig struct {
  19. BoardType BoardType
  20. Translation string
  21. }
  22. // CardConfig is used to identify the type of board card that is being used
  23. CardConfig struct {
  24. CardType CardType
  25. Translation string
  26. }
  27. // Type is used to identify the type of project in question and ownership
  28. Type uint8
  29. )
  30. const (
  31. // TypeIndividual is a type of project board that is owned by an individual
  32. TypeIndividual Type = iota + 1
  33. // TypeRepository is a project that is tied to a repository
  34. TypeRepository
  35. // TypeOrganization is a project that is tied to an organisation
  36. TypeOrganization
  37. )
  38. // ErrProjectNotExist represents a "ProjectNotExist" kind of error.
  39. type ErrProjectNotExist struct {
  40. ID int64
  41. RepoID int64
  42. }
  43. // IsErrProjectNotExist checks if an error is a ErrProjectNotExist
  44. func IsErrProjectNotExist(err error) bool {
  45. _, ok := err.(ErrProjectNotExist)
  46. return ok
  47. }
  48. func (err ErrProjectNotExist) Error() string {
  49. return fmt.Sprintf("projects does not exist [id: %d]", err.ID)
  50. }
  51. func (err ErrProjectNotExist) Unwrap() error {
  52. return util.ErrNotExist
  53. }
  54. // ErrProjectBoardNotExist represents a "ProjectBoardNotExist" kind of error.
  55. type ErrProjectBoardNotExist struct {
  56. BoardID int64
  57. }
  58. // IsErrProjectBoardNotExist checks if an error is a ErrProjectBoardNotExist
  59. func IsErrProjectBoardNotExist(err error) bool {
  60. _, ok := err.(ErrProjectBoardNotExist)
  61. return ok
  62. }
  63. func (err ErrProjectBoardNotExist) Error() string {
  64. return fmt.Sprintf("project board does not exist [id: %d]", err.BoardID)
  65. }
  66. func (err ErrProjectBoardNotExist) Unwrap() error {
  67. return util.ErrNotExist
  68. }
  69. // Project represents a project board
  70. type Project struct {
  71. ID int64 `xorm:"pk autoincr"`
  72. Title string `xorm:"INDEX NOT NULL"`
  73. Description string `xorm:"TEXT"`
  74. OwnerID int64 `xorm:"INDEX"`
  75. Owner *user_model.User `xorm:"-"`
  76. RepoID int64 `xorm:"INDEX"`
  77. Repo *repo_model.Repository `xorm:"-"`
  78. CreatorID int64 `xorm:"NOT NULL"`
  79. IsClosed bool `xorm:"INDEX"`
  80. BoardType BoardType
  81. CardType CardType
  82. Type Type
  83. RenderedContent string `xorm:"-"`
  84. CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  85. UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
  86. ClosedDateUnix timeutil.TimeStamp
  87. }
  88. func (p *Project) LoadOwner(ctx context.Context) (err error) {
  89. if p.Owner != nil {
  90. return nil
  91. }
  92. p.Owner, err = user_model.GetUserByID(ctx, p.OwnerID)
  93. return err
  94. }
  95. func (p *Project) LoadRepo(ctx context.Context) (err error) {
  96. if p.RepoID == 0 || p.Repo != nil {
  97. return nil
  98. }
  99. p.Repo, err = repo_model.GetRepositoryByID(ctx, p.RepoID)
  100. return err
  101. }
  102. // Link returns the project's relative URL.
  103. func (p *Project) Link(ctx context.Context) string {
  104. if p.OwnerID > 0 {
  105. err := p.LoadOwner(ctx)
  106. if err != nil {
  107. log.Error("LoadOwner: %v", err)
  108. return ""
  109. }
  110. return fmt.Sprintf("%s/-/projects/%d", p.Owner.HomeLink(), p.ID)
  111. }
  112. if p.RepoID > 0 {
  113. err := p.LoadRepo(ctx)
  114. if err != nil {
  115. log.Error("LoadRepo: %v", err)
  116. return ""
  117. }
  118. return fmt.Sprintf("%s/projects/%d", p.Repo.Link(), p.ID)
  119. }
  120. return ""
  121. }
  122. func (p *Project) IconName() string {
  123. if p.IsRepositoryProject() {
  124. return "octicon-project"
  125. }
  126. return "octicon-project-symlink"
  127. }
  128. func (p *Project) IsOrganizationProject() bool {
  129. return p.Type == TypeOrganization
  130. }
  131. func (p *Project) IsRepositoryProject() bool {
  132. return p.Type == TypeRepository
  133. }
  134. func init() {
  135. db.RegisterModel(new(Project))
  136. }
  137. // GetBoardConfig retrieves the types of configurations project boards could have
  138. func GetBoardConfig() []BoardConfig {
  139. return []BoardConfig{
  140. {BoardTypeNone, "repo.projects.type.none"},
  141. {BoardTypeBasicKanban, "repo.projects.type.basic_kanban"},
  142. {BoardTypeBugTriage, "repo.projects.type.bug_triage"},
  143. }
  144. }
  145. // GetCardConfig retrieves the types of configurations project board cards could have
  146. func GetCardConfig() []CardConfig {
  147. return []CardConfig{
  148. {CardTypeTextOnly, "repo.projects.card_type.text_only"},
  149. {CardTypeImagesAndText, "repo.projects.card_type.images_and_text"},
  150. }
  151. }
  152. // IsTypeValid checks if a project type is valid
  153. func IsTypeValid(p Type) bool {
  154. switch p {
  155. case TypeIndividual, TypeRepository, TypeOrganization:
  156. return true
  157. default:
  158. return false
  159. }
  160. }
  161. // SearchOptions are options for GetProjects
  162. type SearchOptions struct {
  163. OwnerID int64
  164. RepoID int64
  165. Page int
  166. IsClosed util.OptionalBool
  167. OrderBy db.SearchOrderBy
  168. Type Type
  169. Title string
  170. }
  171. func (opts *SearchOptions) toConds() builder.Cond {
  172. cond := builder.NewCond()
  173. if opts.RepoID > 0 {
  174. cond = cond.And(builder.Eq{"repo_id": opts.RepoID})
  175. }
  176. switch opts.IsClosed {
  177. case util.OptionalBoolTrue:
  178. cond = cond.And(builder.Eq{"is_closed": true})
  179. case util.OptionalBoolFalse:
  180. cond = cond.And(builder.Eq{"is_closed": false})
  181. }
  182. if opts.Type > 0 {
  183. cond = cond.And(builder.Eq{"type": opts.Type})
  184. }
  185. if opts.OwnerID > 0 {
  186. cond = cond.And(builder.Eq{"owner_id": opts.OwnerID})
  187. }
  188. if len(opts.Title) != 0 {
  189. cond = cond.And(db.BuildCaseInsensitiveLike("title", opts.Title))
  190. }
  191. return cond
  192. }
  193. // CountProjects counts projects
  194. func CountProjects(ctx context.Context, opts SearchOptions) (int64, error) {
  195. return db.GetEngine(ctx).Where(opts.toConds()).Count(new(Project))
  196. }
  197. func GetSearchOrderByBySortType(sortType string) db.SearchOrderBy {
  198. switch sortType {
  199. case "oldest":
  200. return db.SearchOrderByOldest
  201. case "recentupdate":
  202. return db.SearchOrderByRecentUpdated
  203. case "leastupdate":
  204. return db.SearchOrderByLeastUpdated
  205. default:
  206. return db.SearchOrderByNewest
  207. }
  208. }
  209. // FindProjects returns a list of all projects that have been created in the repository
  210. func FindProjects(ctx context.Context, opts SearchOptions) ([]*Project, int64, error) {
  211. e := db.GetEngine(ctx).Where(opts.toConds())
  212. if opts.OrderBy.String() != "" {
  213. e = e.OrderBy(opts.OrderBy.String())
  214. }
  215. projects := make([]*Project, 0, setting.UI.IssuePagingNum)
  216. if opts.Page > 0 {
  217. e = e.Limit(setting.UI.IssuePagingNum, (opts.Page-1)*setting.UI.IssuePagingNum)
  218. }
  219. count, err := e.FindAndCount(&projects)
  220. return projects, count, err
  221. }
  222. // NewProject creates a new Project
  223. func NewProject(ctx context.Context, p *Project) error {
  224. if !IsBoardTypeValid(p.BoardType) {
  225. p.BoardType = BoardTypeNone
  226. }
  227. if !IsCardTypeValid(p.CardType) {
  228. p.CardType = CardTypeTextOnly
  229. }
  230. if !IsTypeValid(p.Type) {
  231. return util.NewInvalidArgumentErrorf("project type is not valid")
  232. }
  233. ctx, committer, err := db.TxContext(ctx)
  234. if err != nil {
  235. return err
  236. }
  237. defer committer.Close()
  238. if err := db.Insert(ctx, p); err != nil {
  239. return err
  240. }
  241. if p.RepoID > 0 {
  242. if _, err := db.Exec(ctx, "UPDATE `repository` SET num_projects = num_projects + 1 WHERE id = ?", p.RepoID); err != nil {
  243. return err
  244. }
  245. }
  246. if err := createBoardsForProjectsType(ctx, p); err != nil {
  247. return err
  248. }
  249. return committer.Commit()
  250. }
  251. // GetProjectByID returns the projects in a repository
  252. func GetProjectByID(ctx context.Context, id int64) (*Project, error) {
  253. p := new(Project)
  254. has, err := db.GetEngine(ctx).ID(id).Get(p)
  255. if err != nil {
  256. return nil, err
  257. } else if !has {
  258. return nil, ErrProjectNotExist{ID: id}
  259. }
  260. return p, nil
  261. }
  262. // GetProjectForRepoByID returns the projects in a repository
  263. func GetProjectForRepoByID(ctx context.Context, repoID, id int64) (*Project, error) {
  264. p := new(Project)
  265. has, err := db.GetEngine(ctx).Where("id=? AND repo_id=?", id, repoID).Get(p)
  266. if err != nil {
  267. return nil, err
  268. } else if !has {
  269. return nil, ErrProjectNotExist{ID: id}
  270. }
  271. return p, nil
  272. }
  273. // UpdateProject updates project properties
  274. func UpdateProject(ctx context.Context, p *Project) error {
  275. if !IsCardTypeValid(p.CardType) {
  276. p.CardType = CardTypeTextOnly
  277. }
  278. _, err := db.GetEngine(ctx).ID(p.ID).Cols(
  279. "title",
  280. "description",
  281. "card_type",
  282. ).Update(p)
  283. return err
  284. }
  285. func updateRepositoryProjectCount(ctx context.Context, repoID int64) error {
  286. if _, err := db.GetEngine(ctx).Exec(builder.Update(
  287. builder.Eq{
  288. "`num_projects`": builder.Select("count(*)").From("`project`").
  289. Where(builder.Eq{"`project`.`repo_id`": repoID}.
  290. And(builder.Eq{"`project`.`type`": TypeRepository})),
  291. }).From("`repository`").Where(builder.Eq{"id": repoID})); err != nil {
  292. return err
  293. }
  294. if _, err := db.GetEngine(ctx).Exec(builder.Update(
  295. builder.Eq{
  296. "`num_closed_projects`": builder.Select("count(*)").From("`project`").
  297. Where(builder.Eq{"`project`.`repo_id`": repoID}.
  298. And(builder.Eq{"`project`.`type`": TypeRepository}).
  299. And(builder.Eq{"`project`.`is_closed`": true})),
  300. }).From("`repository`").Where(builder.Eq{"id": repoID})); err != nil {
  301. return err
  302. }
  303. return nil
  304. }
  305. // ChangeProjectStatusByRepoIDAndID toggles a project between opened and closed
  306. func ChangeProjectStatusByRepoIDAndID(ctx context.Context, repoID, projectID int64, isClosed bool) error {
  307. ctx, committer, err := db.TxContext(ctx)
  308. if err != nil {
  309. return err
  310. }
  311. defer committer.Close()
  312. p := new(Project)
  313. has, err := db.GetEngine(ctx).ID(projectID).Where("repo_id = ?", repoID).Get(p)
  314. if err != nil {
  315. return err
  316. } else if !has {
  317. return ErrProjectNotExist{ID: projectID, RepoID: repoID}
  318. }
  319. if err := changeProjectStatus(ctx, p, isClosed); err != nil {
  320. return err
  321. }
  322. return committer.Commit()
  323. }
  324. // ChangeProjectStatus toggle a project between opened and closed
  325. func ChangeProjectStatus(ctx context.Context, p *Project, isClosed bool) error {
  326. ctx, committer, err := db.TxContext(ctx)
  327. if err != nil {
  328. return err
  329. }
  330. defer committer.Close()
  331. if err := changeProjectStatus(ctx, p, isClosed); err != nil {
  332. return err
  333. }
  334. return committer.Commit()
  335. }
  336. func changeProjectStatus(ctx context.Context, p *Project, isClosed bool) error {
  337. p.IsClosed = isClosed
  338. p.ClosedDateUnix = timeutil.TimeStampNow()
  339. count, err := db.GetEngine(ctx).ID(p.ID).Where("repo_id = ? AND is_closed = ?", p.RepoID, !isClosed).Cols("is_closed", "closed_date_unix").Update(p)
  340. if err != nil {
  341. return err
  342. }
  343. if count < 1 {
  344. return nil
  345. }
  346. return updateRepositoryProjectCount(ctx, p.RepoID)
  347. }
  348. // DeleteProjectByID deletes a project from a repository. if it's not in a database
  349. // transaction, it will start a new database transaction
  350. func DeleteProjectByID(ctx context.Context, id int64) error {
  351. return db.WithTx(ctx, func(ctx context.Context) error {
  352. p, err := GetProjectByID(ctx, id)
  353. if err != nil {
  354. if IsErrProjectNotExist(err) {
  355. return nil
  356. }
  357. return err
  358. }
  359. if err := deleteProjectIssuesByProjectID(ctx, id); err != nil {
  360. return err
  361. }
  362. if err := deleteBoardByProjectID(ctx, id); err != nil {
  363. return err
  364. }
  365. if _, err = db.GetEngine(ctx).ID(p.ID).Delete(new(Project)); err != nil {
  366. return err
  367. }
  368. return updateRepositoryProjectCount(ctx, p.RepoID)
  369. })
  370. }
  371. func DeleteProjectByRepoID(ctx context.Context, repoID int64) error {
  372. switch {
  373. case setting.Database.Type.IsSQLite3():
  374. if _, err := db.GetEngine(ctx).Exec("DELETE FROM project_issue WHERE project_issue.id IN (SELECT project_issue.id FROM project_issue INNER JOIN project WHERE project.id = project_issue.project_id AND project.repo_id = ?)", repoID); err != nil {
  375. return err
  376. }
  377. if _, err := db.GetEngine(ctx).Exec("DELETE FROM project_board WHERE project_board.id IN (SELECT project_board.id FROM project_board INNER JOIN project WHERE project.id = project_board.project_id AND project.repo_id = ?)", repoID); err != nil {
  378. return err
  379. }
  380. if _, err := db.GetEngine(ctx).Table("project").Where("repo_id = ? ", repoID).Delete(&Project{}); err != nil {
  381. return err
  382. }
  383. case setting.Database.Type.IsPostgreSQL():
  384. if _, err := db.GetEngine(ctx).Exec("DELETE FROM project_issue USING project WHERE project.id = project_issue.project_id AND project.repo_id = ? ", repoID); err != nil {
  385. return err
  386. }
  387. if _, err := db.GetEngine(ctx).Exec("DELETE FROM project_board USING project WHERE project.id = project_board.project_id AND project.repo_id = ? ", repoID); err != nil {
  388. return err
  389. }
  390. if _, err := db.GetEngine(ctx).Table("project").Where("repo_id = ? ", repoID).Delete(&Project{}); err != nil {
  391. return err
  392. }
  393. default:
  394. if _, err := db.GetEngine(ctx).Exec("DELETE project_issue FROM project_issue INNER JOIN project ON project.id = project_issue.project_id WHERE project.repo_id = ? ", repoID); err != nil {
  395. return err
  396. }
  397. if _, err := db.GetEngine(ctx).Exec("DELETE project_board FROM project_board INNER JOIN project ON project.id = project_board.project_id WHERE project.repo_id = ? ", repoID); err != nil {
  398. return err
  399. }
  400. if _, err := db.GetEngine(ctx).Table("project").Where("repo_id = ? ", repoID).Delete(&Project{}); err != nil {
  401. return err
  402. }
  403. }
  404. return updateRepositoryProjectCount(ctx, repoID)
  405. }