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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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) (*api.Branch, error) {
  28. if bp == nil {
  29. var hasPerm bool
  30. var err error
  31. if user != nil {
  32. hasPerm, err = models.HasAccessUnit(user, repo, models.UnitTypeCode, models.AccessModeWrite)
  33. if err != nil {
  34. return nil, err
  35. }
  36. }
  37. return &api.Branch{
  38. Name: b.Name,
  39. Commit: ToCommit(repo, c),
  40. Protected: false,
  41. RequiredApprovals: 0,
  42. EnableStatusCheck: false,
  43. StatusCheckContexts: []string{},
  44. UserCanPush: hasPerm,
  45. UserCanMerge: hasPerm,
  46. }, nil
  47. }
  48. branch := &api.Branch{
  49. Name: b.Name,
  50. Commit: ToCommit(repo, c),
  51. Protected: true,
  52. RequiredApprovals: bp.RequiredApprovals,
  53. EnableStatusCheck: bp.EnableStatusCheck,
  54. StatusCheckContexts: bp.StatusCheckContexts,
  55. }
  56. if user != nil {
  57. branch.UserCanPush = bp.CanUserPush(user.ID)
  58. branch.UserCanMerge = bp.IsUserMergeWhitelisted(user.ID)
  59. }
  60. return branch, nil
  61. }
  62. // ToTag convert a git.Tag to an api.Tag
  63. func ToTag(repo *models.Repository, t *git.Tag) *api.Tag {
  64. return &api.Tag{
  65. Name: t.Name,
  66. ID: t.ID.String(),
  67. Commit: ToCommitMeta(repo, t),
  68. ZipballURL: util.URLJoin(repo.HTMLURL(), "archive", t.Name+".zip"),
  69. TarballURL: util.URLJoin(repo.HTMLURL(), "archive", t.Name+".tar.gz"),
  70. }
  71. }
  72. // ToCommit convert a git.Commit to api.PayloadCommit
  73. func ToCommit(repo *models.Repository, c *git.Commit) *api.PayloadCommit {
  74. authorUsername := ""
  75. if author, err := models.GetUserByEmail(c.Author.Email); err == nil {
  76. authorUsername = author.Name
  77. } else if !models.IsErrUserNotExist(err) {
  78. log.Error("GetUserByEmail: %v", err)
  79. }
  80. committerUsername := ""
  81. if committer, err := models.GetUserByEmail(c.Committer.Email); err == nil {
  82. committerUsername = committer.Name
  83. } else if !models.IsErrUserNotExist(err) {
  84. log.Error("GetUserByEmail: %v", err)
  85. }
  86. return &api.PayloadCommit{
  87. ID: c.ID.String(),
  88. Message: c.Message(),
  89. URL: util.URLJoin(repo.HTMLURL(), "commit", c.ID.String()),
  90. Author: &api.PayloadUser{
  91. Name: c.Author.Name,
  92. Email: c.Author.Email,
  93. UserName: authorUsername,
  94. },
  95. Committer: &api.PayloadUser{
  96. Name: c.Committer.Name,
  97. Email: c.Committer.Email,
  98. UserName: committerUsername,
  99. },
  100. Timestamp: c.Author.When,
  101. Verification: ToVerification(c),
  102. }
  103. }
  104. // ToVerification convert a git.Commit.Signature to an api.PayloadCommitVerification
  105. func ToVerification(c *git.Commit) *api.PayloadCommitVerification {
  106. verif := models.ParseCommitWithSignature(c)
  107. commitVerification := &api.PayloadCommitVerification{
  108. Verified: verif.Verified,
  109. Reason: verif.Reason,
  110. }
  111. if c.Signature != nil {
  112. commitVerification.Signature = c.Signature.Signature
  113. commitVerification.Payload = c.Signature.Payload
  114. }
  115. if verif.SigningUser != nil {
  116. commitVerification.Signer = &structs.PayloadUser{
  117. Name: verif.SigningUser.Name,
  118. Email: verif.SigningUser.Email,
  119. }
  120. }
  121. return commitVerification
  122. }
  123. // ToPublicKey convert models.PublicKey to api.PublicKey
  124. func ToPublicKey(apiLink string, key *models.PublicKey) *api.PublicKey {
  125. return &api.PublicKey{
  126. ID: key.ID,
  127. Key: key.Content,
  128. URL: apiLink + com.ToStr(key.ID),
  129. Title: key.Name,
  130. Fingerprint: key.Fingerprint,
  131. Created: key.CreatedUnix.AsTime(),
  132. }
  133. }
  134. // ToGPGKey converts models.GPGKey to api.GPGKey
  135. func ToGPGKey(key *models.GPGKey) *api.GPGKey {
  136. subkeys := make([]*api.GPGKey, len(key.SubsKey))
  137. for id, k := range key.SubsKey {
  138. subkeys[id] = &api.GPGKey{
  139. ID: k.ID,
  140. PrimaryKeyID: k.PrimaryKeyID,
  141. KeyID: k.KeyID,
  142. PublicKey: k.Content,
  143. Created: k.CreatedUnix.AsTime(),
  144. Expires: k.ExpiredUnix.AsTime(),
  145. CanSign: k.CanSign,
  146. CanEncryptComms: k.CanEncryptComms,
  147. CanEncryptStorage: k.CanEncryptStorage,
  148. CanCertify: k.CanSign,
  149. }
  150. }
  151. emails := make([]*api.GPGKeyEmail, len(key.Emails))
  152. for i, e := range key.Emails {
  153. emails[i] = ToGPGKeyEmail(e)
  154. }
  155. return &api.GPGKey{
  156. ID: key.ID,
  157. PrimaryKeyID: key.PrimaryKeyID,
  158. KeyID: key.KeyID,
  159. PublicKey: key.Content,
  160. Created: key.CreatedUnix.AsTime(),
  161. Expires: key.ExpiredUnix.AsTime(),
  162. Emails: emails,
  163. SubsKey: subkeys,
  164. CanSign: key.CanSign,
  165. CanEncryptComms: key.CanEncryptComms,
  166. CanEncryptStorage: key.CanEncryptStorage,
  167. CanCertify: key.CanSign,
  168. }
  169. }
  170. // ToGPGKeyEmail convert models.EmailAddress to api.GPGKeyEmail
  171. func ToGPGKeyEmail(email *models.EmailAddress) *api.GPGKeyEmail {
  172. return &api.GPGKeyEmail{
  173. Email: email.Email,
  174. Verified: email.IsActivated,
  175. }
  176. }
  177. // ToHook convert models.Webhook to api.Hook
  178. func ToHook(repoLink string, w *models.Webhook) *api.Hook {
  179. config := map[string]string{
  180. "url": w.URL,
  181. "content_type": w.ContentType.Name(),
  182. }
  183. if w.HookTaskType == models.SLACK {
  184. s := webhook.GetSlackHook(w)
  185. config["channel"] = s.Channel
  186. config["username"] = s.Username
  187. config["icon_url"] = s.IconURL
  188. config["color"] = s.Color
  189. }
  190. return &api.Hook{
  191. ID: w.ID,
  192. Type: w.HookTaskType.Name(),
  193. URL: fmt.Sprintf("%s/settings/hooks/%d", repoLink, w.ID),
  194. Active: w.IsActive,
  195. Config: config,
  196. Events: w.EventsArray(),
  197. Updated: w.UpdatedUnix.AsTime(),
  198. Created: w.CreatedUnix.AsTime(),
  199. }
  200. }
  201. // ToGitHook convert git.Hook to api.GitHook
  202. func ToGitHook(h *git.Hook) *api.GitHook {
  203. return &api.GitHook{
  204. Name: h.Name(),
  205. IsActive: h.IsActive,
  206. Content: h.Content,
  207. }
  208. }
  209. // ToDeployKey convert models.DeployKey to api.DeployKey
  210. func ToDeployKey(apiLink string, key *models.DeployKey) *api.DeployKey {
  211. return &api.DeployKey{
  212. ID: key.ID,
  213. KeyID: key.KeyID,
  214. Key: key.Content,
  215. Fingerprint: key.Fingerprint,
  216. URL: apiLink + com.ToStr(key.ID),
  217. Title: key.Name,
  218. Created: key.CreatedUnix.AsTime(),
  219. ReadOnly: key.Mode == models.AccessModeRead, // All deploy keys are read-only.
  220. }
  221. }
  222. // ToOrganization convert models.User to api.Organization
  223. func ToOrganization(org *models.User) *api.Organization {
  224. return &api.Organization{
  225. ID: org.ID,
  226. AvatarURL: org.AvatarLink(),
  227. UserName: org.Name,
  228. FullName: org.FullName,
  229. Description: org.Description,
  230. Website: org.Website,
  231. Location: org.Location,
  232. Visibility: org.Visibility.String(),
  233. RepoAdminChangeTeamAccess: org.RepoAdminChangeTeamAccess,
  234. }
  235. }
  236. // ToTeam convert models.Team to api.Team
  237. func ToTeam(team *models.Team) *api.Team {
  238. return &api.Team{
  239. ID: team.ID,
  240. Name: team.Name,
  241. Description: team.Description,
  242. IncludesAllRepositories: team.IncludesAllRepositories,
  243. CanCreateOrgRepo: team.CanCreateOrgRepo,
  244. Permission: team.Authorize.String(),
  245. Units: team.GetUnitNames(),
  246. }
  247. }
  248. // ToUser convert models.User to api.User
  249. // signed shall only be set if requester is logged in. authed shall only be set if user is site admin or user himself
  250. func ToUser(user *models.User, signed, authed bool) *api.User {
  251. result := &api.User{
  252. UserName: user.Name,
  253. AvatarURL: user.AvatarLink(),
  254. FullName: markup.Sanitize(user.FullName),
  255. Created: user.CreatedUnix.AsTime(),
  256. }
  257. // hide primary email if API caller is anonymous or user keep email private
  258. if signed && (!user.KeepEmailPrivate || authed) {
  259. result.Email = user.Email
  260. }
  261. // only site admin will get these information and possibly user himself
  262. if authed {
  263. result.ID = user.ID
  264. result.IsAdmin = user.IsAdmin
  265. result.LastLogin = user.LastLoginUnix.AsTime()
  266. result.Language = user.Language
  267. }
  268. return result
  269. }
  270. // ToAnnotatedTag convert git.Tag to api.AnnotatedTag
  271. func ToAnnotatedTag(repo *models.Repository, t *git.Tag, c *git.Commit) *api.AnnotatedTag {
  272. return &api.AnnotatedTag{
  273. Tag: t.Name,
  274. SHA: t.ID.String(),
  275. Object: ToAnnotatedTagObject(repo, c),
  276. Message: t.Message,
  277. URL: util.URLJoin(repo.APIURL(), "git/tags", t.ID.String()),
  278. Tagger: ToCommitUser(t.Tagger),
  279. Verification: ToVerification(c),
  280. }
  281. }
  282. // ToAnnotatedTagObject convert a git.Commit to an api.AnnotatedTagObject
  283. func ToAnnotatedTagObject(repo *models.Repository, commit *git.Commit) *api.AnnotatedTagObject {
  284. return &api.AnnotatedTagObject{
  285. SHA: commit.ID.String(),
  286. Type: string(git.ObjectCommit),
  287. URL: util.URLJoin(repo.APIURL(), "git/commits", commit.ID.String()),
  288. }
  289. }
  290. // ToCommitUser convert a git.Signature to an api.CommitUser
  291. func ToCommitUser(sig *git.Signature) *api.CommitUser {
  292. return &api.CommitUser{
  293. Identity: api.Identity{
  294. Name: sig.Name,
  295. Email: sig.Email,
  296. },
  297. Date: sig.When.UTC().Format(time.RFC3339),
  298. }
  299. }
  300. // ToCommitMeta convert a git.Tag to an api.CommitMeta
  301. func ToCommitMeta(repo *models.Repository, tag *git.Tag) *api.CommitMeta {
  302. return &api.CommitMeta{
  303. SHA: tag.Object.String(),
  304. // TODO: Add the /commits API endpoint and use it here (https://developer.github.com/v3/repos/commits/#get-a-single-commit)
  305. URL: util.URLJoin(repo.APIURL(), "git/commits", tag.ID.String()),
  306. }
  307. }
  308. // ToTopicResponse convert from models.Topic to api.TopicResponse
  309. func ToTopicResponse(topic *models.Topic) *api.TopicResponse {
  310. return &api.TopicResponse{
  311. ID: topic.ID,
  312. Name: topic.Name,
  313. RepoCount: topic.RepoCount,
  314. Created: topic.CreatedUnix.AsTime(),
  315. Updated: topic.UpdatedUnix.AsTime(),
  316. }
  317. }