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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  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(ctx, bp.WhitelistTeamIDs)
  110. if err != nil {
  111. log.Error("GetTeamNamesByID (WhitelistTeamIDs): %v", err)
  112. }
  113. mergeWhitelistTeams, err := organization.GetTeamNamesByID(ctx, bp.MergeWhitelistTeamIDs)
  114. if err != nil {
  115. log.Error("GetTeamNamesByID (MergeWhitelistTeamIDs): %v", err)
  116. }
  117. approvalsWhitelistTeams, err := organization.GetTeamNamesByID(ctx, 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. IgnoreStaleApprovals: bp.IgnoreStaleApprovals,
  147. RequireSignedCommits: bp.RequireSignedCommits,
  148. ProtectedFilePatterns: bp.ProtectedFilePatterns,
  149. UnprotectedFilePatterns: bp.UnprotectedFilePatterns,
  150. Created: bp.CreatedUnix.AsTime(),
  151. Updated: bp.UpdatedUnix.AsTime(),
  152. }
  153. }
  154. // ToTag convert a git.Tag to an api.Tag
  155. func ToTag(repo *repo_model.Repository, t *git.Tag) *api.Tag {
  156. return &api.Tag{
  157. Name: t.Name,
  158. Message: strings.TrimSpace(t.Message),
  159. ID: t.ID.String(),
  160. Commit: ToCommitMeta(repo, t),
  161. ZipballURL: util.URLJoin(repo.HTMLURL(), "archive", t.Name+".zip"),
  162. TarballURL: util.URLJoin(repo.HTMLURL(), "archive", t.Name+".tar.gz"),
  163. }
  164. }
  165. // ToVerification convert a git.Commit.Signature to an api.PayloadCommitVerification
  166. func ToVerification(ctx context.Context, c *git.Commit) *api.PayloadCommitVerification {
  167. verif := asymkey_model.ParseCommitWithSignature(ctx, c)
  168. commitVerification := &api.PayloadCommitVerification{
  169. Verified: verif.Verified,
  170. Reason: verif.Reason,
  171. }
  172. if c.Signature != nil {
  173. commitVerification.Signature = c.Signature.Signature
  174. commitVerification.Payload = c.Signature.Payload
  175. }
  176. if verif.SigningUser != nil {
  177. commitVerification.Signer = &api.PayloadUser{
  178. Name: verif.SigningUser.Name,
  179. Email: verif.SigningUser.Email,
  180. }
  181. }
  182. return commitVerification
  183. }
  184. // ToPublicKey convert asymkey_model.PublicKey to api.PublicKey
  185. func ToPublicKey(apiLink string, key *asymkey_model.PublicKey) *api.PublicKey {
  186. return &api.PublicKey{
  187. ID: key.ID,
  188. Key: key.Content,
  189. URL: fmt.Sprintf("%s%d", apiLink, key.ID),
  190. Title: key.Name,
  191. Fingerprint: key.Fingerprint,
  192. Created: key.CreatedUnix.AsTime(),
  193. }
  194. }
  195. // ToGPGKey converts models.GPGKey to api.GPGKey
  196. func ToGPGKey(key *asymkey_model.GPGKey) *api.GPGKey {
  197. subkeys := make([]*api.GPGKey, len(key.SubsKey))
  198. for id, k := range key.SubsKey {
  199. subkeys[id] = &api.GPGKey{
  200. ID: k.ID,
  201. PrimaryKeyID: k.PrimaryKeyID,
  202. KeyID: k.KeyID,
  203. PublicKey: k.Content,
  204. Created: k.CreatedUnix.AsTime(),
  205. Expires: k.ExpiredUnix.AsTime(),
  206. CanSign: k.CanSign,
  207. CanEncryptComms: k.CanEncryptComms,
  208. CanEncryptStorage: k.CanEncryptStorage,
  209. CanCertify: k.CanSign,
  210. Verified: k.Verified,
  211. }
  212. }
  213. emails := make([]*api.GPGKeyEmail, len(key.Emails))
  214. for i, e := range key.Emails {
  215. emails[i] = ToGPGKeyEmail(e)
  216. }
  217. return &api.GPGKey{
  218. ID: key.ID,
  219. PrimaryKeyID: key.PrimaryKeyID,
  220. KeyID: key.KeyID,
  221. PublicKey: key.Content,
  222. Created: key.CreatedUnix.AsTime(),
  223. Expires: key.ExpiredUnix.AsTime(),
  224. Emails: emails,
  225. SubsKey: subkeys,
  226. CanSign: key.CanSign,
  227. CanEncryptComms: key.CanEncryptComms,
  228. CanEncryptStorage: key.CanEncryptStorage,
  229. CanCertify: key.CanSign,
  230. Verified: key.Verified,
  231. }
  232. }
  233. // ToGPGKeyEmail convert models.EmailAddress to api.GPGKeyEmail
  234. func ToGPGKeyEmail(email *user_model.EmailAddress) *api.GPGKeyEmail {
  235. return &api.GPGKeyEmail{
  236. Email: email.Email,
  237. Verified: email.IsActivated,
  238. }
  239. }
  240. // ToGitHook convert git.Hook to api.GitHook
  241. func ToGitHook(h *git.Hook) *api.GitHook {
  242. return &api.GitHook{
  243. Name: h.Name(),
  244. IsActive: h.IsActive,
  245. Content: h.Content,
  246. }
  247. }
  248. // ToDeployKey convert asymkey_model.DeployKey to api.DeployKey
  249. func ToDeployKey(apiLink string, key *asymkey_model.DeployKey) *api.DeployKey {
  250. return &api.DeployKey{
  251. ID: key.ID,
  252. KeyID: key.KeyID,
  253. Key: key.Content,
  254. Fingerprint: key.Fingerprint,
  255. URL: fmt.Sprintf("%s%d", apiLink, key.ID),
  256. Title: key.Name,
  257. Created: key.CreatedUnix.AsTime(),
  258. ReadOnly: key.Mode == perm.AccessModeRead, // All deploy keys are read-only.
  259. }
  260. }
  261. // ToOrganization convert user_model.User to api.Organization
  262. func ToOrganization(ctx context.Context, org *organization.Organization) *api.Organization {
  263. return &api.Organization{
  264. ID: org.ID,
  265. AvatarURL: org.AsUser().AvatarLink(ctx),
  266. Name: org.Name,
  267. UserName: org.Name,
  268. FullName: org.FullName,
  269. Email: org.Email,
  270. Description: org.Description,
  271. Website: org.Website,
  272. Location: org.Location,
  273. Visibility: org.Visibility.String(),
  274. RepoAdminChangeTeamAccess: org.RepoAdminChangeTeamAccess,
  275. }
  276. }
  277. // ToTeam convert models.Team to api.Team
  278. func ToTeam(ctx context.Context, team *organization.Team, loadOrg ...bool) (*api.Team, error) {
  279. teams, err := ToTeams(ctx, []*organization.Team{team}, len(loadOrg) != 0 && loadOrg[0])
  280. if err != nil || len(teams) == 0 {
  281. return nil, err
  282. }
  283. return teams[0], nil
  284. }
  285. // ToTeams convert models.Team list to api.Team list
  286. func ToTeams(ctx context.Context, teams []*organization.Team, loadOrgs bool) ([]*api.Team, error) {
  287. cache := make(map[int64]*api.Organization)
  288. apiTeams := make([]*api.Team, 0, len(teams))
  289. for _, t := range teams {
  290. if err := t.LoadUnits(ctx); err != nil {
  291. return nil, err
  292. }
  293. apiTeam := &api.Team{
  294. ID: t.ID,
  295. Name: t.Name,
  296. Description: t.Description,
  297. IncludesAllRepositories: t.IncludesAllRepositories,
  298. CanCreateOrgRepo: t.CanCreateOrgRepo,
  299. Permission: t.AccessMode.String(),
  300. Units: t.GetUnitNames(),
  301. UnitsMap: t.GetUnitsMap(),
  302. }
  303. if loadOrgs {
  304. apiOrg, ok := cache[t.OrgID]
  305. if !ok {
  306. org, err := organization.GetOrgByID(ctx, t.OrgID)
  307. if err != nil {
  308. return nil, err
  309. }
  310. apiOrg = ToOrganization(ctx, org)
  311. cache[t.OrgID] = apiOrg
  312. }
  313. apiTeam.Organization = apiOrg
  314. }
  315. apiTeams = append(apiTeams, apiTeam)
  316. }
  317. return apiTeams, nil
  318. }
  319. // ToAnnotatedTag convert git.Tag to api.AnnotatedTag
  320. func ToAnnotatedTag(ctx context.Context, repo *repo_model.Repository, t *git.Tag, c *git.Commit) *api.AnnotatedTag {
  321. return &api.AnnotatedTag{
  322. Tag: t.Name,
  323. SHA: t.ID.String(),
  324. Object: ToAnnotatedTagObject(repo, c),
  325. Message: t.Message,
  326. URL: util.URLJoin(repo.APIURL(), "git/tags", t.ID.String()),
  327. Tagger: ToCommitUser(t.Tagger),
  328. Verification: ToVerification(ctx, c),
  329. }
  330. }
  331. // ToAnnotatedTagObject convert a git.Commit to an api.AnnotatedTagObject
  332. func ToAnnotatedTagObject(repo *repo_model.Repository, commit *git.Commit) *api.AnnotatedTagObject {
  333. return &api.AnnotatedTagObject{
  334. SHA: commit.ID.String(),
  335. Type: string(git.ObjectCommit),
  336. URL: util.URLJoin(repo.APIURL(), "git/commits", commit.ID.String()),
  337. }
  338. }
  339. // ToTopicResponse convert from models.Topic to api.TopicResponse
  340. func ToTopicResponse(topic *repo_model.Topic) *api.TopicResponse {
  341. return &api.TopicResponse{
  342. ID: topic.ID,
  343. Name: topic.Name,
  344. RepoCount: topic.RepoCount,
  345. Created: topic.CreatedUnix.AsTime(),
  346. Updated: topic.UpdatedUnix.AsTime(),
  347. }
  348. }
  349. // ToOAuth2Application convert from auth.OAuth2Application to api.OAuth2Application
  350. func ToOAuth2Application(app *auth.OAuth2Application) *api.OAuth2Application {
  351. return &api.OAuth2Application{
  352. ID: app.ID,
  353. Name: app.Name,
  354. ClientID: app.ClientID,
  355. ClientSecret: app.ClientSecret,
  356. ConfidentialClient: app.ConfidentialClient,
  357. RedirectURIs: app.RedirectURIs,
  358. Created: app.CreatedUnix.AsTime(),
  359. }
  360. }
  361. // ToLFSLock convert a LFSLock to api.LFSLock
  362. func ToLFSLock(ctx context.Context, l *git_model.LFSLock) *api.LFSLock {
  363. u, err := user_model.GetUserByID(ctx, l.OwnerID)
  364. if err != nil {
  365. return nil
  366. }
  367. return &api.LFSLock{
  368. ID: strconv.FormatInt(l.ID, 10),
  369. Path: l.Path,
  370. LockedAt: l.Created.Round(time.Second),
  371. Owner: &api.LFSLockOwner{
  372. Name: u.Name,
  373. },
  374. }
  375. }
  376. // ToChangedFile convert a gitdiff.DiffFile to api.ChangedFile
  377. func ToChangedFile(f *gitdiff.DiffFile, repo *repo_model.Repository, commit string) *api.ChangedFile {
  378. status := "changed"
  379. if f.IsDeleted {
  380. status = "deleted"
  381. } else if f.IsCreated {
  382. status = "added"
  383. } else if f.IsRenamed && f.Type == gitdiff.DiffFileCopy {
  384. status = "copied"
  385. } else if f.IsRenamed && f.Type == gitdiff.DiffFileRename {
  386. status = "renamed"
  387. } else if f.Addition == 0 && f.Deletion == 0 {
  388. status = "unchanged"
  389. }
  390. file := &api.ChangedFile{
  391. Filename: f.GetDiffFileName(),
  392. Status: status,
  393. Additions: f.Addition,
  394. Deletions: f.Deletion,
  395. Changes: f.Addition + f.Deletion,
  396. HTMLURL: fmt.Sprint(repo.HTMLURL(), "/src/commit/", commit, "/", util.PathEscapeSegments(f.GetDiffFileName())),
  397. ContentsURL: fmt.Sprint(repo.APIURL(), "/contents/", util.PathEscapeSegments(f.GetDiffFileName()), "?ref=", commit),
  398. RawURL: fmt.Sprint(repo.HTMLURL(), "/raw/commit/", commit, "/", util.PathEscapeSegments(f.GetDiffFileName())),
  399. }
  400. if status == "rename" {
  401. file.PreviousFilename = f.OldName
  402. }
  403. return file
  404. }