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.

convert.go 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Copyright 2018 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package convert
  6. import (
  7. "fmt"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "code.gitea.io/gitea/models"
  12. "code.gitea.io/gitea/models/login"
  13. "code.gitea.io/gitea/modules/git"
  14. "code.gitea.io/gitea/modules/log"
  15. "code.gitea.io/gitea/modules/structs"
  16. api "code.gitea.io/gitea/modules/structs"
  17. "code.gitea.io/gitea/modules/util"
  18. "code.gitea.io/gitea/services/webhook"
  19. )
  20. // ToEmail convert models.EmailAddress to api.Email
  21. func ToEmail(email *models.EmailAddress) *api.Email {
  22. return &api.Email{
  23. Email: email.Email,
  24. Verified: email.IsActivated,
  25. Primary: email.IsPrimary,
  26. }
  27. }
  28. // ToBranch convert a git.Commit and git.Branch to an api.Branch
  29. func ToBranch(repo *models.Repository, b *git.Branch, c *git.Commit, bp *models.ProtectedBranch, user *models.User, isRepoAdmin bool) (*api.Branch, error) {
  30. if bp == nil {
  31. var hasPerm bool
  32. var err error
  33. if user != nil {
  34. hasPerm, err = models.HasAccessUnit(user, repo, models.UnitTypeCode, models.AccessModeWrite)
  35. if err != nil {
  36. return nil, err
  37. }
  38. }
  39. return &api.Branch{
  40. Name: b.Name,
  41. Commit: ToPayloadCommit(repo, c),
  42. Protected: false,
  43. RequiredApprovals: 0,
  44. EnableStatusCheck: false,
  45. StatusCheckContexts: []string{},
  46. UserCanPush: hasPerm,
  47. UserCanMerge: hasPerm,
  48. }, nil
  49. }
  50. branch := &api.Branch{
  51. Name: b.Name,
  52. Commit: ToPayloadCommit(repo, c),
  53. Protected: true,
  54. RequiredApprovals: bp.RequiredApprovals,
  55. EnableStatusCheck: bp.EnableStatusCheck,
  56. StatusCheckContexts: bp.StatusCheckContexts,
  57. }
  58. if isRepoAdmin {
  59. branch.EffectiveBranchProtectionName = bp.BranchName
  60. }
  61. if user != nil {
  62. permission, err := models.GetUserRepoPermission(repo, user)
  63. if err != nil {
  64. return nil, err
  65. }
  66. branch.UserCanPush = bp.CanUserPush(user.ID)
  67. branch.UserCanMerge = bp.IsUserMergeWhitelisted(user.ID, permission)
  68. }
  69. return branch, nil
  70. }
  71. // ToBranchProtection convert a ProtectedBranch to api.BranchProtection
  72. func ToBranchProtection(bp *models.ProtectedBranch) *api.BranchProtection {
  73. pushWhitelistUsernames, err := models.GetUserNamesByIDs(bp.WhitelistUserIDs)
  74. if err != nil {
  75. log.Error("GetUserNamesByIDs (WhitelistUserIDs): %v", err)
  76. }
  77. mergeWhitelistUsernames, err := models.GetUserNamesByIDs(bp.MergeWhitelistUserIDs)
  78. if err != nil {
  79. log.Error("GetUserNamesByIDs (MergeWhitelistUserIDs): %v", err)
  80. }
  81. approvalsWhitelistUsernames, err := models.GetUserNamesByIDs(bp.ApprovalsWhitelistUserIDs)
  82. if err != nil {
  83. log.Error("GetUserNamesByIDs (ApprovalsWhitelistUserIDs): %v", err)
  84. }
  85. pushWhitelistTeams, err := models.GetTeamNamesByID(bp.WhitelistTeamIDs)
  86. if err != nil {
  87. log.Error("GetTeamNamesByID (WhitelistTeamIDs): %v", err)
  88. }
  89. mergeWhitelistTeams, err := models.GetTeamNamesByID(bp.MergeWhitelistTeamIDs)
  90. if err != nil {
  91. log.Error("GetTeamNamesByID (MergeWhitelistTeamIDs): %v", err)
  92. }
  93. approvalsWhitelistTeams, err := models.GetTeamNamesByID(bp.ApprovalsWhitelistTeamIDs)
  94. if err != nil {
  95. log.Error("GetTeamNamesByID (ApprovalsWhitelistTeamIDs): %v", err)
  96. }
  97. return &api.BranchProtection{
  98. BranchName: bp.BranchName,
  99. EnablePush: bp.CanPush,
  100. EnablePushWhitelist: bp.EnableWhitelist,
  101. PushWhitelistUsernames: pushWhitelistUsernames,
  102. PushWhitelistTeams: pushWhitelistTeams,
  103. PushWhitelistDeployKeys: bp.WhitelistDeployKeys,
  104. EnableMergeWhitelist: bp.EnableMergeWhitelist,
  105. MergeWhitelistUsernames: mergeWhitelistUsernames,
  106. MergeWhitelistTeams: mergeWhitelistTeams,
  107. EnableStatusCheck: bp.EnableStatusCheck,
  108. StatusCheckContexts: bp.StatusCheckContexts,
  109. RequiredApprovals: bp.RequiredApprovals,
  110. EnableApprovalsWhitelist: bp.EnableApprovalsWhitelist,
  111. ApprovalsWhitelistUsernames: approvalsWhitelistUsernames,
  112. ApprovalsWhitelistTeams: approvalsWhitelistTeams,
  113. BlockOnRejectedReviews: bp.BlockOnRejectedReviews,
  114. BlockOnOfficialReviewRequests: bp.BlockOnOfficialReviewRequests,
  115. BlockOnOutdatedBranch: bp.BlockOnOutdatedBranch,
  116. DismissStaleApprovals: bp.DismissStaleApprovals,
  117. RequireSignedCommits: bp.RequireSignedCommits,
  118. ProtectedFilePatterns: bp.ProtectedFilePatterns,
  119. UnprotectedFilePatterns: bp.UnprotectedFilePatterns,
  120. Created: bp.CreatedUnix.AsTime(),
  121. Updated: bp.UpdatedUnix.AsTime(),
  122. }
  123. }
  124. // ToTag convert a git.Tag to an api.Tag
  125. func ToTag(repo *models.Repository, t *git.Tag) *api.Tag {
  126. return &api.Tag{
  127. Name: t.Name,
  128. Message: strings.TrimSpace(t.Message),
  129. ID: t.ID.String(),
  130. Commit: ToCommitMeta(repo, t),
  131. ZipballURL: util.URLJoin(repo.HTMLURL(), "archive", t.Name+".zip"),
  132. TarballURL: util.URLJoin(repo.HTMLURL(), "archive", t.Name+".tar.gz"),
  133. }
  134. }
  135. // ToVerification convert a git.Commit.Signature to an api.PayloadCommitVerification
  136. func ToVerification(c *git.Commit) *api.PayloadCommitVerification {
  137. verif := models.ParseCommitWithSignature(c)
  138. commitVerification := &api.PayloadCommitVerification{
  139. Verified: verif.Verified,
  140. Reason: verif.Reason,
  141. }
  142. if c.Signature != nil {
  143. commitVerification.Signature = c.Signature.Signature
  144. commitVerification.Payload = c.Signature.Payload
  145. }
  146. if verif.SigningUser != nil {
  147. commitVerification.Signer = &structs.PayloadUser{
  148. Name: verif.SigningUser.Name,
  149. Email: verif.SigningUser.Email,
  150. }
  151. }
  152. return commitVerification
  153. }
  154. // ToPublicKey convert models.PublicKey to api.PublicKey
  155. func ToPublicKey(apiLink string, key *models.PublicKey) *api.PublicKey {
  156. return &api.PublicKey{
  157. ID: key.ID,
  158. Key: key.Content,
  159. URL: fmt.Sprintf("%s%d", apiLink, key.ID),
  160. Title: key.Name,
  161. Fingerprint: key.Fingerprint,
  162. Created: key.CreatedUnix.AsTime(),
  163. }
  164. }
  165. // ToGPGKey converts models.GPGKey to api.GPGKey
  166. func ToGPGKey(key *models.GPGKey) *api.GPGKey {
  167. subkeys := make([]*api.GPGKey, len(key.SubsKey))
  168. for id, k := range key.SubsKey {
  169. subkeys[id] = &api.GPGKey{
  170. ID: k.ID,
  171. PrimaryKeyID: k.PrimaryKeyID,
  172. KeyID: k.KeyID,
  173. PublicKey: k.Content,
  174. Created: k.CreatedUnix.AsTime(),
  175. Expires: k.ExpiredUnix.AsTime(),
  176. CanSign: k.CanSign,
  177. CanEncryptComms: k.CanEncryptComms,
  178. CanEncryptStorage: k.CanEncryptStorage,
  179. CanCertify: k.CanSign,
  180. Verified: k.Verified,
  181. }
  182. }
  183. emails := make([]*api.GPGKeyEmail, len(key.Emails))
  184. for i, e := range key.Emails {
  185. emails[i] = ToGPGKeyEmail(e)
  186. }
  187. return &api.GPGKey{
  188. ID: key.ID,
  189. PrimaryKeyID: key.PrimaryKeyID,
  190. KeyID: key.KeyID,
  191. PublicKey: key.Content,
  192. Created: key.CreatedUnix.AsTime(),
  193. Expires: key.ExpiredUnix.AsTime(),
  194. Emails: emails,
  195. SubsKey: subkeys,
  196. CanSign: key.CanSign,
  197. CanEncryptComms: key.CanEncryptComms,
  198. CanEncryptStorage: key.CanEncryptStorage,
  199. CanCertify: key.CanSign,
  200. Verified: key.Verified,
  201. }
  202. }
  203. // ToGPGKeyEmail convert models.EmailAddress to api.GPGKeyEmail
  204. func ToGPGKeyEmail(email *models.EmailAddress) *api.GPGKeyEmail {
  205. return &api.GPGKeyEmail{
  206. Email: email.Email,
  207. Verified: email.IsActivated,
  208. }
  209. }
  210. // ToHook convert models.Webhook to api.Hook
  211. func ToHook(repoLink string, w *models.Webhook) *api.Hook {
  212. config := map[string]string{
  213. "url": w.URL,
  214. "content_type": w.ContentType.Name(),
  215. }
  216. if w.Type == models.SLACK {
  217. s := webhook.GetSlackHook(w)
  218. config["channel"] = s.Channel
  219. config["username"] = s.Username
  220. config["icon_url"] = s.IconURL
  221. config["color"] = s.Color
  222. }
  223. return &api.Hook{
  224. ID: w.ID,
  225. Type: string(w.Type),
  226. URL: fmt.Sprintf("%s/settings/hooks/%d", repoLink, w.ID),
  227. Active: w.IsActive,
  228. Config: config,
  229. Events: w.EventsArray(),
  230. Updated: w.UpdatedUnix.AsTime(),
  231. Created: w.CreatedUnix.AsTime(),
  232. }
  233. }
  234. // ToGitHook convert git.Hook to api.GitHook
  235. func ToGitHook(h *git.Hook) *api.GitHook {
  236. return &api.GitHook{
  237. Name: h.Name(),
  238. IsActive: h.IsActive,
  239. Content: h.Content,
  240. }
  241. }
  242. // ToDeployKey convert models.DeployKey to api.DeployKey
  243. func ToDeployKey(apiLink string, key *models.DeployKey) *api.DeployKey {
  244. return &api.DeployKey{
  245. ID: key.ID,
  246. KeyID: key.KeyID,
  247. Key: key.Content,
  248. Fingerprint: key.Fingerprint,
  249. URL: fmt.Sprintf("%s%d", apiLink, key.ID),
  250. Title: key.Name,
  251. Created: key.CreatedUnix.AsTime(),
  252. ReadOnly: key.Mode == models.AccessModeRead, // All deploy keys are read-only.
  253. }
  254. }
  255. // ToOrganization convert models.User to api.Organization
  256. func ToOrganization(org *models.User) *api.Organization {
  257. return &api.Organization{
  258. ID: org.ID,
  259. AvatarURL: org.AvatarLink(),
  260. UserName: org.Name,
  261. FullName: org.FullName,
  262. Description: org.Description,
  263. Website: org.Website,
  264. Location: org.Location,
  265. Visibility: org.Visibility.String(),
  266. RepoAdminChangeTeamAccess: org.RepoAdminChangeTeamAccess,
  267. }
  268. }
  269. // ToTeam convert models.Team to api.Team
  270. func ToTeam(team *models.Team) *api.Team {
  271. if team == nil {
  272. return nil
  273. }
  274. return &api.Team{
  275. ID: team.ID,
  276. Name: team.Name,
  277. Description: team.Description,
  278. IncludesAllRepositories: team.IncludesAllRepositories,
  279. CanCreateOrgRepo: team.CanCreateOrgRepo,
  280. Permission: team.Authorize.String(),
  281. Units: team.GetUnitNames(),
  282. }
  283. }
  284. // ToAnnotatedTag convert git.Tag to api.AnnotatedTag
  285. func ToAnnotatedTag(repo *models.Repository, t *git.Tag, c *git.Commit) *api.AnnotatedTag {
  286. return &api.AnnotatedTag{
  287. Tag: t.Name,
  288. SHA: t.ID.String(),
  289. Object: ToAnnotatedTagObject(repo, c),
  290. Message: t.Message,
  291. URL: util.URLJoin(repo.APIURL(), "git/tags", t.ID.String()),
  292. Tagger: ToCommitUser(t.Tagger),
  293. Verification: ToVerification(c),
  294. }
  295. }
  296. // ToAnnotatedTagObject convert a git.Commit to an api.AnnotatedTagObject
  297. func ToAnnotatedTagObject(repo *models.Repository, commit *git.Commit) *api.AnnotatedTagObject {
  298. return &api.AnnotatedTagObject{
  299. SHA: commit.ID.String(),
  300. Type: string(git.ObjectCommit),
  301. URL: util.URLJoin(repo.APIURL(), "git/commits", commit.ID.String()),
  302. }
  303. }
  304. // ToTopicResponse convert from models.Topic to api.TopicResponse
  305. func ToTopicResponse(topic *models.Topic) *api.TopicResponse {
  306. return &api.TopicResponse{
  307. ID: topic.ID,
  308. Name: topic.Name,
  309. RepoCount: topic.RepoCount,
  310. Created: topic.CreatedUnix.AsTime(),
  311. Updated: topic.UpdatedUnix.AsTime(),
  312. }
  313. }
  314. // ToOAuth2Application convert from login.OAuth2Application to api.OAuth2Application
  315. func ToOAuth2Application(app *login.OAuth2Application) *api.OAuth2Application {
  316. return &api.OAuth2Application{
  317. ID: app.ID,
  318. Name: app.Name,
  319. ClientID: app.ClientID,
  320. ClientSecret: app.ClientSecret,
  321. RedirectURIs: app.RedirectURIs,
  322. Created: app.CreatedUnix.AsTime(),
  323. }
  324. }
  325. // ToLFSLock convert a LFSLock to api.LFSLock
  326. func ToLFSLock(l *models.LFSLock) *api.LFSLock {
  327. return &api.LFSLock{
  328. ID: strconv.FormatInt(l.ID, 10),
  329. Path: l.Path,
  330. LockedAt: l.Created.Round(time.Second),
  331. Owner: &api.LFSLockOwner{
  332. Name: l.Owner.DisplayName(),
  333. },
  334. }
  335. }