gitforgefs/forges/github/client.go

98 lines
2.4 KiB
Go
Raw Normal View History

package github
import (
2024-08-05 01:16:03 +00:00
"context"
2024-08-04 22:59:57 +00:00
"fmt"
"log/slog"
2024-08-04 22:59:57 +00:00
"sync"
"github.com/badjware/gitlabfs/config"
"github.com/badjware/gitlabfs/fstree"
"github.com/google/go-github/v63/github"
)
type githubClient struct {
config.GithubClientConfig
client *github.Client
logger *slog.Logger
rootContent map[string]fstree.GroupSource
2024-08-04 22:59:57 +00:00
// API response cache
organizationCacheMux sync.RWMutex
organizationNameToIDMap map[string]int64
organizationCache map[int64]*Organization
2024-08-05 01:00:34 +00:00
userCacheMux sync.RWMutex
userNameToIDMap map[string]int64
userCache map[int64]*User
}
func NewClient(logger *slog.Logger, config config.GithubClientConfig) (*githubClient, error) {
client := github.NewClient(nil)
if config.Token != "" {
client = client.WithAuthToken(config.Token)
}
gitHubClient := &githubClient{
GithubClientConfig: config,
client: client,
logger: logger,
2024-08-04 22:59:57 +00:00
rootContent: nil,
organizationNameToIDMap: map[string]int64{},
organizationCache: map[int64]*Organization{},
2024-08-05 01:00:34 +00:00
userNameToIDMap: map[string]int64{},
userCache: map[int64]*User{},
}
2024-08-05 01:16:03 +00:00
// Fetch current user and add it to the list
currentUser, _, err := client.Users.Get(context.Background(), "")
if err != nil {
logger.Warn("failed to fetch the current user:", "error", err.Error())
} else {
gitHubClient.UserNames = append(gitHubClient.UserNames, *currentUser.Login)
}
return gitHubClient, nil
}
func (c *githubClient) FetchRootGroupContent() (map[string]fstree.GroupSource, error) {
2024-08-04 22:59:57 +00:00
if c.rootContent == nil {
rootContent := make(map[string]fstree.GroupSource)
2024-08-09 03:44:12 +00:00
for _, orgName := range c.GithubClientConfig.OrgNames {
org, err := c.fetchOrganization(orgName)
2024-08-04 22:59:57 +00:00
if err != nil {
c.logger.Warn(err.Error())
} else {
rootContent[org.Name] = org
}
}
2024-08-05 01:00:34 +00:00
2024-08-09 03:44:12 +00:00
for _, userName := range c.GithubClientConfig.UserNames {
user, err := c.fetchUser(userName)
2024-08-05 01:00:34 +00:00
if err != nil {
c.logger.Warn(err.Error())
} else {
rootContent[user.Name] = user
}
}
2024-08-04 22:59:57 +00:00
c.rootContent = rootContent
}
return c.rootContent, nil
}
func (c *githubClient) FetchGroupContent(gid uint64) (map[string]fstree.GroupSource, map[string]fstree.RepositorySource, error) {
2024-08-04 22:59:57 +00:00
if org, found := c.organizationCache[int64(gid)]; found {
return c.fetchOrganizationContent(org)
}
2024-08-05 01:00:34 +00:00
if user, found := c.userCache[int64(gid)]; found {
return c.fetchUserContent(user)
}
2024-08-04 22:59:57 +00:00
return nil, nil, fmt.Errorf("invalid gid: %v", gid)
}