summaryrefslogtreecommitdiff
path: root/apt_linux.go
blob: 5d6eb162c41515ae9bfc03c8f6daaf67db58f950 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package main

import (
	"bufio"
	"fmt"
	"os"
	"os/exec"
	"runtime"
	"strings"
)

// detectDistro returns the Linux distribution name (if possible)
func detectDistro() string {
	// Check if we're on Linux
	if runtime.GOOS != "linux" {
		return ""
	}

	// Try to read /etc/os-release to determine the distro
	file, err := os.Open("/etc/os-release")
	if err != nil {
		return ""
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		line := scanner.Text()
		if strings.HasPrefix(line, "ID=") {
			parts := strings.SplitN(line, "=", 2)
			if len(parts) == 2 {
				return strings.Trim(parts[1], `"`)
			}
		}
	}
	return ""
}

// getPackageList returns the list of installed packages based on the distro
func getPackageList(distro string) ([]string, error) {
	var cmd *exec.Cmd

	// Run the appropriate command based on the detected distribution
	switch distro {
	case "ubuntu", "debian":
		cmd = exec.Command("dpkg-query", "-W", "-f=${Package} ${Version}\n")
	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)
	}

	// Split the output into lines and return
	lines := strings.Split(string(output), "\n")
	return lines, nil
}