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 12KB

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