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