templatefile/pkg/templater/repo-apk.go

100 lines
1.7 KiB
Go
Raw Normal View History

package templater
import (
"bufio"
"fmt"
"io/ioutil"
2022-06-29 17:02:30 +02:00
"log"
"os"
"strings"
"forge.cadoles.com/pcaseiro/templatefile/pkg/utils"
2022-06-29 17:02:30 +02:00
"google.golang.org/appengine/log"
)
var APKConfigFile = "/etc/apk/repositories"
type APKRepository struct {
Repository
}
func (hr *APKRepository) urlIsPresent() (bool, error) {
f, err := os.Open(APKConfigFile)
if err != nil {
return false, err
}
defer f.Close()
// Splits on newlines by default.
scanner := bufio.NewScanner(f)
line := 1
for scanner.Scan() {
if strings.Contains(scanner.Text(), hr.URL) {
2022-06-29 17:02:30 +02:00
log.Printf("Repository %s already present\n", hr.Name)
return true, nil
}
line++
}
if err := scanner.Err(); err != nil {
return false, err
}
return false, nil
}
func (hr *APKRepository) Add() error {
URLIsPresent, err := hr.urlIsPresent()
if err != nil {
return err
}
if URLIsPresent {
return nil
} else {
data := fmt.Sprintf("%s\n", hr.URL)
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 {
2022-06-29 17:00:24 +02:00
if err := hr.Add(); err != nil {
return err
}
return hr.Update()
} else {
return hr.Delete()
}
}