gitblog1
This commit is contained in:
98
internal/github/client.go
Normal file
98
internal/github/client.go
Normal file
@@ -0,0 +1,98 @@
|
||||
package github
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/go-github/v56/github"
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
client *github.Client
|
||||
owner string
|
||||
repo string
|
||||
}
|
||||
|
||||
type Content struct {
|
||||
Path string
|
||||
Content string
|
||||
SHA string
|
||||
LastUpdated time.Time
|
||||
}
|
||||
|
||||
func NewClient(token, owner, repo string) *Client {
|
||||
ctx := context.Background()
|
||||
ts := oauth2.StaticTokenSource(
|
||||
&oauth2.Token{AccessToken: token},
|
||||
)
|
||||
tc := oauth2.NewClient(ctx, ts)
|
||||
client := github.NewClient(tc)
|
||||
|
||||
return &Client{
|
||||
client: client,
|
||||
owner: owner,
|
||||
repo: repo,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) GetFileContent(path string) (*Content, error) {
|
||||
ctx := context.Background()
|
||||
|
||||
fileContent, _, _, err := c.client.Repositories.GetContents(ctx, c.owner, c.repo, path, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get file content: %w", err)
|
||||
}
|
||||
|
||||
content, err := fileContent.GetContent()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode content: %w", err)
|
||||
}
|
||||
|
||||
return &Content{
|
||||
Path: path,
|
||||
Content: content,
|
||||
SHA: fileContent.GetSHA(),
|
||||
LastUpdated: time.Now(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *Client) ListDirectory(path string) ([]*Content, error) {
|
||||
ctx := context.Background()
|
||||
|
||||
_, contents, _, err := c.client.Repositories.GetContents(ctx, c.owner, c.repo, path, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to list directory: %w", err)
|
||||
}
|
||||
|
||||
var result []*Content
|
||||
for _, content := range contents {
|
||||
if content.GetType() == "file" {
|
||||
fileContent, err := c.GetFileContent(content.GetPath())
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
result = append(result, fileContent)
|
||||
}
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (c *Client) GetLastCommit() (*github.RepositoryCommit, error) {
|
||||
ctx := context.Background()
|
||||
|
||||
commits, _, err := c.client.Repositories.ListCommits(ctx, c.owner, c.repo, &github.CommitsListOptions{
|
||||
ListOptions: github.ListOptions{PerPage: 1},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get last commit: %w", err)
|
||||
}
|
||||
|
||||
if len(commits) == 0 {
|
||||
return nil, fmt.Errorf("no commits found")
|
||||
}
|
||||
|
||||
return commits[0], nil
|
||||
}
|
Reference in New Issue
Block a user