gitforgefs/git/client.go

90 lines
2.0 KiB
Go
Raw Permalink Normal View History

2020-12-29 02:37:18 +00:00
package git
import (
"context"
2020-12-29 02:37:18 +00:00
"net/url"
"os"
"path/filepath"
"strconv"
"time"
"github.com/vmihailenco/taskq/v3"
"github.com/vmihailenco/taskq/v3/memqueue"
2020-12-29 02:37:18 +00:00
)
2021-03-03 05:24:27 +00:00
const (
CloneInit = iota
CloneClone = iota
)
type GitClonerPuller interface {
CloneOrPull(url string, pid int, defaultBranch string) (localRepoLoc string, err error)
}
2020-12-29 02:37:18 +00:00
type GitClientParam struct {
2021-03-03 05:24:27 +00:00
CloneLocation string
RemoteName string
RemoteURL *url.URL
CloneMethod int
PullDepth int
AutoPull bool
QueueSize int
QueueWorkerCount int
2020-12-29 02:37:18 +00:00
}
type gitClient struct {
GitClientParam
queue taskq.Queue
cloneTask *taskq.Task
pullTask *taskq.Task
2020-12-29 02:37:18 +00:00
}
func NewClient(p GitClientParam) (*gitClient, error) {
queueFactory := memqueue.NewFactory()
2020-12-29 02:37:18 +00:00
// Create the client
c := &gitClient{
GitClientParam: p,
queue: queueFactory.RegisterQueue(&taskq.QueueOptions{
Name: "git-queue",
MaxNumWorker: int32(p.QueueWorkerCount),
BufferSize: p.QueueSize,
Storage: taskq.NewLocalStorage(),
}),
2020-12-29 02:37:18 +00:00
}
c.cloneTask = taskq.RegisterTask(&taskq.TaskOptions{
Name: "git-clone",
Handler: c.clone,
RetryLimit: 1,
})
c.pullTask = taskq.RegisterTask(&taskq.TaskOptions{
Name: "git-pull",
Handler: c.pull,
RetryLimit: 1,
})
2020-12-29 02:37:18 +00:00
return c, nil
}
func (c *gitClient) getLocalRepoLoc(pid int) string {
return filepath.Join(c.CloneLocation, c.RemoteURL.Hostname(), strconv.Itoa(pid))
}
func (c *gitClient) CloneOrPull(url string, pid int, defaultBranch string) (localRepoLoc string, err error) {
localRepoLoc = c.getLocalRepoLoc(pid)
if _, err := os.Stat(localRepoLoc); os.IsNotExist(err) {
// Dispatch clone msg
msg := c.cloneTask.WithArgs(context.Background(), url, defaultBranch, localRepoLoc)
msg.OnceInPeriod(time.Second, pid)
c.queue.Add(msg)
} else if c.AutoPull {
// Dispatch pull msg
msg := c.pullTask.WithArgs(context.Background(), localRepoLoc, defaultBranch)
msg.OnceInPeriod(time.Second, pid)
c.queue.Add(msg)
}
return localRepoLoc, nil
}