81 lines
1.7 KiB
Go
81 lines
1.7 KiB
Go
package pkg
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"strings"
|
|
)
|
|
|
|
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() (PackageManager, error) {
|
|
|
|
// 1. get distro name
|
|
out, err := exec.Command("lsb_release", "-is").Output()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
distro := strings.ToLower(strings.Trim(string(out), " \n\t"))
|
|
|
|
// 2. 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()
|
|
|
|
// 3. Parse json
|
|
table := make(map[string][]string)
|
|
decoder := json.NewDecoder(file)
|
|
if err := decoder.Decode(&table); err != nil {
|
|
return nil, err
|
|
}
|
|
decoder = nil
|
|
|
|
// 4. Get available package-manager list for distro
|
|
available, exists := table[distro]
|
|
if !exists || len(available) < 1 {
|
|
return nil, ErrUnknownDistribution
|
|
}
|
|
|
|
// 5. 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
|
|
}
|
|
|
|
// 6. 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
|
|
|
|
}
|