about summary refs log tree commit diff stats
path: root/internal/vcs/repository.go
blob: 6e8f07917085550db800e0fab5c85348b80d7d23 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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/go-git/go-git/v5/plumbing"
	"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.Info("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 && !errors.Is(err, git.NoErrAlreadyUpToDate) {
		return false, err
	}

	ref, err := r.repo.Reference(plumbing.ReferenceName("refs/remotes/origin/"+cfg.Branch), true)
	if err != nil {
		return false, err
	}

	log.Info("applying changes", "hash", ref.Hash().String())
	err = r.repo.Merge(*ref, git.MergeOptions{
		Strategy: git.FastForwardMerge,
	})

	return true, nil
}