Skip to content

Instantly share code, notes, and snippets.

@vbatts
Created September 2, 2021 16:28
Show Gist options
  • Save vbatts/dc1756ec0c8fcc648081c05de64262f0 to your computer and use it in GitHub Desktop.
Save vbatts/dc1756ec0c8fcc648081c05de64262f0 to your computer and use it in GitHub Desktop.
dumb simple access to the on-disk gentoo pkg database
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
)
func main() {
var basepath = "/"
if len(os.Args) > 1 && os.Args[1] != "" {
basepath = os.Args[1]
}
db := DB{
Prefix: basepath,
}
pkgs, err := db.ListPkgs()
if err != nil {
log.Fatal(err)
}
buf, err := json.MarshalIndent(pkgs, "", " ")
if err != nil {
log.Fatal(err)
}
fmt.Println(string(buf))
}
type DB struct {
Prefix string
}
func (db *DB) pkgdir() string {
return filepath.Join(db.Prefix, "/var/db/pkg/")
}
func (db *DB) ListPkgs() ([]Pkg, error) {
var pkgs []Pkg
err := filepath.Walk(db.pkgdir(), func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
return nil
}
fpath := strings.TrimPrefix(path, db.pkgdir()+"/")
if !strings.Contains(fpath, "/") {
return nil
}
pkg := Pkg{
db: db,
Name: strings.Split(fpath, "/")[1],
Group: strings.Split(fpath, "/")[0],
}
pkgs = append(pkgs, pkg)
return nil
})
if err != nil {
return nil, err
}
return pkgs, nil
}
type Pkg struct {
db *DB
Group string
Name string
}
func (pkg Pkg) MarshalJSON() ([]byte, error) {
kv := map[string]string{}
kv["name"] = pkg.Name
kv["group"] = pkg.Group
matches, err := filepath.Glob(filepath.Join(pkg.db.pkgdir(), pkg.Group, pkg.Name, "/*"))
if err != nil {
return nil, err
}
mfor:
for _, m := range matches {
k := filepath.Base(m)
if strings.HasSuffix(k, ".bz2") {
continue mfor
}
val, err := ioutil.ReadFile(m)
if err != nil {
continue mfor
}
kv[k] = string(val)
}
return json.Marshal(kv)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment