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. "code.gitea.io/gitea/models/db"
  14. git_model "code.gitea.io/gitea/models/git"
  15. issues_model "code.gitea.io/gitea/models/issues"
  16. "code.gitea.io/gitea/models/organization"
  17. "code.gitea.io/gitea/models/perm"
  18. access_model "code.gitea.io/gitea/models/perm/access"
  19. repo_model "code.gitea.io/gitea/models/repo"
  20. "code.gitea.io/gitea/models/unit"
  21. user_model "code.gitea.io/gitea/models/user"
  22. "code.gitea.io/gitea/modules/git"
  23. "code.gitea.io/gitea/modules/log"
  24. api "code.gitea.io/gitea/modules/structs"
  25. "code.gitea.io/gitea/modules/util"
  26. "code.gitea.io/gitea/services/gitdiff"
  27. )
  28. // ToEmail convert models.EmailAddress to api.Email
  29. func ToEmail(email *user_model.EmailAddress) *api.Email {
  30. return &api.Email{
  31. Email: email.Email,
  32. Verified: email.IsActivated,
  33. Primary: email.IsPrimary,
  34. }
  35. }
  36. // ToEmail convert models.EmailAddress to api.Email
  37. func ToEmailSearch(email *user_model.SearchEmailResult) *api.Email {
  38. return &api.Email{
  39. Email: email.Email,
  40. Verified: email.IsActivated,
  41. Primary: email.IsPrimary,
  42. UserID: email.UID,
  43. UserName: email.Name,
  44. }
  45. }
  46. // ToBranch convert a git.Commit and git.Branch to an api.Branch
  47. func ToBranch(ctx context.Context, repo *repo_model.Repository, b *git.Branch, c *git.Commit, bp *git_model.ProtectedBranch, user *user_model.User, isRepoAdmin bool) (*api.Branch, error) {
  48. if bp == nil {
  49. var hasPerm bool
  50. var canPush bool
  51. var err error
  52. if user != nil {
  53. hasPerm, err = access_model.HasAccessUnit(db.DefaultContext, user, repo, unit.TypeCode, perm.AccessModeWrite)
  54. if err != nil {
  55. return nil, err
  56. }
  57. perms, err := access_model.GetUserRepoPermission(db.DefaultContext, repo, user)
  58. if err != nil {
  59. return nil, err
  60. }
  61. canPush = issues_model.CanMaintainerWriteToBranch(perms, b.Name, user)
  62. }
  63. return &api.Branch{
  64. Name: b.Name,
  65. Commit: ToPayloadCommit(ctx, repo, c),
  66. Protected: false,
  67. RequiredApprovals: 0,
  68. EnableStatusCheck: false,
  69. StatusCheckContexts: []string{},
  70. UserCanPush: canPush,
  71. UserCanMerge: hasPerm,
  72. }, nil
  73. }
  74. branch := &api.Branch{
  75. Name: b.Name,
  76. Commit: ToPayloadCommit(ctx, repo, c),
  77. Protected: true,
  78. RequiredApprovals: bp.RequiredApprovals,
  79. EnableStatusCheck: bp.EnableStatusCheck,
  80. StatusCheckContexts: bp.StatusCheckContexts,
  81. }
  82. if isRepoAdmin {
  83. branch.EffectiveBranchProtectionName = bp.RuleName
  84. }
  85. if user != nil {
  86. permission, err := access_model.GetUserRepoPermission(db.DefaultContext, repo, user)
  87. if err != nil {
  88. return nil, err
  89. }
  90. bp.Repo = repo
  91. branch.UserCanPush = bp.CanUserPush(db.DefaultContext, user)
  92. branch.UserCanMerge = git_model.IsUserMergeWhitelisted(db.DefaultContext, bp, user.ID, permission)
  93. }
  94. return branch, nil
  95. }
  96. // ToBranchProtection convert a ProtectedBranch to api.BranchProtection
  97. func ToBranchProtection(bp *git_model.ProtectedBranch) *api.BranchProtection {
  98. pushWhitelistUsernames, err := user_model.GetUserNamesByIDs(bp.WhitelistUserIDs)
  99. if err != nil {
  100. log.Error("GetUserNamesByIDs (WhitelistUserIDs): %v", err)
  101. }
  102. mergeWhitelistUsernames, err := user_model.GetUserNamesByIDs(bp.MergeWhitelistUserIDs)
  103. if err != nil {
  104. log.Error("GetUserNamesByIDs (MergeWhitelistUserIDs): %v", err)
  105. }
  106. approvalsWhitelistUsernames, err := user_model.GetUserNamesByIDs(bp.ApprovalsWhitelistUserIDs)
  107. if err != nil {
  108. log.Error("GetUserNamesByIDs (ApprovalsWhitelistUserIDs): %v", err)
  109. }
  110. pushWhitelistTeams, err := organization.GetTeamNamesByID(bp.WhitelistTeamIDs)
  111. if err != nil {
  112. log.Error("GetTeamNamesByID (WhitelistTeamIDs): %v", err)
  113. }
  114. mergeWhitelistTeams, err := organization.GetTeamNamesByID(bp.MergeWhitelistTeamIDs)
  115. if err != nil {
  116. log.Error("GetTeamNamesByID (MergeWhitelistTeamIDs): %v", err)
  117. }
  118. approvalsWhitelistTeams, err := organization.GetTeamNamesByID(bp.ApprovalsWhitelistTeamIDs)
  119. if err != nil {
  120. log.Error("GetTeamNamesByID (ApprovalsWhitelistTeamIDs): %v", err)
  121. }
  122. branchName := ""
  123. if !git_model.IsRuleNameSpecial(bp.RuleName) {
  124. branchName = bp.RuleName
  125. }
  126. return &api.BranchProtection{
  127. BranchName: branchName,
  128. RuleName: bp.RuleName,
  129. EnablePush: bp.CanPush,
  130. EnablePushWhitelist: bp.EnableWhitelist,
  131. PushWhitelistUsernames: pushWhitelistUsernames,
  132. PushWhitelistTeams: pushWhitelistTeams,
  133. PushWhitelistDeployKeys: bp.WhitelistDeployKeys,
  134. EnableMergeWhitelist: bp.EnableMergeWhitelist,
  135. MergeWhitelistUsernames: mergeWhitelistUsernames,
  136. MergeWhitelistTeams: mergeWhitelistTeams,
  137. EnableStatusCheck: bp.EnableStatusCheck,
  138. StatusCheckContexts: bp.StatusCheckContexts,
  139. RequiredApprovals: bp.RequiredApprovals,
  140. EnableApprovalsWhitelist: bp.EnableApprovalsWhitelist,
  141. ApprovalsWhitelistUsernames: approvalsWhitelistUsernames,
  142. ApprovalsWhitelistTeams: approvalsWhitelistTeams,
  143. BlockOnRejectedReviews: bp.BlockOnRejectedReviews,
  144. BlockOnOfficialReviewRequests: bp.BlockOnOfficialReviewRequests,
  145. BlockOnOutdatedBranch: bp.BlockOnOutdatedBranch,
  146. DismissStaleApprovals: bp.DismissStaleApprovals,
  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. 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(db.DefaultContext, 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. }