73 lines
1.5 KiB
Go
73 lines
1.5 KiB
Go
package patches
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"regexp"
|
|
|
|
"github.com/sirupsen/logrus"
|
|
"gopkg.in/yaml.v2"
|
|
)
|
|
|
|
type Patch struct {
|
|
Name string
|
|
Targets []string
|
|
Before string
|
|
After string
|
|
}
|
|
|
|
type Patches []*Patch
|
|
|
|
func NewPatchFromFile(filePath string) (*Patch, error){
|
|
var patch Patch
|
|
logrus.Infof("reading a new patch file: %s", filePath)
|
|
patchFile, err := os.ReadFile(filePath)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if err := yaml.Unmarshal(patchFile, &patch); err != nil {
|
|
return nil, err
|
|
}
|
|
return &patch, nil
|
|
}
|
|
|
|
func(p *Patch) Apply(chartDir string) error {
|
|
logrus.Infof("Applying patch: %s", p.Name)
|
|
if len(p.Before) > 0 {
|
|
beforeCompiled, err := regexp.Compile(p.Before)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
for _, target := range p.Targets {
|
|
fullTarget := fmt.Sprintf("%s/%s", chartDir, target)
|
|
file, err := os.ReadFile(fullTarget)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
newfile := beforeCompiled.ReplaceAll(file, []byte(p.After))
|
|
err = os.WriteFile(fullTarget, newfile, os.ModePerm)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
} else {
|
|
for _, target := range p.Targets {
|
|
fullTarget := fmt.Sprintf("%s/%s", chartDir, target)
|
|
f, err := os.OpenFile(fullTarget, os.O_APPEND|os.O_CREATE|os.O_WRONLY, os.ModePerm)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer f.Close()
|
|
if _, err := f.Write([]byte(p.After + "\n")); err != nil {
|
|
return err
|
|
}
|
|
if err := f.Close(); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
}
|