diff options
author | Alan Pearce | 2024-06-25 17:07:47 +0200 |
---|---|---|
committer | Alan Pearce | 2024-06-25 17:07:47 +0200 |
commit | cd1125a213d742b5a89e8b60f0c7aafef13b8783 (patch) | |
tree | b3271d6883c15eea11252d76b3a7c4c6626e1ded /internal/vcs | |
parent | 83a4eef89b9906d8ad90411e9b256da6dab07b55 (diff) | |
download | website-cd1125a213d742b5a89e8b60f0c7aafef13b8783.tar.lz website-cd1125a213d742b5a89e8b60f0c7aafef13b8783.tar.zst website-cd1125a213d742b5a89e8b60f0c7aafef13b8783.zip |
fetch and build site on server start
Diffstat (limited to 'internal/vcs')
-rw-r--r-- | internal/vcs/repository.go | 65 |
1 files changed, 65 insertions, 0 deletions
diff --git a/internal/vcs/repository.go b/internal/vcs/repository.go new file mode 100644 index 0000000..cc9bdaa --- /dev/null +++ b/internal/vcs/repository.go @@ -0,0 +1,65 @@ +package vcs + +import ( + "os" + "website/internal/config" + + "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) { + 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) { + return false, nil + } + return false, err + } + return true, nil +} |