templatefile/pkg/templater/repo-apk.go

107 lines
1.8 KiB
Go

package templater
import (
"bufio"
"fmt"
"io/ioutil"
"log"
"os"
"strings"
"forge.cadoles.com/pcaseiro/templatefile/pkg/utils"
)
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) {
log.Printf("\tRepository %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
} else {
log.Printf("Repository %s added\n", hr.Name)
}
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
}
// FIXME
func (hr *APKRepository) Delete() error {
fileBytes, err := ioutil.ReadFile(APKConfigFile)
if err != nil {
return err
}
lines := strings.Split(string(fileBytes), "\n")
for _, line := range lines {
fmt.Printf("DEBUG TODO %s", line)
}
return nil
}
func (hr *APKRepository) Manage() error {
if utils.DryRun {
return nil
} else {
if hr.Enabled {
if err := hr.Add(); err != nil {
return err
}
log.Println("\tUpdating apk repositories")
return hr.Update()
} else {
return hr.Delete()
}
}
}