nix-amer/internal/pkg/loader.go

72 lines
1.5 KiB
Go
Raw Normal View History

package pkg
import (
"encoding/json"
"errors"
"os"
"os/exec"
"path/filepath"
)
var ErrUnknownDistribution = errors.New("unknown linux distribution")
var ErrNoCandidateInstalled = errors.New("no package-manager candidate installed")
var ErrNoDriverFound = errors.New("no driver found for the package manager")
func Load(_distro string) (PackageManager, error) {
// 1. load config file
driverTable := filepath.Join(os.Getenv("GOPATH"), "src/git.xdrm.io/xdrm-brackets/nix-amer/meta/pkg-drivers.json")
file, err := os.Open(driverTable)
if err != nil {
return nil, err
}
defer file.Close()
// 2. Parse json
table := make(map[string][]string)
decoder := json.NewDecoder(file)
if err := decoder.Decode(&table); err != nil {
return nil, err
}
decoder = nil
// 3. Get available package-manager list for distro
available, exists := table[_distro]
if !exists || len(available) < 1 {
return nil, ErrUnknownDistribution
}
// 4. Check each available package-manager in order
selected := ""
for _, current := range available {
if exec.Command("which", current).Run() == nil {
selected = current
break
}
}
// no candidate installed
if len(selected) < 1 {
return nil, ErrNoCandidateInstalled
}
// 5. Instanciate
switch selected {
case "apt-get":
return new(Apt), nil
case "apk":
return new(Apk), nil
case "eopkg":
return new(Eopkg), nil
case "pacman":
return new(Pacman), nil
case "dnf":
return new(Dnf), nil
case "yum":
return new(Yum), nil
}
return nil, ErrNoDriverFound
}