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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Copyright 2018 The Gitea Authors. All rights reserved.
  3. // SPDX-License-Identifier: MIT
  4. package convert
  5. import (
  6. "context"
  7. "fmt"
  8. "strconv"
  9. "strings"
  10. "time"
  11. asymkey_model "code.gitea.io/gitea/models/asymkey"
  12. "code.gitea.io/gitea/models/auth"
  13. git_model "code.gitea.io/gitea/models/git"
  14. issues_model "code.gitea.io/gitea/models/issues"
  15. "code.gitea.io/gitea/models/organization"
  16. "code.gitea.io/gitea/models/perm"
  17. access_model "code.gitea.io/gitea/models/perm/access"
  18. repo_model "code.gitea.io/gitea/models/repo"
  19. "code.gitea.io/gitea/models/unit"
  20. user_model "code.gitea.io/gitea/models/user"
  21. "code.gitea.io/gitea/modules/git"
  22. "code.gitea.io/gitea/modules/log"
  23. api "code.gitea.io/gitea/modules/structs"
  24. "code.gitea.io/gitea/modules/util"
  25. "code.gitea.io/gitea/services/gitdiff"
  26. )
  27. // ToEmail convert models.EmailAddress to api.Email
  28. func ToEmail(email *user_model.EmailAddress) *api.Email {
  29. return &api.Email{
  30. Email: email.Email,
  31. Verified: email.IsActivated,
  32. Primary: email.IsPrimary,
  33. }
  34. }
  35. // ToEmail convert models.EmailAddress to api.Email
  36. func ToEmailSearch(email *user_model.SearchEmailResult) *api.Email {
  37. return &api.Email{
  38. Email: email.Email,
  39. Verified: email.IsActivated,
  40. Primary: email.IsPrimary,
  41. UserID: email.UID,
  42. UserName: email.Name,
  43. }
  44. }
  45. // ToBranch convert a git.Commit and git.Branch to an api.Branch
  46. func ToBranch(ctx context.Context, repo *repo_model.Repository, branchName string, c *git.Commit, bp *git_model.ProtectedBranch, user *user_model.User, isRepoAdmin bool) (*api.Branch, error) {
  47. if bp == nil {
  48. var hasPerm bool
  49. var canPush bool
  50. var err error
  51. if user != nil {
  52. hasPerm, err = access_model.HasAccessUnit(ctx, user, repo, unit.TypeCode, perm.AccessModeWrite)
  53. if err != nil {
  54. return nil, err
  55. }
  56. perms, err := access_model.GetUserRepoPermission(ctx, repo, user)
  57. if err != nil {
  58. return nil, err
  59. }
  60. canPush = issues_model.CanMaintainerWriteToBranch(ctx, perms, branchName, user)
  61. }
  62. return &api.Branch{
  63. Name: branchName,
  64. Commit: ToPayloadCommit(ctx, repo, c),
  65. Protected: false,
  66. RequiredApprovals: 0,
  67. EnableStatusCheck: false,
  68. StatusCheckContexts: []string{},
  69. UserCanPush: canPush,
  70. UserCanMerge: hasPerm,
  71. }, nil
  72. }
  73. branch := &api.Branch{
  74. Name: branchName,
  75. Commit: ToPayloadCommit(ctx, repo, c),
  76. Protected: true,
  77. RequiredApprovals: bp.RequiredApprovals,
  78. EnableStatusCheck: bp.EnableStatusCheck,
  79. StatusCheckContexts: bp.StatusCheckContexts,
  80. }
  81. if isRepoAdmin {
  82. branch.EffectiveBranchProtectionName = bp.RuleName
  83. }
  84. if user != nil {
  85. permission, err := access_model.GetUserRepoPermission(ctx, repo, user)
  86. if err != nil {
  87. return nil, err
  88. }
  89. bp.Repo = repo
  90. branch.UserCanPush = bp.CanUserPush(ctx, user)
  91. branch.UserCanMerge = git_model.IsUserMergeWhitelisted(ctx, bp, user.ID, permission)
  92. }
  93. return branch, nil
  94. }
  95. // ToBranchProtection convert a ProtectedBranch to api.BranchProtection
  96. func ToBranchProtection(ctx context.Context, bp *git_model.ProtectedBranch) *api.BranchProtection {
  97. pushWhitelistUsernames, err := user_model.GetUserNamesByIDs(ctx, bp.WhitelistUserIDs)
  98. if err != nil {
  99. log.Error("GetUserNamesByIDs (WhitelistUserIDs): %v", err)
  100. }
  101. mergeWhitelistUsernames, err := user_model.GetUserNamesByIDs(ctx, bp.MergeWhitelistUserIDs)
  102. if err != nil {
  103. log.Error("GetUserNamesByIDs (MergeWhitelistUserIDs): %v", err)
  104. }
  105. approvalsWhitelistUsernames, err := user_model.GetUserNamesByIDs(ctx, bp.ApprovalsWhitelistUserIDs)
  106. if err != nil {
  107. log.Error("GetUserNamesByIDs (ApprovalsWhitelistUserIDs): %v", err)
  108. }
  109. pushWhitelistTeams, err := organization.GetTeamNamesByID(bp.WhitelistTeamIDs)
  110. if err != nil {
  111. log.Error("GetTeamNamesByID (WhitelistTeamIDs): %v", err)
  112. }
  113. mergeWhitelistTeams, err := organization.GetTeamNamesByID(bp.MergeWhitelistTeamIDs)
  114. if err != nil {
  115. log.Error("GetTeamNamesByID (MergeWhitelistTeamIDs): %v", err)
  116. }
  117. approvalsWhitelistTeams, err := organization.GetTeamNamesByID(bp.ApprovalsWhitelistTeamIDs)
  118. if err != nil {
  119. log.Error("GetTeamNamesByID (ApprovalsWhitelistTeamIDs): %v", err)
  120. }
  121. branchName := ""
  122. if !git_model.IsRuleNameSpecial(bp.RuleName) {
  123. branchName = bp.RuleName
  124. }
  125. return &api.BranchProtection{
  126. BranchName: branchName,
  127. RuleName: bp.RuleName,
  128. EnablePush: bp.CanPush,
  129. EnablePushWhitelist: bp.EnableWhitelist,
  130. PushWhitelistUsernames: pushWhitelistUsernames,
  131. PushWhitelistTeams: pushWhitelistTeams,
  132. PushWhitelistDeployKeys: bp.WhitelistDeployKeys,
  133. EnableMergeWhitelist: bp.EnableMergeWhitelist,
  134. MergeWhitelistUsernames: mergeWhitelistUsernames,
  135. MergeWhitelistTeams: mergeWhitelistTeams,
  136. EnableStatusCheck: bp.EnableStatusCheck,
  137. StatusCheckContexts: bp.StatusCheckContexts,
  138. RequiredApprovals: bp.RequiredApprovals,
  139. EnableApprovalsWhitelist: bp.EnableApprovalsWhitelist,
  140. ApprovalsWhitelistUsernames: approvalsWhitelistUsernames,
  141. ApprovalsWhitelistTeams: approvalsWhitelistTeams,
  142. BlockOnRejectedReviews: bp.BlockOnRejectedReviews,
  143. BlockOnOfficialReviewRequests: bp.BlockOnOfficialReviewRequests,
  144. BlockOnOutdatedBranch: bp.BlockOnOutdatedBranch,
  145. DismissStaleApprovals: bp.DismissStaleApprovals,
  146. RequireSignedCommits: bp.RequireSignedCommits,
  147. ProtectedFilePatterns: bp.ProtectedFilePatterns,
  148. UnprotectedFilePatterns: bp.UnprotectedFilePatterns,
  149. Created: bp.CreatedUnix.AsTime(),
  150. Updated: bp.UpdatedUnix.AsTime(),
  151. }
  152. }
  153. // ToTag convert a git.Tag to an api.Tag
  154. func ToTag(repo *repo_model.Repository, t *git.Tag) *api.Tag {
  155. return &api.Tag{
  156. Name: t.Name,
  157. Message: strings.TrimSpace(t.Message),
  158. ID: t.ID.String(),
  159. Commit: ToCommitMeta(repo, t),
  160. ZipballURL: util.URLJoin(repo.HTMLURL(), "archive", t.Name+".zip"),
  161. TarballURL: util.URLJoin(repo.HTMLURL(), "archive", t.Name+".tar.gz"),
  162. }
  163. }
  164. // ToVerification convert a git.Commit.Signature to an api.PayloadCommitVerification
  165. func ToVerification(ctx context.Context, c *git.Commit) *api.PayloadCommitVerification {
  166. verif := asymkey_model.ParseCommitWithSignature(ctx, c)
  167. commitVerification := &api.PayloadCommitVerification{
  168. Verified: verif.Verified,
  169. Reason: verif.Reason,
  170. }
  171. if c.Signature != nil {
  172. commitVerification.Signature = c.Signature.Signature
  173. commitVerification.Payload = c.Signature.Payload
  174. }
  175. if verif.SigningUser != nil {
  176. commitVerification.Signer = &api.PayloadUser{
  177. Name: verif.SigningUser.Name,
  178. Email: verif.SigningUser.Email,
  179. }
  180. }
  181. return commitVerification
  182. }
  183. // ToPublicKey convert asymkey_model.PublicKey to api.PublicKey
  184. func ToPublicKey(apiLink string, key *asymkey_model.PublicKey) *api.PublicKey {
  185. return &api.PublicKey{
  186. ID: key.ID,
  187. Key: key.Content,
  188. URL: fmt.Sprintf("%s%d", apiLink, key.ID),
  189. Title: key.Name,
  190. Fingerprint: key.Fingerprint,
  191. Created: key.CreatedUnix.AsTime(),
  192. }
  193. }
  194. // ToGPGKey converts models.GPGKey to api.GPGKey
  195. func ToGPGKey(key *asymkey_model.GPGKey) *api.GPGKey {
  196. subkeys := make([]*api.GPGKey, len(key.SubsKey))
  197. for id, k := range key.SubsKey {
  198. subkeys[id] = &api.GPGKey{
  199. ID: k.ID,
  200. PrimaryKeyID: k.PrimaryKeyID,
  201. KeyID: k.KeyID,
  202. PublicKey: k.Content,
  203. Created: k.CreatedUnix.AsTime(),
  204. Expires: k.ExpiredUnix.AsTime(),
  205. CanSign: k.CanSign,
  206. CanEncryptComms: k.CanEncryptComms,
  207. CanEncryptStorage: k.CanEncryptStorage,
  208. CanCertify: k.CanSign,
  209. Verified: k.Verified,
  210. }
  211. }
  212. emails := make([]*api.GPGKeyEmail, len(key.Emails))
  213. for i, e := range key.Emails {
  214. emails[i] = ToGPGKeyEmail(e)
  215. }
  216. return &api.GPGKey{
  217. ID: key.ID,
  218. PrimaryKeyID: key.PrimaryKeyID,
  219. KeyID: key.KeyID,
  220. PublicKey: key.Content,
  221. Created: key.CreatedUnix.AsTime(),
  222. Expires: key.ExpiredUnix.AsTime(),
  223. Emails: emails,
  224. SubsKey: subkeys,
  225. CanSign: key.CanSign,
  226. CanEncryptComms: key.CanEncryptComms,
  227. CanEncryptStorage: key.CanEncryptStorage,
  228. CanCertify: key.CanSign,
  229. Verified: key.Verified,
  230. }
  231. }
  232. // ToGPGKeyEmail convert models.EmailAddress to api.GPGKeyEmail
  233. func ToGPGKeyEmail(email *user_model.EmailAddress) *api.GPGKeyEmail {
  234. return &api.GPGKeyEmail{
  235. Email: email.Email,
  236. Verified: email.IsActivated,
  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(ctx context.Context, org *organization.Organization) *api.Organization {
  262. return &api.Organization{
  263. ID: org.ID,
  264. AvatarURL: org.AsUser().AvatarLink(ctx),
  265. Name: org.Name,
  266. UserName: org.Name,
  267. FullName: org.FullName,
  268. Email: org.Email,
  269. Description: org.Description,
  270. Website: org.Website,
  271. Location: org.Location,
  272. Visibility: org.Visibility.String(),
  273. RepoAdminChangeTeamAccess: org.RepoAdminChangeTeamAccess,
  274. }
  275. }
  276. // ToTeam convert models.Team to api.Team
  277. func ToTeam(ctx context.Context, team *organization.Team, loadOrg ...bool) (*api.Team, error) {
  278. teams, err := ToTeams(ctx, []*organization.Team{team}, len(loadOrg) != 0 && loadOrg[0])
  279. if err != nil || len(teams) == 0 {
  280. return nil, err
  281. }
  282. return teams[0], nil
  283. }
  284. // ToTeams convert models.Team list to api.Team list
  285. func ToTeams(ctx context.Context, teams []*organization.Team, loadOrgs bool) ([]*api.Team, error) {
  286. if len(teams) == 0 || teams[0] == nil {
  287. return nil, nil
  288. }
  289. cache := make(map[int64]*api.Organization)
  290. apiTeams := make([]*api.Team, len(teams))
  291. for i := range teams {
  292. if err := teams[i].LoadUnits(ctx); err != nil {
  293. return nil, err
  294. }
  295. apiTeams[i] = &api.Team{
  296. ID: teams[i].ID,
  297. Name: teams[i].Name,
  298. Description: teams[i].Description,
  299. IncludesAllRepositories: teams[i].IncludesAllRepositories,
  300. CanCreateOrgRepo: teams[i].CanCreateOrgRepo,
  301. Permission: teams[i].AccessMode.String(),
  302. Units: teams[i].GetUnitNames(),
  303. UnitsMap: teams[i].GetUnitsMap(),
  304. }
  305. if loadOrgs {
  306. apiOrg, ok := cache[teams[i].OrgID]
  307. if !ok {
  308. org, err := organization.GetOrgByID(ctx, teams[i].OrgID)
  309. if err != nil {
  310. return nil, err
  311. }
  312. apiOrg = ToOrganization(ctx, org)
  313. cache[teams[i].OrgID] = apiOrg
  314. }
  315. apiTeams[i].Organization = apiOrg
  316. }
  317. }
  318. return apiTeams, nil
  319. }
  320. // ToAnnotatedTag convert git.Tag to api.AnnotatedTag
  321. func ToAnnotatedTag(ctx context.Context, repo *repo_model.Repository, t *git.Tag, c *git.Commit) *api.AnnotatedTag {
  322. return &api.AnnotatedTag{
  323. Tag: t.Name,
  324. SHA: t.ID.String(),
  325. Object: ToAnnotatedTagObject(repo, c),
  326. Message: t.Message,
  327. URL: util.URLJoin(repo.APIURL(), "git/tags", t.ID.String()),
  328. Tagger: ToCommitUser(t.Tagger),
  329. Verification: ToVerification(ctx, c),
  330. }
  331. }
  332. // ToAnnotatedTagObject convert a git.Commit to an api.AnnotatedTagObject
  333. func ToAnnotatedTagObject(repo *repo_model.Repository, commit *git.Commit) *api.AnnotatedTagObject {
  334. return &api.AnnotatedTagObject{
  335. SHA: commit.ID.String(),
  336. Type: string(git.ObjectCommit),
  337. URL: util.URLJoin(repo.APIURL(), "git/commits", commit.ID.String()),
  338. }
  339. }
  340. // ToTopicResponse convert from models.Topic to api.TopicResponse
  341. func ToTopicResponse(topic *repo_model.Topic) *api.TopicResponse {
  342. return &api.TopicResponse{
  343. ID: topic.ID,
  344. Name: topic.Name,
  345. RepoCount: topic.RepoCount,
  346. Created: topic.CreatedUnix.AsTime(),
  347. Updated: topic.UpdatedUnix.AsTime(),
  348. }
  349. }
  350. // ToOAuth2Application convert from auth.OAuth2Application to api.OAuth2Application
  351. func ToOAuth2Application(app *auth.OAuth2Application) *api.OAuth2Application {
  352. return &api.OAuth2Application{
  353. ID: app.ID,
  354. Name: app.Name,
  355. ClientID: app.ClientID,
  356. ClientSecret: app.ClientSecret,
  357. ConfidentialClient: app.ConfidentialClient,
  358. RedirectURIs: app.RedirectURIs,
  359. Created: app.CreatedUnix.AsTime(),
  360. }
  361. }
  362. // ToLFSLock convert a LFSLock to api.LFSLock
  363. func ToLFSLock(ctx context.Context, l *git_model.LFSLock) *api.LFSLock {
  364. u, err := user_model.GetUserByID(ctx, l.OwnerID)
  365. if err != nil {
  366. return nil
  367. }
  368. return &api.LFSLock{
  369. ID: strconv.FormatInt(l.ID, 10),
  370. Path: l.Path,
  371. LockedAt: l.Created.Round(time.Second),
  372. Owner: &api.LFSLockOwner{
  373. Name: u.Name,
  374. },
  375. }
  376. }
  377. // ToChangedFile convert a gitdiff.DiffFile to api.ChangedFile
  378. func ToChangedFile(f *gitdiff.DiffFile, repo *repo_model.Repository, commit string) *api.ChangedFile {
  379. status := "changed"
  380. if f.IsDeleted {
  381. status = "deleted"
  382. } else if f.IsCreated {
  383. status = "added"
  384. } else if f.IsRenamed && f.Type == gitdiff.DiffFileCopy {
  385. status = "copied"
  386. } else if f.IsRenamed && f.Type == gitdiff.DiffFileRename {
  387. status = "renamed"
  388. } else if f.Addition == 0 && f.Deletion == 0 {
  389. status = "unchanged"
  390. }
  391. file := &api.ChangedFile{
  392. Filename: f.GetDiffFileName(),
  393. Status: status,
  394. Additions: f.Addition,
  395. Deletions: f.Deletion,
  396. Changes: f.Addition + f.Deletion,
  397. HTMLURL: fmt.Sprint(repo.HTMLURL(), "/src/commit/", commit, "/", util.PathEscapeSegments(f.GetDiffFileName())),
  398. ContentsURL: fmt.Sprint(repo.APIURL(), "/contents/", util.PathEscapeSegments(f.GetDiffFileName()), "?ref=", commit),
  399. RawURL: fmt.Sprint(repo.HTMLURL(), "/raw/commit/", commit, "/", util.PathEscapeSegments(f.GetDiffFileName())),
  400. }
  401. if status == "rename" {
  402. file.PreviousFilename = f.OldName
  403. }
  404. return file
  405. }