blob: 271a1c421c9099492f7344f9ba0b6314730e306f [file] [log] [blame]
Giorgi Lekveishvili3550b432023-06-09 19:37:51 +04001package installer
2
3import (
4 "io/fs"
5 "path/filepath"
6 "time"
7
8 "github.com/go-git/go-git/v5"
9 "github.com/go-git/go-git/v5/plumbing/object"
10 "golang.org/x/crypto/ssh"
11)
12
13type RepoIO interface {
14 ReadKustomization(path string) (*Kustomization, error)
15 WriteKustomization(path string, kust Kustomization) error
16 CommitAndPush(message string) error
17}
18
19type repoIO struct {
20 repo *git.Repository
21 signer ssh.Signer
22}
23
24func NewRepoIO(repo *git.Repository, signer ssh.Signer) RepoIO {
25 return &repoIO{
26 repo,
27 signer,
28 }
29}
30
31func (r *repoIO) ReadKustomization(path string) (*Kustomization, error) {
32 wt, err := r.repo.Worktree()
33 if err != nil {
34 return nil, err
35 }
36 inp, err := wt.Filesystem.Open(path)
37 if err != nil {
38 return nil, err
39 }
40 defer inp.Close()
41 return ReadKustomization(inp)
42}
43
44func (r *repoIO) WriteKustomization(path string, kust Kustomization) error {
45 wt, err := r.repo.Worktree()
46 if err != nil {
47 return err
48 }
49 if err := wt.Filesystem.MkdirAll(filepath.Dir(path), fs.ModePerm); err != nil {
50 return err
51 }
52 out, err := wt.Filesystem.Create(path)
53 if err != nil {
54 return err
55 }
56 defer out.Close()
57 return kust.Write(out)
58}
59
60func (r *repoIO) CommitAndPush(message string) error {
61 wt, err := r.repo.Worktree()
62 if err != nil {
63 return err
64 }
65 if err := wt.AddGlob("*"); err != nil {
66 return err
67 }
68 if _, err := wt.Commit(message, &git.CommitOptions{
69 Author: &object.Signature{
70 Name: "pcloud-installer",
71 When: time.Now(),
72 },
73 }); err != nil {
74 return err
75 }
76 return r.repo.Push(&git.PushOptions{
77 RemoteName: "soft", // TODO(giolekva): configurable
78 Auth: auth(r.signer),
79 })
80}