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

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