package vcs import ( "os" "website/internal/config" "website/internal/log" "github.com/go-git/go-git/v5" gitc "github.com/go-git/go-git/v5/config" "github.com/pkg/errors" ) type Config struct { LocalPath string RemoteURL config.URL Branch string `conf:"default:main"` } type Repository struct { repo *git.Repository } func CloneOrUpdate(cfg *Config) (*Repository, error) { gr, err := git.PlainClone(cfg.LocalPath, false, &git.CloneOptions{ URL: cfg.RemoteURL.String(), Progress: os.Stdout, }) if err != nil { if !errors.Is(err, git.ErrRepositoryAlreadyExists) { return nil, err } gr, err = git.PlainOpen(cfg.LocalPath) if err != nil { return nil, err } repo := &Repository{ repo: gr, } _, err := repo.Update(cfg) if err != nil { return nil, err } return repo, nil } return &Repository{ repo: gr, }, nil } func (r *Repository) Update(cfg *Config) (bool, error) { log.Debug("updating repository") err := r.repo.Fetch(&git.FetchOptions{ RefSpecs: []gitc.RefSpec{ gitc.RefSpec( "+refs/heads/" + cfg.Branch + ":refs/remotes/origin/" + cfg.Branch, ), }, }) if err != nil { if errors.Is(err, git.NoErrAlreadyUpToDate) { log.Debug("no changes to pull") return false, nil } return false, err } head, err := r.repo.Head() if err != nil { return false, err } log.Debug("applying changes", "head", head.Name()) err = r.repo.Merge(*head, git.MergeOptions{ Strategy: git.FastForwardMerge, }) return true, nil }