2021-11-02 18:19:31 +00:00
|
|
|
package commands
|
|
|
|
|
|
|
|
import (
|
2024-06-16 13:28:12 +00:00
|
|
|
"errors"
|
2021-11-02 18:19:31 +00:00
|
|
|
"fmt"
|
2024-01-13 14:39:40 +00:00
|
|
|
"gitlab.com/revalus/grm/internal/config"
|
2021-11-02 18:19:31 +00:00
|
|
|
|
|
|
|
"github.com/go-git/go-git/v5"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Synchronizer struct {
|
|
|
|
workspace string
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewSynchronizer(workspace string) Synchronizer {
|
|
|
|
return Synchronizer{
|
|
|
|
workspace: workspace,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const (
|
|
|
|
syncUpToDate = "up to date"
|
|
|
|
syncFetched = "has been fetched" // Why fetched, instead of updated? To be consistent with git commands :D
|
|
|
|
syncCloned = "has been cloned"
|
|
|
|
)
|
|
|
|
|
|
|
|
func fetchRepository(repo *git.Repository) (bool, error) {
|
|
|
|
err := repo.Fetch(&git.FetchOptions{})
|
|
|
|
|
2024-06-16 13:28:12 +00:00
|
|
|
switch {
|
|
|
|
case errors.Is(err, git.NoErrAlreadyUpToDate):
|
2021-11-02 18:19:31 +00:00
|
|
|
return false, nil
|
2024-06-16 13:28:12 +00:00
|
|
|
case errors.Is(err, git.NoErrAlreadyUpToDate):
|
|
|
|
return false, nil
|
|
|
|
default:
|
|
|
|
return true, nil
|
2021-11-02 18:19:31 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func cloneRepository(destPath string, repoCfg *config.RepositoryConfig) (bool, error) {
|
|
|
|
_, err := git.PlainClone(destPath, false, &git.CloneOptions{
|
|
|
|
URL: repoCfg.Src,
|
|
|
|
})
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return true, nil
|
|
|
|
}
|
|
|
|
|
2021-11-08 17:30:45 +00:00
|
|
|
func (s Synchronizer) Command(repoCfg config.RepositoryConfig) CommandStatus {
|
2021-11-02 18:19:31 +00:00
|
|
|
var err error
|
|
|
|
|
|
|
|
cmdStatus := CommandStatus{
|
|
|
|
Name: repoCfg.Name,
|
|
|
|
Changed: false,
|
|
|
|
Message: "",
|
|
|
|
Error: false,
|
|
|
|
}
|
|
|
|
|
|
|
|
destPath := fmt.Sprintf("%v/%v", s.workspace, repoCfg.Dest)
|
|
|
|
repo, err := git.PlainOpen(destPath)
|
|
|
|
|
2024-06-16 13:28:12 +00:00
|
|
|
if err != nil {
|
|
|
|
if errors.Is(err, git.ErrRepositoryNotExists) {
|
|
|
|
cmdStatus.Changed, err = cloneRepository(destPath, &repoCfg)
|
|
|
|
cmdStatus.Message = syncCloned
|
2021-11-02 18:19:31 +00:00
|
|
|
} else {
|
2024-06-16 13:28:12 +00:00
|
|
|
cmdStatus.Error = true
|
|
|
|
cmdStatus.Message = err.Error()
|
2021-11-02 18:19:31 +00:00
|
|
|
}
|
2021-11-08 17:30:45 +00:00
|
|
|
return cmdStatus
|
2021-11-02 18:19:31 +00:00
|
|
|
}
|
|
|
|
|
2024-06-16 13:28:12 +00:00
|
|
|
cmdStatus.Changed, err = fetchRepository(repo)
|
|
|
|
if cmdStatus.Changed {
|
|
|
|
cmdStatus.Message = syncFetched
|
|
|
|
} else {
|
|
|
|
cmdStatus.Message = syncUpToDate
|
|
|
|
}
|
|
|
|
|
2021-11-02 18:19:31 +00:00
|
|
|
if err != nil {
|
|
|
|
cmdStatus.Error = true
|
|
|
|
cmdStatus.Message = err.Error()
|
|
|
|
}
|
|
|
|
|
2021-11-08 17:30:45 +00:00
|
|
|
return cmdStatus
|
2021-11-02 18:19:31 +00:00
|
|
|
|
|
|
|
}
|