| Giorgi Lekveishvili | 23ef7f8 | 2023-05-26 11:57:48 +0400 | [diff] [blame^] | 1 | package installer |
| 2 | |
| 3 | import ( |
| 4 | "io/fs" |
| 5 | |
| 6 | "golang.org/x/exp/slices" |
| 7 | |
| 8 | "github.com/go-git/go-billy/v5" |
| 9 | "github.com/go-git/go-billy/v5/util" |
| 10 | ) |
| 11 | |
| 12 | const kustomizationFileName = "kustomization.yaml" |
| 13 | |
| 14 | type AppRepository interface { |
| 15 | Find(name string) (*App, error) |
| 16 | } |
| 17 | |
| 18 | type AppManager struct { |
| 19 | fs billy.Filesystem |
| 20 | config Config |
| 21 | appRepo AppRepository |
| 22 | rootKust *Kustomization |
| 23 | } |
| 24 | |
| 25 | func NewAppManager(fs billy.Filesystem, config Config, appRepo AppRepository) (*AppManager, error) { |
| 26 | rootKustF, err := fs.Open(kustomizationFileName) |
| 27 | if err != nil { |
| 28 | return nil, err |
| 29 | } |
| 30 | defer rootKustF.Close() |
| 31 | rootKust, err := ReadKustomization(rootKustF) |
| 32 | if err != nil { |
| 33 | return nil, err |
| 34 | } |
| 35 | return &AppManager{ |
| 36 | fs, |
| 37 | config, |
| 38 | appRepo, |
| 39 | rootKust, |
| 40 | }, nil |
| 41 | } |
| 42 | |
| 43 | func (m *AppManager) Install(name string) error { |
| 44 | app, err := m.appRepo.Find(name) |
| 45 | if err != nil { |
| 46 | return nil |
| 47 | } |
| 48 | if err := util.RemoveAll(m.fs, name); err != nil { |
| 49 | return err |
| 50 | } |
| 51 | if err := m.fs.MkdirAll(name, fs.ModePerm); err != nil { |
| 52 | return nil |
| 53 | } |
| 54 | appRoot, err := m.fs.Chroot(name) |
| 55 | if err != nil { |
| 56 | return err |
| 57 | } |
| 58 | appKust := NewKustomization() |
| 59 | for _, t := range app.Templates { |
| 60 | out, err := appRoot.Create(t.Name()) |
| 61 | if err != nil { |
| 62 | return err |
| 63 | } |
| 64 | defer out.Close() |
| 65 | if err := t.Execute(out, m.config); err != nil { |
| 66 | return err |
| 67 | } |
| 68 | appKust.Resources = append(appKust.Resources, t.Name()) |
| 69 | } |
| 70 | appKustF, err := appRoot.Create(kustomizationFileName) |
| 71 | if err != nil { |
| 72 | return err |
| 73 | } |
| 74 | defer appKustF.Close() |
| 75 | if err := appKust.Write(appKustF); err != nil { |
| 76 | return err |
| 77 | } |
| 78 | if slices.Contains(m.rootKust.Resources, name) { |
| 79 | return nil |
| 80 | } |
| 81 | m.rootKust.Resources = append(m.rootKust.Resources, name) |
| 82 | rootKustF, err := m.fs.Create(kustomizationFileName) |
| 83 | if err != nil { |
| 84 | return err |
| 85 | } |
| 86 | defer rootKustF.Close() |
| 87 | return m.rootKust.Write(rootKustF) |
| 88 | } |