templatefile/pkg/templater/repo-apk.go

97 lines
1.6 KiB
Go
Raw Normal View History

2022-06-27 15:58:37 +02:00
package templater
import (
2022-06-29 16:18:28 +02:00
"bufio"
2022-06-27 15:58:37 +02:00
"fmt"
"io/ioutil"
"os"
"strings"
"forge.cadoles.com/pcaseiro/templatefile/pkg/utils"
)
2022-06-29 16:18:28 +02:00
var APKConfigFile = "/etc/apk/repositories"
2022-06-27 15:58:37 +02:00
type APKRepository struct {
2022-06-29 16:18:28 +02:00
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) {
return true, nil
}
line++
}
if err := scanner.Err(); err != nil {
return false, err
}
return false, nil
2022-06-27 15:58:37 +02:00
}
func (hr *APKRepository) Add() error {
2022-06-29 16:18:28 +02:00
URLIsPresent, err := hr.urlIsPresent()
2022-06-27 15:58:37 +02:00
if err != nil {
return err
}
2022-06-29 16:18:28 +02:00
if URLIsPresent {
return nil
} else {
data := fmt.Sprintf("%s", hr.URL)
2022-06-29 16:21:56 +02:00
fmt.Printf("DEBUG %v", data)
2022-06-29 16:18:28 +02:00
file, err := os.OpenFile("/etc/apk/repositories", 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
2022-06-27 15:58:37 +02:00
}
2022-06-29 16:18:28 +02:00
2022-06-27 15:58:37 +02:00
}
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")
2022-06-29 12:13:32 +02:00
for _, line := range lines {
fmt.Println(line)
2022-06-27 15:58:37 +02:00
}
return nil
}
2022-06-29 16:18:28 +02:00
2022-06-27 15:58:37 +02:00
func (hr *APKRepository) Manage() error {
if hr.Enabled {
return hr.Add()
} else {
return hr.Delete()
}
}