Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions cli/cmd_hash.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package cli

import (
"github.com/spf13/cobra"
)

func (a *App) hashCmd() *cobra.Command {
return &cobra.Command{
Use: "hash <module@version>",
Short: "Look up the checksum database entry for a module version",
Long: `Look up the hash record for a specific module version from sum.golang.org.

Returns the tree hash (h1:...) and go.mod hash (h1:...) that go tools use to
verify downloads. The argument must be in module@version form.`,
Args: cobra.ExactArgs(1),
Example: " gopkg hash github.com/spf13/cobra@v1.8.0\n gopkg hash golang.org/x/net@v0.20.0 -o json",
RunE: func(cmd *cobra.Command, args []string) error {
moduleAt := args[0]
a.progressf("looking up hash for %s...", moduleAt)
info, err := a.client.Hash(cmd.Context(), moduleAt)
if err != nil {
return mapFetchErr(err)
}
return a.render(info)
},
}
}
27 changes: 27 additions & 0 deletions cli/cmd_latest.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package cli

import (
"github.com/spf13/cobra"
)

func (a *App) latestCmd() *cobra.Command {
return &cobra.Command{
Use: "latest <module>",
Short: "Show the latest version of a module",
Long: `Show the latest published version of a Go module from the GOPROXY.

Returns the version string, publish timestamp, and a link to the pkg.go.dev
page for that version.`,
Args: cobra.ExactArgs(1),
Example: " gopkg latest github.com/spf13/cobra\n gopkg latest golang.org/x/net -o json",
RunE: func(cmd *cobra.Command, args []string) error {
module := args[0]
a.progressf("fetching latest version for %s...", module)
info, err := a.client.Latest(cmd.Context(), module)
if err != nil {
return mapFetchErr(err)
}
return a.render(info)
},
}
}
28 changes: 28 additions & 0 deletions cli/cmd_search.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package cli

import (
"github.com/spf13/cobra"
)

func (a *App) searchCmd() *cobra.Command {
return &cobra.Command{
Use: "search <query>",
Short: "Search packages on pkg.go.dev",
Long: `Search pkg.go.dev for Go packages matching query.

Results are sorted by relevance as returned by the site. Each record includes
the import path, a short synopsis, latest version, and publish date.`,
Args: cobra.MinimumNArgs(1),
Example: " gopkg search \"http server\" -n 10\n gopkg search gin -o json",
RunE: func(cmd *cobra.Command, args []string) error {
query := args[0]
n := a.effectiveLimit(10)
a.progressf("searching pkg.go.dev for %q...", query)
pkgs, err := a.client.Search(cmd.Context(), query, n)
if err != nil {
return mapFetchErr(err)
}
return a.renderOrEmpty(pkgs, len(pkgs))
},
}
}
27 changes: 27 additions & 0 deletions cli/cmd_versions.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package cli

import (
"github.com/spf13/cobra"
)

func (a *App) versionsCmd() *cobra.Command {
return &cobra.Command{
Use: "versions <module>",
Short: "List all versions of a module",
Long: `List all known versions of a Go module from the GOPROXY version list.

Versions are returned newest first. Use -n to cap the number of results.`,
Args: cobra.ExactArgs(1),
Example: " gopkg versions github.com/spf13/cobra\n gopkg versions github.com/gin-gonic/gin -n 5 -o table",
RunE: func(cmd *cobra.Command, args []string) error {
module := args[0]
n := a.effectiveLimit(0)
a.progressf("fetching versions for %s...", module)
versions, err := a.client.Versions(cmd.Context(), module, n)
if err != nil {
return mapFetchErr(err)
}
return a.renderOrEmpty(versions, len(versions))
},
}
}
25 changes: 25 additions & 0 deletions cli/output.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package cli

import (
"io"

"github.com/tamnd/pkggodev-cli/pkg/render"
)

// Format aliases so command code reads cleanly.
type Format = render.Format

const (
FormatTable = render.FormatTable
FormatJSON = render.FormatJSON
FormatJSONL = render.FormatJSONL
FormatCSV = render.FormatCSV
FormatTSV = render.FormatTSV
FormatURL = render.FormatURL
FormatRaw = render.FormatRaw
)

// NewRenderer builds a renderer writing to w.
func NewRenderer(w io.Writer, format Format, fields []string, noHeader bool, tmpl string) *render.Renderer {
return render.New(w, format, fields, noHeader, tmpl)
}
127 changes: 122 additions & 5 deletions cli/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@
package cli

import (
"fmt"
"os"

"github.com/mattn/go-isatty"
"github.com/spf13/cobra"
"github.com/tamnd/pkggodev-cli/pkggodev"
)

// Build metadata, set via -ldflags at release time.
Expand All @@ -12,20 +17,132 @@ var (
Date = "unknown"
)

// exit codes.
const (
exitError = 1
exitUsage = 2
exitNoData = 3
)

// ExitError carries a process exit code up to main.
type ExitError struct {
Code int
Err error
}

func (e *ExitError) Error() string {
if e.Err != nil {
return e.Err.Error()
}
return fmt.Sprintf("exit %d", e.Code)
}

func (e *ExitError) Unwrap() error { return e.Err }

func codeError(code int, err error) error { return &ExitError{Code: code, Err: err} }

// App holds shared state threaded through every command.
type App struct {
client *pkggodev.Client
cfg pkggodev.Config

output string
fields []string
noHeader bool
template string
limit int
quiet bool
}

// Root builds the root command and its subtree.
func Root() *cobra.Command {
app := &App{cfg: pkggodev.DefaultConfig()}

root := &cobra.Command{
Use: "gopkg",
Short: "Browse Go packages on pkg.go.dev",
Long: `Browse Go packages on pkg.go.dev
Long: `gopkg reads Go package and module data from pkg.go.dev, proxy.golang.org,
and sum.golang.org. All three are open and require no API key. It returns
records as table, JSON, JSONL, CSV, TSV, or URLs.

This is a fresh scaffold. Add your commands here on top of the pkggodev
library package, then wire them into Root with root.AddCommand.`,
gopkg is an independent tool and is not affiliated with Google or the Go team.`,
SilenceUsage: true,
SilenceErrors: true,
PersistentPreRunE: func(cmd *cobra.Command, _ []string) error {
return app.setup()
},
}

root.AddCommand(newVersionCmd())
// TODO: root.AddCommand(newGetCmd()), etc.
pf := root.PersistentFlags()
pf.StringVarP(&app.output, "output", "o", "auto", "output: table|json|jsonl|csv|tsv|url|raw (auto=table on TTY, jsonl piped)")
pf.StringSliceVar(&app.fields, "fields", nil, "comma-separated columns to include")
pf.BoolVar(&app.noHeader, "no-header", false, "omit the header row in table/csv/tsv")
pf.StringVar(&app.template, "template", "", "Go text/template applied per record")
pf.IntVarP(&app.limit, "limit", "n", 0, "limit number of records (0 = command default)")
pf.BoolVarP(&app.quiet, "quiet", "q", false, "suppress progress on stderr")

pf.DurationVar(&app.cfg.Rate, "delay", app.cfg.Rate, "minimum spacing between requests")
pf.DurationVar(&app.cfg.Timeout, "timeout", app.cfg.Timeout, "per-request timeout")
pf.IntVar(&app.cfg.Retries, "retries", app.cfg.Retries, "retry attempts on 429/5xx")
pf.StringVar(&app.cfg.UserAgent, "user-agent", app.cfg.UserAgent, "User-Agent sent with each request")

root.AddCommand(
app.searchCmd(),
app.versionsCmd(),
app.latestCmd(),
app.hashCmd(),
newVersionCmd(),
)
return root
}

func (a *App) setup() error {
if a.output == "" || a.output == "auto" {
if isatty.IsTerminal(os.Stdout.Fd()) {
a.output = string(FormatTable)
} else {
a.output = string(FormatJSONL)
}
}
if !Format(a.output).Valid() {
return codeError(exitUsage, fmt.Errorf("unknown output format %q", a.output))
}
a.client = pkggodev.NewClient(a.cfg)
return nil
}

func (a *App) render(records any) error {
r := NewRenderer(os.Stdout, Format(a.output), a.fields, a.noHeader, a.template)
return r.Render(records)
}

func (a *App) renderOrEmpty(records any, n int) error {
if err := a.render(records); err != nil {
return err
}
if n == 0 {
return codeError(exitNoData, nil)
}
return nil
}

func (a *App) progressf(format string, args ...any) {
if a.quiet {
return
}
_, _ = fmt.Fprintf(os.Stderr, format+"\n", args...)
}

func (a *App) effectiveLimit(def int) int {
if a.limit > 0 {
return a.limit
}
return def
}

func mapFetchErr(err error) error {
if err == nil {
return nil
}
return codeError(exitError, err)
}
30 changes: 30 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,33 @@ require (
github.com/charmbracelet/fang v1.0.0
github.com/spf13/cobra v1.10.2
)

require (
charm.land/lipgloss/v2 v2.0.0-beta.3.0.20251106193318-19329a3e8410 // indirect
github.com/charmbracelet/colorprofile v0.3.3 // indirect
github.com/charmbracelet/ultraviolet v0.0.0-20251106190538-99ea45596692 // indirect
github.com/charmbracelet/x/ansi v0.11.0 // indirect
github.com/charmbracelet/x/exp/charmtone v0.0.0-20250603201427-c31516f43444 // indirect
github.com/charmbracelet/x/term v0.2.2 // indirect
github.com/charmbracelet/x/termios v0.1.1 // indirect
github.com/charmbracelet/x/windows v0.2.2 // indirect
github.com/clipperhouse/displaywidth v0.4.1 // indirect
github.com/clipperhouse/stringish v0.1.1 // indirect
github.com/clipperhouse/uax29/v2 v2.3.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/lucasb-eyer/go-colorful v1.3.0 // indirect
github.com/mattn/go-isatty v0.0.22 // indirect
github.com/mattn/go-runewidth v0.0.19 // indirect
github.com/muesli/cancelreader v0.2.2 // indirect
github.com/muesli/mango v0.1.0 // indirect
github.com/muesli/mango-cobra v1.2.0 // indirect
github.com/muesli/mango-pflag v0.1.0 // indirect
github.com/muesli/roff v0.1.0 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/spf13/pflag v1.0.9 // indirect
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
golang.org/x/net v0.56.0 // indirect
golang.org/x/sync v0.21.0 // indirect
golang.org/x/sys v0.46.0 // indirect
golang.org/x/text v0.38.0 // indirect
)
Loading
Loading