zood/apt_linux.go

73 lines
1.8 KiB
Go
Raw Permalink Normal View History

package main
import (
"bufio"
"fmt"
"os/exec"
"strings"
2024-11-15 18:11:52 -06:00
"go.wit.com/log"
)
// getPackageList returns the list of installed packages based on the distro
2024-11-15 18:11:52 -06:00
func getPackageList(distro string) (map[string]string, error) {
var cmd *exec.Cmd
// Run the appropriate command based on the detected distribution
switch distro {
case "ubuntu", "debian":
2024-11-15 18:11:52 -06:00
return dpkgQuery()
case "fedora", "centos", "rhel":
cmd = exec.Command("rpm", "-qa")
case "arch", "manjaro":
cmd = exec.Command("pacman", "-Q")
default:
return nil, fmt.Errorf("unsupported distribution: %s", distro)
}
// Capture the command's output
output, err := cmd.CombinedOutput()
if err != nil {
return nil, fmt.Errorf("error running command: %v", err)
}
2024-11-15 18:11:52 -06:00
// todo: Split the output into lines and return
lines := strings.Split(string(output), "\n")
2024-11-15 18:11:52 -06:00
log.Info("output had", len(lines), "lines")
return nil, nil
}
func dpkgQuery() (map[string]string, error) {
// Run the dpkg-query command to list installed packages and versions
cmd := exec.Command("dpkg-query", "-W", "-f=${Package} ${Version}\n")
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
// Start the command execution
if err := cmd.Start(); err != nil {
return nil, err
}
defer cmd.Wait()
// Create a map to store package names and versions
installedPackages := make(map[string]string)
// Use a scanner to read the output of the command line by line
scanner := bufio.NewScanner(stdout)
for scanner.Scan() {
line := scanner.Text()
// Split each line into package name and version
parts := strings.SplitN(line, " ", 2)
if len(parts) == 2 {
packageName := parts[0]
version := parts[1]
installedPackages[packageName] = version
}
}
// Return the map with package names and versions
return installedPackages, scanner.Err()
}