vanity/service/github.go

90 lines
1.9 KiB
Go

package service
import (
"context"
"fmt"
"go.jolheiser.com/vanity/api"
"go.jolheiser.com/vanity/flags"
"github.com/google/go-github/v32/github"
"golang.org/x/oauth2"
)
var _ Service = &GitHub{}
func NewGitHub() *GitHub {
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: flags.Token},
)
client := oauth2.NewClient(context.Background(), ts)
ghClient := github.NewClient(client)
ghClient.BaseURL = flags.BaseURL
return &GitHub{
client: ghClient,
}
}
type GitHub struct {
client *github.Client
}
func (g GitHub) Packages() (map[string]*api.Package, error) {
packages := make(map[string]*api.Package)
page := 0
for {
opts := github.RepositoryListOptions{
ListOptions: github.ListOptions{
Page: page,
PerPage: 50,
},
}
repos, _, err := g.client.Repositories.List(context.Background(), flags.Namespace, &opts)
if err != nil {
return nil, err
}
for _, repo := range repos {
packages[repo.GetName()] = &api.Package{
Name: repo.GetName(),
Description: repo.GetDescription(),
Branch: repo.GetDefaultBranch(),
WebURL: repo.GetHTMLURL(),
CloneHTTP: repo.GetCloneURL(),
CloneSSH: repo.GetSSHURL(),
Private: repo.GetPrivate(),
Fork: repo.GetFork(),
Mirror: false,
Archive: repo.GetArchived(),
}
}
page++
if len(repos) == 0 {
break
}
}
return packages, nil
}
func (g GitHub) GoDir(pkg *api.Package) string {
return fmt.Sprintf("%s/tree/%s{/dir}", pkg.WebURL, pkg.Branch)
}
func (g GitHub) GoFile(pkg *api.Package) string {
return fmt.Sprintf("%s/blob/%s{/dir}/{file}#L{line}", pkg.WebURL, pkg.Branch)
}
func (g GitHub) GoMod(pkg *api.Package) (string, error) {
content, _, _, err := g.client.Repositories.GetContents(context.Background(), flags.Namespace, pkg.Name, "go.mod",
&github.RepositoryContentGetOptions{
Ref: pkg.Branch,
})
if err != nil {
return "", err
}
return content.GetContent()
}