Skip to content

Commit 9977811

Browse files
committed
Add a ListInstalled function
I've needed at times to list the packages that are currently listed on a system. Search("") is equivalent to that, but since we have List() which is equivalent to Search("*"), I figured this might be handy to have as well.
1 parent 0d7233b commit 9977811

File tree

1 file changed

+17
-1
lines changed

1 file changed

+17
-1
lines changed

apt.go

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import (
2222
"bufio"
2323
"bytes"
2424
"fmt"
25+
"log"
2526
"os/exec"
2627
"regexp"
2728
"strconv"
@@ -44,15 +45,29 @@ func List() ([]*Package, error) {
4445
return Search("*")
4546
}
4647

48+
// ListInstalled returns a list of packages installed on the system.
49+
func ListInstalled() ([]*Package, error) {
50+
return Search("")
51+
}
52+
4753
// Search list packages available in the system that match the search
4854
// pattern
4955
func Search(pattern string) ([]*Package, error) {
50-
cmd := exec.Command("dpkg-query", "-W", "-f=${Package}\t${Architecture}\t${db:Status-Status}\t${Version}\t${Installed-Size}\t${Binary:summary}\n", pattern)
56+
args := []string{
57+
"-W",
58+
"-f=${Package}\t${Architecture}\t${db:Status-Status}\t${Version}\t${Installed-Size}\t${Binary:summary}\n",
59+
}
60+
if pattern != "" {
61+
args = append(args, pattern)
62+
}
63+
64+
cmd := exec.Command("dpkg-query", args...)
5165

5266
out, err := cmd.CombinedOutput()
5367
if err != nil {
5468
// Avoid returning an error if the list is empty
5569
if bytes.Contains(out, []byte("no packages found matching")) {
70+
log.Print(string(out))
5671
return []*Package{}, nil
5772
}
5873
return nil, fmt.Errorf("running dpkg-query: %s - %s", err, out)
@@ -69,6 +84,7 @@ func parseDpkgQueryOutput(out []byte) []*Package {
6984
size, err := strconv.Atoi(data[4])
7085
if err != nil {
7186
// Ignore error
87+
log.Print(err)
7288
size = 0
7389
}
7490
res = append(res, &Package{

0 commit comments

Comments
 (0)