distea/forge/gitea.go
John Olheiser bba74a4923 Add extra context for PRs (#12)
Co-authored-by: jolheiser <john.olheiser@gmail.com>
Reviewed-on: gitea/distea#12
2022-09-08 00:28:34 +08:00

125 lines
2.8 KiB
Go

package forge
import (
"encoding/base64"
"fmt"
"sort"
"time"
"code.gitea.io/sdk/gitea"
)
var (
giteaOrg = "gitea"
giteaRepo = "gitea"
)
// Gitea is a forge implementation for https://gitea.com
type Gitea struct {
Client *gitea.Client
}
// ReplaceIssueLinks replaces issue short-links with markdown
func (g *Gitea) ReplaceIssueLinks(in string) string {
return issueRe.ReplaceAllString(in, "[#$1](https://gitea.com/gitea/gitea/issues/$1)")
}
// Image returns the Gitea image on GitHub
func (g *Gitea) Image() string {
return "https://gitea.com/avatars/35dea380390772b3130aafbac7ca49e6"
}
// Issue returns an Issue from Gitea
func (g *Gitea) Issue(num int) (*Issue, error) {
issue, _, err := g.Client.GetIssue(giteaOrg, giteaRepo, int64(num))
if err != nil {
return nil, err
}
labels := make([]string, 0, len(issue.Labels))
for _, label := range issue.Labels {
labels = append(labels, label.Name)
}
sort.Strings(labels)
var closed time.Time
if issue.Closed != nil {
closed = *issue.Closed
}
var pr *PullRequest
if issue.PullRequest != nil {
pull, _, err := g.Client.GetPullRequest(giteaOrg, giteaRepo, int64(num))
if err != nil {
return nil, err
}
pr = &PullRequest{
CanMerge: pull.Mergeable,
Base: pull.Base.Name,
Head: pull.Head.Name,
Diff: pull.DiffURL,
Patch: pull.PatchURL,
}
}
return &Issue{
User: User{
Username: issue.Poster.UserName,
URL: fmt.Sprintf("https://gitea.com/%s", issue.Poster.UserName),
Image: issue.Poster.AvatarURL,
},
Title: issue.Title,
URL: issue.HTMLURL,
Body: issue.Body,
Labels: labels,
State: string(issue.State),
Created: issue.Created,
Closed: closed,
Comments: issue.Comments,
PullRequest: pr,
}, nil
}
// Commit returns a Commit from Gitea
func (g *Gitea) Commit(sha string) (*Commit, error) {
commit, _, err := g.Client.GetSingleCommit(giteaOrg, giteaRepo, sha)
if err != nil {
return nil, err
}
return &Commit{
Author: User{
Username: commit.Author.UserName,
URL: fmt.Sprintf("https://gitea.com/%s", commit.Author.UserName),
Image: commit.Author.AvatarURL,
},
Message: commit.RepoCommit.Message,
SHA: commit.SHA,
URL: commit.HTMLURL,
Time: commit.CommitMeta.Created,
Additions: 0,
Deletions: 0,
Verified: false,
}, nil
}
// File returns a File from Gitea
func (g *Gitea) File(path, branch string) (*File, error) {
var ref string
if branch != "" {
ref = branch
}
file, _, err := g.Client.GetContents(giteaOrg, giteaRepo, ref, path)
if err != nil {
return nil, err
}
if file.Type != "file" {
return nil, ErrSourceFileOnly
}
content, err := base64.StdEncoding.DecodeString(*file.Content)
if err != nil {
return nil, err
}
return &File{
Contents: string(content),
URL: *file.HTMLURL,
}, nil
}