feat(pkg): add JSON output for package search
All checks were successful
Security Scan / security (push) Successful in 19s

Co-Authored-By: Virgil <virgil@lethean.io>
This commit is contained in:
Virgil 2026-03-31 19:59:57 +00:00
parent 7fda1cf320
commit 10de071704
6 changed files with 144 additions and 13 deletions

View file

@ -1,11 +1,13 @@
package pkgcmd package pkgcmd
import ( import (
"cmp"
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"os/exec" "os/exec"
"path/filepath" "path/filepath"
"slices"
"strings" "strings"
"forge.lthn.ai/core/go-i18n" "forge.lthn.ai/core/go-i18n"
@ -74,6 +76,10 @@ func runPkgList(format string) error {
return nil return nil
} }
slices.SortFunc(allRepos, func(a, b *repos.Repo) int {
return cmp.Compare(a.Name, b.Name)
})
var entries []pkgListEntry var entries []pkgListEntry
var installed, missing int var installed, missing int
for _, r := range allRepos { for _, r := range allRepos {

View file

@ -26,6 +26,7 @@ var (
searchType string searchType string
searchLimit int searchLimit int
searchRefresh bool searchRefresh bool
searchFormat string
) )
// addPkgSearchCommand adds the 'pkg search' command. // addPkgSearchCommand adds the 'pkg search' command.
@ -45,7 +46,7 @@ func addPkgSearchCommand(parent *cobra.Command) {
if limit == 0 { if limit == 0 {
limit = 50 limit = 50
} }
return runPkgSearch(org, pattern, searchType, limit, searchRefresh) return runPkgSearch(org, pattern, searchType, limit, searchRefresh, searchFormat)
}, },
} }
@ -54,13 +55,14 @@ func addPkgSearchCommand(parent *cobra.Command) {
searchCmd.Flags().StringVar(&searchType, "type", "", i18n.T("cmd.pkg.search.flag.type")) searchCmd.Flags().StringVar(&searchType, "type", "", i18n.T("cmd.pkg.search.flag.type"))
searchCmd.Flags().IntVar(&searchLimit, "limit", 0, i18n.T("cmd.pkg.search.flag.limit")) searchCmd.Flags().IntVar(&searchLimit, "limit", 0, i18n.T("cmd.pkg.search.flag.limit"))
searchCmd.Flags().BoolVar(&searchRefresh, "refresh", false, i18n.T("cmd.pkg.search.flag.refresh")) searchCmd.Flags().BoolVar(&searchRefresh, "refresh", false, i18n.T("cmd.pkg.search.flag.refresh"))
searchCmd.Flags().StringVar(&searchFormat, "format", "table", "Output format: table or json")
parent.AddCommand(searchCmd) parent.AddCommand(searchCmd)
} }
type ghRepo struct { type ghRepo struct {
Name string `json:"name"`
FullName string `json:"fullName"` FullName string `json:"fullName"`
Name string `json:"name"`
Description string `json:"description"` Description string `json:"description"`
Visibility string `json:"visibility"` Visibility string `json:"visibility"`
UpdatedAt string `json:"updatedAt"` UpdatedAt string `json:"updatedAt"`
@ -72,7 +74,29 @@ type ghLanguage struct {
Name string `json:"name"` Name string `json:"name"`
} }
func runPkgSearch(org, pattern, repoType string, limit int, refresh bool) error { type pkgSearchEntry struct {
Name string `json:"name"`
FullName string `json:"fullName,omitempty"`
Description string `json:"description,omitempty"`
Visibility string `json:"visibility,omitempty"`
StargazerCount int `json:"stargazerCount,omitempty"`
PrimaryLanguage string `json:"primaryLanguage,omitempty"`
UpdatedAt string `json:"updatedAt,omitempty"`
Updated string `json:"updated,omitempty"`
}
type pkgSearchReport struct {
Format string `json:"format"`
Org string `json:"org"`
Pattern string `json:"pattern"`
Type string `json:"type,omitempty"`
Limit int `json:"limit"`
Cached bool `json:"cached"`
Count int `json:"count"`
Repos []pkgSearchEntry `json:"repos"`
}
func runPkgSearch(org, pattern, repoType string, limit int, refresh bool, format string) error {
// Initialize cache in workspace .core/ directory // Initialize cache in workspace .core/ directory
var cacheDir string var cacheDir string
if regPath, err := repos.FindRegistry(coreio.Local); err == nil { if regPath, err := repos.FindRegistry(coreio.Local); err == nil {
@ -92,8 +116,6 @@ func runPkgSearch(org, pattern, repoType string, limit int, refresh bool) error
if c != nil && !refresh { if c != nil && !refresh {
if found, err := c.Get(cacheKey, &ghRepos); found && err == nil { if found, err := c.Get(cacheKey, &ghRepos); found && err == nil {
fromCache = true fromCache = true
age := c.Age(cacheKey)
fmt.Printf("%s %s %s\n", dimStyle.Render(i18n.T("cmd.pkg.search.cache_label")), org, dimStyle.Render(fmt.Sprintf("(%s ago)", age.Round(time.Second))))
} }
} }
@ -103,20 +125,24 @@ func runPkgSearch(org, pattern, repoType string, limit int, refresh bool) error
return errors.New(i18n.T("cmd.pkg.error.gh_not_authenticated")) return errors.New(i18n.T("cmd.pkg.error.gh_not_authenticated"))
} }
if os.Getenv("GH_TOKEN") != "" { if os.Getenv("GH_TOKEN") != "" && !strings.EqualFold(format, "json") {
fmt.Printf("%s %s\n", dimStyle.Render(i18n.Label("note")), i18n.T("cmd.pkg.search.gh_token_warning")) fmt.Printf("%s %s\n", dimStyle.Render(i18n.Label("note")), i18n.T("cmd.pkg.search.gh_token_warning"))
fmt.Printf("%s %s\n\n", dimStyle.Render(""), i18n.T("cmd.pkg.search.gh_token_unset")) fmt.Printf("%s %s\n\n", dimStyle.Render(""), i18n.T("cmd.pkg.search.gh_token_unset"))
} }
if !strings.EqualFold(format, "json") {
fmt.Printf("%s %s... ", dimStyle.Render(i18n.T("cmd.pkg.search.fetching_label")), org) fmt.Printf("%s %s... ", dimStyle.Render(i18n.T("cmd.pkg.search.fetching_label")), org)
}
cmd := exec.Command("gh", "repo", "list", org, cmd := exec.Command("gh", "repo", "list", org,
"--json", "name,description,visibility,updatedAt,stargazerCount,primaryLanguage", "--json", "fullName,name,description,visibility,updatedAt,stargazerCount,primaryLanguage",
"--limit", fmt.Sprintf("%d", limit)) "--limit", fmt.Sprintf("%d", limit))
output, err := cmd.CombinedOutput() output, err := cmd.CombinedOutput()
if err != nil { if err != nil {
if !strings.EqualFold(format, "json") {
fmt.Println() fmt.Println()
}
errStr := strings.TrimSpace(string(output)) errStr := strings.TrimSpace(string(output))
if strings.Contains(errStr, "401") || strings.Contains(errStr, "Bad credentials") { if strings.Contains(errStr, "401") || strings.Contains(errStr, "Bad credentials") {
return errors.New(i18n.T("cmd.pkg.error.auth_failed")) return errors.New(i18n.T("cmd.pkg.error.auth_failed"))
@ -132,8 +158,10 @@ func runPkgSearch(org, pattern, repoType string, limit int, refresh bool) error
_ = c.Set(cacheKey, ghRepos) _ = c.Set(cacheKey, ghRepos)
} }
if !strings.EqualFold(format, "json") {
fmt.Printf("%s\n", successStyle.Render("✓")) fmt.Printf("%s\n", successStyle.Render("✓"))
} }
}
// Filter by glob pattern and type // Filter by glob pattern and type
var filtered []ghRepo var filtered []ghRepo
@ -148,6 +176,10 @@ func runPkgSearch(org, pattern, repoType string, limit int, refresh bool) error
} }
if len(filtered) == 0 { if len(filtered) == 0 {
if strings.EqualFold(format, "json") {
report := buildPkgSearchReport(org, pattern, repoType, limit, fromCache, filtered)
return printPkgSearchJSON(report)
}
fmt.Println(i18n.T("cmd.pkg.search.no_repos_found")) fmt.Println(i18n.T("cmd.pkg.search.no_repos_found"))
return nil return nil
} }
@ -156,6 +188,15 @@ func runPkgSearch(org, pattern, repoType string, limit int, refresh bool) error
return cmp.Compare(a.Name, b.Name) return cmp.Compare(a.Name, b.Name)
}) })
if strings.EqualFold(format, "json") {
report := buildPkgSearchReport(org, pattern, repoType, limit, fromCache, filtered)
return printPkgSearchJSON(report)
}
if fromCache && !strings.EqualFold(format, "json") {
age := c.Age(cacheKey)
fmt.Printf("%s %s %s\n", dimStyle.Render(i18n.T("cmd.pkg.search.cache_label")), org, dimStyle.Render(fmt.Sprintf("(%s ago)", age.Round(time.Second))))
}
renderPkgSearchResults(filtered) renderPkgSearchResults(filtered)
fmt.Println() fmt.Println()
@ -190,6 +231,44 @@ func renderPkgSearchResults(repos []ghRepo) {
} }
} }
func buildPkgSearchReport(org, pattern, repoType string, limit int, cached bool, repos []ghRepo) pkgSearchReport {
report := pkgSearchReport{
Format: "json",
Org: org,
Pattern: pattern,
Type: repoType,
Limit: limit,
Cached: cached,
Count: len(repos),
Repos: make([]pkgSearchEntry, 0, len(repos)),
}
for _, r := range repos {
report.Repos = append(report.Repos, pkgSearchEntry{
Name: r.Name,
FullName: r.FullName,
Description: r.Description,
Visibility: r.Visibility,
StargazerCount: r.StargazerCount,
PrimaryLanguage: strings.TrimSpace(r.PrimaryLanguage.Name),
UpdatedAt: r.UpdatedAt,
Updated: formatPkgSearchUpdatedAt(r.UpdatedAt),
})
}
return report
}
func printPkgSearchJSON(report pkgSearchReport) error {
out, err := json.MarshalIndent(report, "", " ")
if err != nil {
return fmt.Errorf("%s: %w", i18n.T("i18n.fail.format", "search results"), err)
}
fmt.Println(string(out))
return nil
}
func formatPkgSearchMetadata(r ghRepo) string { func formatPkgSearchMetadata(r ghRepo) string {
var parts []string var parts []string

View file

@ -1,6 +1,7 @@
package pkgcmd package pkgcmd
import ( import (
"encoding/json"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -22,3 +23,44 @@ func TestResolvePkgSearchPattern_Good(t *testing.T) {
assert.Equal(t, "*", got) assert.Equal(t, "*", got)
}) })
} }
func TestBuildPkgSearchReport_Good(t *testing.T) {
repos := []ghRepo{
{
FullName: "host-uk/core-api",
Name: "core-api",
Description: "REST API framework",
Visibility: "public",
UpdatedAt: "2026-03-30T12:00:00Z",
StargazerCount: 42,
PrimaryLanguage: ghLanguage{
Name: "Go",
},
},
}
report := buildPkgSearchReport("host-uk", "core-*", "api", 50, true, repos)
assert.Equal(t, "json", report.Format)
assert.Equal(t, "host-uk", report.Org)
assert.Equal(t, "core-*", report.Pattern)
assert.Equal(t, "api", report.Type)
assert.Equal(t, 50, report.Limit)
assert.True(t, report.Cached)
assert.Equal(t, 1, report.Count)
requireRepo := report.Repos
if assert.Len(t, requireRepo, 1) {
assert.Equal(t, "core-api", requireRepo[0].Name)
assert.Equal(t, "host-uk/core-api", requireRepo[0].FullName)
assert.Equal(t, "REST API framework", requireRepo[0].Description)
assert.Equal(t, "public", requireRepo[0].Visibility)
assert.Equal(t, 42, requireRepo[0].StargazerCount)
assert.Equal(t, "Go", requireRepo[0].PrimaryLanguage)
assert.Equal(t, "2026-03-30T12:00:00Z", requireRepo[0].UpdatedAt)
assert.NotEmpty(t, requireRepo[0].Updated)
}
out, err := json.Marshal(report)
assert.NoError(t, err)
assert.Contains(t, string(out), `"format":"json"`)
}

View file

@ -19,6 +19,7 @@ core pkg search [flags]
| `--type` | Filter by type in name (mod, services, plug, website) | | `--type` | Filter by type in name (mod, services, plug, website) |
| `--limit` | Max results (default: 50) | | `--limit` | Max results (default: 50) |
| `--refresh` | Bypass cache and fetch fresh data | | `--refresh` | Bypass cache and fetch fresh data |
| `--format` | Output format (`table` or `json`) |
## Examples ## Examples
@ -40,6 +41,9 @@ core pkg search --refresh
# Combine filters # Combine filters
core pkg search --pattern "core-*" --type mod --limit 20 core pkg search --pattern "core-*" --type mod --limit 20
# JSON output for automation
core pkg search --format json
``` ```
## Output ## Output

2
go.mod
View file

@ -15,7 +15,7 @@ require (
) )
require ( require (
forge.lthn.ai/core/go v0.3.2 // indirect forge.lthn.ai/core/go v0.3.3 // indirect
forge.lthn.ai/core/go-inference v0.1.7 // indirect forge.lthn.ai/core/go-inference v0.1.7 // indirect
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
github.com/charmbracelet/colorprofile v0.4.3 // indirect github.com/charmbracelet/colorprofile v0.4.3 // indirect

4
go.sum
View file

@ -1,7 +1,7 @@
dappco.re/go/core v0.4.7 h1:KmIA/2lo6rl1NMtLrKqCWfMlUqpDZYH3q0/d10dTtGA= dappco.re/go/core v0.4.7 h1:KmIA/2lo6rl1NMtLrKqCWfMlUqpDZYH3q0/d10dTtGA=
dappco.re/go/core v0.4.7/go.mod h1:f2/tBZ3+3IqDrg2F5F598llv0nmb/4gJVCFzM5geE4A= dappco.re/go/core v0.4.7/go.mod h1:f2/tBZ3+3IqDrg2F5F598llv0nmb/4gJVCFzM5geE4A=
forge.lthn.ai/core/go v0.3.2 h1:VB9pW6ggqBhe438cjfE2iSI5Lg+62MmRbaOFglZM+nQ= forge.lthn.ai/core/go v0.3.3 h1:kYYZ2nRYy0/Be3cyuLJspRjLqTMxpckVyhb/7Sw2gd0=
forge.lthn.ai/core/go v0.3.2/go.mod h1:f7/zb3Labn4ARfwTq5Bi2AFHY+uxyPHozO+hLb54eFo= forge.lthn.ai/core/go v0.3.3/go.mod h1:Cp4ac25pghvO2iqOu59t1GyngTKVOzKB5/VPdhRi9CQ=
forge.lthn.ai/core/go-i18n v0.1.7 h1:aHkAoc3W8fw3RPNvw/UszQbjyFWXHszzbZgty3SwyAA= forge.lthn.ai/core/go-i18n v0.1.7 h1:aHkAoc3W8fw3RPNvw/UszQbjyFWXHszzbZgty3SwyAA=
forge.lthn.ai/core/go-i18n v0.1.7/go.mod h1:0VDjwtY99NSj2iqwrI09h5GUsJeM9s48MLkr+/Dn4G8= forge.lthn.ai/core/go-i18n v0.1.7/go.mod h1:0VDjwtY99NSj2iqwrI09h5GUsJeM9s48MLkr+/Dn4G8=
forge.lthn.ai/core/go-inference v0.1.7 h1:9Dy6v03jX5ZRH3n5iTzlYyGtucuBIgSe+S7GWvBzx9Q= forge.lthn.ai/core/go-inference v0.1.7 h1:9Dy6v03jX5ZRH3n5iTzlYyGtucuBIgSe+S7GWvBzx9Q=