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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package convert
  5. import (
  6. "fmt"
  7. "time"
  8. "code.gitea.io/gitea/models"
  9. "code.gitea.io/gitea/modules/git"
  10. "code.gitea.io/gitea/modules/log"
  11. "code.gitea.io/gitea/modules/markup"
  12. "code.gitea.io/gitea/modules/structs"
  13. api "code.gitea.io/gitea/modules/structs"
  14. "code.gitea.io/gitea/modules/util"
  15. "code.gitea.io/gitea/modules/webhook"
  16. "github.com/unknwon/com"
  17. )
  18. // ToEmail convert models.EmailAddress to api.Email
  19. func ToEmail(email *models.EmailAddress) *api.Email {
  20. return &api.Email{
  21. Email: email.Email,
  22. Verified: email.IsActivated,
  23. Primary: email.IsPrimary,
  24. }
  25. }
  26. // ToBranch convert a git.Commit and git.Branch to an api.Branch
  27. func ToBranch(repo *models.Repository, b *git.Branch, c *git.Commit, bp *models.ProtectedBranch, user *models.User, isRepoAdmin bool) *api.Branch {
  28. if bp == nil {
  29. return &api.Branch{
  30. Name: b.Name,
  31. Commit: ToCommit(repo, c),
  32. Protected: false,
  33. RequiredApprovals: 0,
  34. EnableStatusCheck: false,
  35. StatusCheckContexts: []string{},
  36. UserCanPush: true,
  37. UserCanMerge: true,
  38. EffectiveBranchProtectionName: "",
  39. }
  40. }
  41. branchProtectionName := ""
  42. if isRepoAdmin {
  43. branchProtectionName = bp.BranchName
  44. }
  45. return &api.Branch{
  46. Name: b.Name,
  47. Commit: ToCommit(repo, c),
  48. Protected: true,
  49. RequiredApprovals: bp.RequiredApprovals,
  50. EnableStatusCheck: bp.EnableStatusCheck,
  51. StatusCheckContexts: bp.StatusCheckContexts,
  52. UserCanPush: bp.CanUserPush(user.ID),
  53. UserCanMerge: bp.IsUserMergeWhitelisted(user.ID),
  54. EffectiveBranchProtectionName: branchProtectionName,
  55. }
  56. }
  57. // ToBranchProtection convert a ProtectedBranch to api.BranchProtection
  58. func ToBranchProtection(bp *models.ProtectedBranch) *api.BranchProtection {
  59. pushWhitelistUsernames, err := models.GetUserNamesByIDs(bp.WhitelistUserIDs)
  60. if err != nil {
  61. log.Error("GetUserNamesByIDs (WhitelistUserIDs): %v", err)
  62. }
  63. mergeWhitelistUsernames, err := models.GetUserNamesByIDs(bp.MergeWhitelistUserIDs)
  64. if err != nil {
  65. log.Error("GetUserNamesByIDs (MergeWhitelistUserIDs): %v", err)
  66. }
  67. approvalsWhitelistUsernames, err := models.GetUserNamesByIDs(bp.ApprovalsWhitelistUserIDs)
  68. if err != nil {
  69. log.Error("GetUserNamesByIDs (ApprovalsWhitelistUserIDs): %v", err)
  70. }
  71. pushWhitelistTeams, err := models.GetTeamNamesByID(bp.WhitelistTeamIDs)
  72. if err != nil {
  73. log.Error("GetTeamNamesByID (WhitelistTeamIDs): %v", err)
  74. }
  75. mergeWhitelistTeams, err := models.GetTeamNamesByID(bp.MergeWhitelistTeamIDs)
  76. if err != nil {
  77. log.Error("GetTeamNamesByID (MergeWhitelistTeamIDs): %v", err)
  78. }
  79. approvalsWhitelistTeams, err := models.GetTeamNamesByID(bp.ApprovalsWhitelistTeamIDs)
  80. if err != nil {
  81. log.Error("GetTeamNamesByID (ApprovalsWhitelistTeamIDs): %v", err)
  82. }
  83. return &api.BranchProtection{
  84. BranchName: bp.BranchName,
  85. EnablePush: bp.CanPush,
  86. EnablePushWhitelist: bp.EnableWhitelist,
  87. PushWhitelistUsernames: pushWhitelistUsernames,
  88. PushWhitelistTeams: pushWhitelistTeams,
  89. PushWhitelistDeployKeys: bp.WhitelistDeployKeys,
  90. EnableMergeWhitelist: bp.EnableMergeWhitelist,
  91. MergeWhitelistUsernames: mergeWhitelistUsernames,
  92. MergeWhitelistTeams: mergeWhitelistTeams,
  93. EnableStatusCheck: bp.EnableStatusCheck,
  94. StatusCheckContexts: bp.StatusCheckContexts,
  95. RequiredApprovals: bp.RequiredApprovals,
  96. EnableApprovalsWhitelist: bp.EnableApprovalsWhitelist,
  97. ApprovalsWhitelistUsernames: approvalsWhitelistUsernames,
  98. ApprovalsWhitelistTeams: approvalsWhitelistTeams,
  99. BlockOnRejectedReviews: bp.BlockOnRejectedReviews,
  100. DismissStaleApprovals: bp.DismissStaleApprovals,
  101. RequireSignedCommits: bp.RequireSignedCommits,
  102. Created: bp.CreatedUnix.AsTime(),
  103. Updated: bp.UpdatedUnix.AsTime(),
  104. }
  105. }
  106. // ToTag convert a git.Tag to an api.Tag
  107. func ToTag(repo *models.Repository, t *git.Tag) *api.Tag {
  108. return &api.Tag{
  109. Name: t.Name,
  110. ID: t.ID.String(),
  111. Commit: ToCommitMeta(repo, t),
  112. ZipballURL: util.URLJoin(repo.HTMLURL(), "archive", t.Name+".zip"),
  113. TarballURL: util.URLJoin(repo.HTMLURL(), "archive", t.Name+".tar.gz"),
  114. }
  115. }
  116. // ToCommit convert a git.Commit to api.PayloadCommit
  117. func ToCommit(repo *models.Repository, c *git.Commit) *api.PayloadCommit {
  118. authorUsername := ""
  119. if author, err := models.GetUserByEmail(c.Author.Email); err == nil {
  120. authorUsername = author.Name
  121. } else if !models.IsErrUserNotExist(err) {
  122. log.Error("GetUserByEmail: %v", err)
  123. }
  124. committerUsername := ""
  125. if committer, err := models.GetUserByEmail(c.Committer.Email); err == nil {
  126. committerUsername = committer.Name
  127. } else if !models.IsErrUserNotExist(err) {
  128. log.Error("GetUserByEmail: %v", err)
  129. }
  130. return &api.PayloadCommit{
  131. ID: c.ID.String(),
  132. Message: c.Message(),
  133. URL: util.URLJoin(repo.HTMLURL(), "commit", c.ID.String()),
  134. Author: &api.PayloadUser{
  135. Name: c.Author.Name,
  136. Email: c.Author.Email,
  137. UserName: authorUsername,
  138. },
  139. Committer: &api.PayloadUser{
  140. Name: c.Committer.Name,
  141. Email: c.Committer.Email,
  142. UserName: committerUsername,
  143. },
  144. Timestamp: c.Author.When,
  145. Verification: ToVerification(c),
  146. }
  147. }
  148. // ToVerification convert a git.Commit.Signature to an api.PayloadCommitVerification
  149. func ToVerification(c *git.Commit) *api.PayloadCommitVerification {
  150. verif := models.ParseCommitWithSignature(c)
  151. commitVerification := &api.PayloadCommitVerification{
  152. Verified: verif.Verified,
  153. Reason: verif.Reason,
  154. }
  155. if c.Signature != nil {
  156. commitVerification.Signature = c.Signature.Signature
  157. commitVerification.Payload = c.Signature.Payload
  158. }
  159. if verif.SigningUser != nil {
  160. commitVerification.Signer = &structs.PayloadUser{
  161. Name: verif.SigningUser.Name,
  162. Email: verif.SigningUser.Email,
  163. }
  164. }
  165. return commitVerification
  166. }
  167. // ToPublicKey convert models.PublicKey to api.PublicKey
  168. func ToPublicKey(apiLink string, key *models.PublicKey) *api.PublicKey {
  169. return &api.PublicKey{
  170. ID: key.ID,
  171. Key: key.Content,
  172. URL: apiLink + com.ToStr(key.ID),
  173. Title: key.Name,
  174. Fingerprint: key.Fingerprint,
  175. Created: key.CreatedUnix.AsTime(),
  176. }
  177. }
  178. // ToGPGKey converts models.GPGKey to api.GPGKey
  179. func ToGPGKey(key *models.GPGKey) *api.GPGKey {
  180. subkeys := make([]*api.GPGKey, len(key.SubsKey))
  181. for id, k := range key.SubsKey {
  182. subkeys[id] = &api.GPGKey{
  183. ID: k.ID,
  184. PrimaryKeyID: k.PrimaryKeyID,
  185. KeyID: k.KeyID,
  186. PublicKey: k.Content,
  187. Created: k.CreatedUnix.AsTime(),
  188. Expires: k.ExpiredUnix.AsTime(),
  189. CanSign: k.CanSign,
  190. CanEncryptComms: k.CanEncryptComms,
  191. CanEncryptStorage: k.CanEncryptStorage,
  192. CanCertify: k.CanSign,
  193. }
  194. }
  195. emails := make([]*api.GPGKeyEmail, len(key.Emails))
  196. for i, e := range key.Emails {
  197. emails[i] = ToGPGKeyEmail(e)
  198. }
  199. return &api.GPGKey{
  200. ID: key.ID,
  201. PrimaryKeyID: key.PrimaryKeyID,
  202. KeyID: key.KeyID,
  203. PublicKey: key.Content,
  204. Created: key.CreatedUnix.AsTime(),
  205. Expires: key.ExpiredUnix.AsTime(),
  206. Emails: emails,
  207. SubsKey: subkeys,
  208. CanSign: key.CanSign,
  209. CanEncryptComms: key.CanEncryptComms,
  210. CanEncryptStorage: key.CanEncryptStorage,
  211. CanCertify: key.CanSign,
  212. }
  213. }
  214. // ToGPGKeyEmail convert models.EmailAddress to api.GPGKeyEmail
  215. func ToGPGKeyEmail(email *models.EmailAddress) *api.GPGKeyEmail {
  216. return &api.GPGKeyEmail{
  217. Email: email.Email,
  218. Verified: email.IsActivated,
  219. }
  220. }
  221. // ToHook convert models.Webhook to api.Hook
  222. func ToHook(repoLink string, w *models.Webhook) *api.Hook {
  223. config := map[string]string{
  224. "url": w.URL,
  225. "content_type": w.ContentType.Name(),
  226. }
  227. if w.HookTaskType == models.SLACK {
  228. s := webhook.GetSlackHook(w)
  229. config["channel"] = s.Channel
  230. config["username"] = s.Username
  231. config["icon_url"] = s.IconURL
  232. config["color"] = s.Color
  233. }
  234. return &api.Hook{
  235. ID: w.ID,
  236. Type: w.HookTaskType.Name(),
  237. URL: fmt.Sprintf("%s/settings/hooks/%d", repoLink, w.ID),
  238. Active: w.IsActive,
  239. Config: config,
  240. Events: w.EventsArray(),
  241. Updated: w.UpdatedUnix.AsTime(),
  242. Created: w.CreatedUnix.AsTime(),
  243. }
  244. }
  245. // ToGitHook convert git.Hook to api.GitHook
  246. func ToGitHook(h *git.Hook) *api.GitHook {
  247. return &api.GitHook{
  248. Name: h.Name(),
  249. IsActive: h.IsActive,
  250. Content: h.Content,
  251. }
  252. }
  253. // ToDeployKey convert models.DeployKey to api.DeployKey
  254. func ToDeployKey(apiLink string, key *models.DeployKey) *api.DeployKey {
  255. return &api.DeployKey{
  256. ID: key.ID,
  257. KeyID: key.KeyID,
  258. Key: key.Content,
  259. Fingerprint: key.Fingerprint,
  260. URL: apiLink + com.ToStr(key.ID),
  261. Title: key.Name,
  262. Created: key.CreatedUnix.AsTime(),
  263. ReadOnly: key.Mode == models.AccessModeRead, // All deploy keys are read-only.
  264. }
  265. }
  266. // ToOrganization convert models.User to api.Organization
  267. func ToOrganization(org *models.User) *api.Organization {
  268. return &api.Organization{
  269. ID: org.ID,
  270. AvatarURL: org.AvatarLink(),
  271. UserName: org.Name,
  272. FullName: org.FullName,
  273. Description: org.Description,
  274. Website: org.Website,
  275. Location: org.Location,
  276. Visibility: org.Visibility.String(),
  277. RepoAdminChangeTeamAccess: org.RepoAdminChangeTeamAccess,
  278. }
  279. }
  280. // ToTeam convert models.Team to api.Team
  281. func ToTeam(team *models.Team) *api.Team {
  282. return &api.Team{
  283. ID: team.ID,
  284. Name: team.Name,
  285. Description: team.Description,
  286. IncludesAllRepositories: team.IncludesAllRepositories,
  287. CanCreateOrgRepo: team.CanCreateOrgRepo,
  288. Permission: team.Authorize.String(),
  289. Units: team.GetUnitNames(),
  290. }
  291. }
  292. // ToUser convert models.User to api.User
  293. // signed shall only be set if requester is logged in. authed shall only be set if user is site admin or user himself
  294. func ToUser(user *models.User, signed, authed bool) *api.User {
  295. result := &api.User{
  296. UserName: user.Name,
  297. AvatarURL: user.AvatarLink(),
  298. FullName: markup.Sanitize(user.FullName),
  299. Created: user.CreatedUnix.AsTime(),
  300. }
  301. // hide primary email if API caller is anonymous or user keep email private
  302. if signed && (!user.KeepEmailPrivate || authed) {
  303. result.Email = user.Email
  304. }
  305. // only site admin will get these information and possibly user himself
  306. if authed {
  307. result.ID = user.ID
  308. result.IsAdmin = user.IsAdmin
  309. result.LastLogin = user.LastLoginUnix.AsTime()
  310. result.Language = user.Language
  311. }
  312. return result
  313. }
  314. // ToAnnotatedTag convert git.Tag to api.AnnotatedTag
  315. func ToAnnotatedTag(repo *models.Repository, t *git.Tag, c *git.Commit) *api.AnnotatedTag {
  316. return &api.AnnotatedTag{
  317. Tag: t.Name,
  318. SHA: t.ID.String(),
  319. Object: ToAnnotatedTagObject(repo, c),
  320. Message: t.Message,
  321. URL: util.URLJoin(repo.APIURL(), "git/tags", t.ID.String()),
  322. Tagger: ToCommitUser(t.Tagger),
  323. Verification: ToVerification(c),
  324. }
  325. }
  326. // ToAnnotatedTagObject convert a git.Commit to an api.AnnotatedTagObject
  327. func ToAnnotatedTagObject(repo *models.Repository, commit *git.Commit) *api.AnnotatedTagObject {
  328. return &api.AnnotatedTagObject{
  329. SHA: commit.ID.String(),
  330. Type: string(git.ObjectCommit),
  331. URL: util.URLJoin(repo.APIURL(), "git/commits", commit.ID.String()),
  332. }
  333. }
  334. // ToCommitUser convert a git.Signature to an api.CommitUser
  335. func ToCommitUser(sig *git.Signature) *api.CommitUser {
  336. return &api.CommitUser{
  337. Identity: api.Identity{
  338. Name: sig.Name,
  339. Email: sig.Email,
  340. },
  341. Date: sig.When.UTC().Format(time.RFC3339),
  342. }
  343. }
  344. // ToCommitMeta convert a git.Tag to an api.CommitMeta
  345. func ToCommitMeta(repo *models.Repository, tag *git.Tag) *api.CommitMeta {
  346. return &api.CommitMeta{
  347. SHA: tag.Object.String(),
  348. // TODO: Add the /commits API endpoint and use it here (https://developer.github.com/v3/repos/commits/#get-a-single-commit)
  349. URL: util.URLJoin(repo.APIURL(), "git/commits", tag.ID.String()),
  350. }
  351. }
  352. // ToTopicResponse convert from models.Topic to api.TopicResponse
  353. func ToTopicResponse(topic *models.Topic) *api.TopicResponse {
  354. return &api.TopicResponse{
  355. ID: topic.ID,
  356. Name: topic.Name,
  357. RepoCount: topic.RepoCount,
  358. Created: topic.CreatedUnix.AsTime(),
  359. Updated: topic.UpdatedUnix.AsTime(),
  360. }
  361. }
  362. // ToOAuth2Application convert from models.OAuth2Application to api.OAuth2Application
  363. func ToOAuth2Application(app *models.OAuth2Application) *api.OAuth2Application {
  364. return &api.OAuth2Application{
  365. ID: app.ID,
  366. Name: app.Name,
  367. ClientID: app.ClientID,
  368. ClientSecret: app.ClientSecret,
  369. RedirectURIs: app.RedirectURIs,
  370. Created: app.CreatedUnix.AsTime(),
  371. }
  372. }