templatefile/pkg/templater/repo-apk.go

85 lines
1.5 KiB
Go
Raw Normal View History

2022-06-27 15:58:37 +02:00
package templater
import (
"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) {
2022-06-29 16:30:20 +02:00
// read the whole file at once
b, err := ioutil.ReadFile(APKConfigFile)
2022-06-29 16:18:28 +02:00
if err != nil {
2022-06-29 16:30:20 +02:00
return err
2022-06-29 16:18:28 +02:00
}
2022-06-29 16:30:20 +02:00
s := string(b)
// //check whether s contains substring text
if strings.Contains(s, hr.URL) {
return true, nil
2022-06-29 16:18:28 +02:00
}
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 {
2022-06-29 16:24:31 +02:00
fmt.Printf("DEBUG %v\n", URLIsPresent)
2022-06-29 16:18:28 +02:00
return nil
} else {
2022-06-29 16:24:31 +02:00
data := fmt.Sprintf("%s\n", hr.URL)
2022-06-29 16:21:56 +02:00
fmt.Printf("DEBUG %v", data)
2022-06-29 16:24:04 +02:00
file, err := os.OpenFile(APKConfigFile, os.O_APPEND|os.O_WRONLY, 0644)
2022-06-29 16:18:28 +02:00
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()
}
}