about summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorBen Morrison <ben@gbmor.dev>2020-05-10 01:34:03 -0400
committerBen Morrison <ben@gbmor.dev>2020-05-10 01:34:03 -0400
commit037d58e2b92faca8eaec6f06ae4249f334f3b9aa (patch)
tree8a2e41d8466994d5b94ea3829381b81d7348e0e3
parent1bc03b1738df7573d56d68ccbb3754e2d655389f (diff)
downloadapi-037d58e2b92faca8eaec6f06ae4249f334f3b9aa.tar.gz
added endpoint to query for all installed packages
-rw-r--r--cache.go2
-rw-r--r--pkgs.go40
2 files changed, 37 insertions, 5 deletions
diff --git a/cache.go b/cache.go
index 283f698..fde11ee 100644
--- a/cache.go
+++ b/cache.go
@@ -87,6 +87,8 @@ func (cache *cacheWrapper) bap(requestPath string) error {
 		bytes, err = uptimeQuery(format)
 	case "usercount":
 		bytes, err = userCountQuery(format)
+	case "pkgs":
+		bytes, err = pkgsQuery(format)
 	default:
 		if requestPath == "/" {
 			bytes, err = ioutil.ReadFile("web/index.txt")
diff --git a/pkgs.go b/pkgs.go
index 991ba53..9674916 100644
--- a/pkgs.go
+++ b/pkgs.go
@@ -1,10 +1,40 @@
 package main
 
-import "net/http"
+import (
+	"fmt"
+	"os/exec"
+	"strings"
+)
 
-// Pkgs handles the /<format>/pkgs endpoint.
-// Sends a list of installed packages.
-func Pkgs(w http.ResponseWriter, r *http.Request, format string) error {
+// Returns a list of packages installed on the system
+func pkgsQuery(format string) ([]byte, error) {
+	raw, err := exec.Command("pkg_info", "-a").Output()
+	if err != nil {
+		return nil, err
+	}
 
-	return nil
+	if format == "plain" {
+		return raw, nil
+	}
+
+	json := `{
+	"packages": [`
+	rawlines := strings.Split(string(raw), "\n")
+	for _, line := range rawlines {
+		split := strings.Fields(line)
+		if len(split) < 2 {
+			continue
+		}
+		desc := strings.Join(split[1:], " ")
+		json = fmt.Sprintf(`%s
+		{
+			"package": "%s",
+			"description": "%s"
+		},`, json, split[0], desc)
+	}
+	json = fmt.Sprintf(`%s
+	]
+}
+`, json[:len(json)-1])
+	return []byte(json), nil
 }