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

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