templatefile/pkg/templater/repo-apk.go

85 lines
1.5 KiB
Go

package templater
import (
"fmt"
"io/ioutil"
"os"
"strings"
"forge.cadoles.com/pcaseiro/templatefile/pkg/utils"
)
var APKConfigFile = "/etc/apk/repositories"
type APKRepository struct {
Repository
}
func (hr *APKRepository) urlIsPresent() (bool, error) {
// read the whole file at once
b, err := ioutil.ReadFile(APKConfigFile)
if err != nil {
return false, err
}
s := string(b)
// //check whether s contains substring text
if strings.Contains(s, hr.URL) {
return true, nil
}
return false, nil
}
func (hr *APKRepository) Add() error {
URLIsPresent, err := hr.urlIsPresent()
if err != nil {
return err
}
if URLIsPresent {
fmt.Printf("DEBUG %v\n", URLIsPresent)
return nil
} else {
data := fmt.Sprintf("%s\n", hr.URL)
fmt.Printf("DEBUG %v", data)
file, err := os.OpenFile(APKConfigFile, os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
return err
}
defer file.Close()
if _, err := file.WriteString(data); err != nil {
return err
}
return nil
}
}
func (hr *APKRepository) Update() error {
if _, stdErr, err := utils.RunSystemCommand("apk", "update"); err != nil {
return fmt.Errorf("%s [%s]", stdErr, err)
}
return nil
}
func (hr *APKRepository) Delete() error {
fileBytes, err := ioutil.ReadFile("/etc/apk/repositories")
if err != nil {
return err
}
lines := strings.Split(string(fileBytes), "\n")
for _, line := range lines {
fmt.Println(line)
}
return nil
}
func (hr *APKRepository) Manage() error {
if hr.Enabled {
return hr.Add()
} else {
return hr.Delete()
}
}