Documentation
¶
Overview ¶
Package supermarket is a Go client for the Chef Supermarket API.
Read endpoints (cookbooks, search, tools, users, /universe, health) are anonymous; build a Client with no credentials:
c, err := supermarket.NewClient(supermarket.Config{})
if err != nil {
return err
}
cb, _, err := c.Cookbooks.Get(ctx, "apache2")
if err != nil {
return err // errors.Is(err, supermarket.ErrNotFound) for a missing cookbook
}
Write endpoints (share, delete) use the Chef mixlib-authentication signed-header protocol (version 1.1, SHA-1 — the version the public Supermarket accepts). The credentials are the Supermarket username and the RSA private key whose public half is registered on that user's Supermarket profile:
key, err := supermarket.LoadKeyFile("/home/me/.chef/me.pem")
if err != nil {
return err
}
c, err := supermarket.NewClient(supermarket.Config{Username: "me", Key: key})
if err != nil {
return err
}
if _, _, err := c.Cookbooks.Share(ctx, "apache2", "Web Servers", tarball); err != nil {
return err
}
All list and search endpoints share a paginated envelope; the generic Page[T] type carries the items along with Start/Items/Total for cursoring. Loop while Page.HasMore, passing Page.NextStart as the next Start.
The examples in this package show each of these in full.
Example (NotFound) ¶
Supermarket reports a missing resource as 400 with error_code NOT_FOUND rather than 404. Match on the sentinel, not the status code.
package main
import (
"context"
"errors"
"fmt"
"log"
supermarket "github.com/cinc-project/cinc-supermarket-api"
)
func main() {
c, err := supermarket.NewClient(supermarket.Config{})
if err != nil {
log.Fatal(err)
}
_, _, err = c.Cookbooks.Get(context.Background(), "no-such-cookbook")
switch {
case errors.Is(err, supermarket.ErrNotFound):
fmt.Println("cookbook does not exist")
case err != nil:
log.Fatal(err)
}
}
Output:
Example (Pagination) ¶
List returns one page at a time. Page.HasMore reports whether another page exists and Page.NextStart is the offset to request it with; a page with no items always ends the loop, even if Total claims more.
package main
import (
"context"
"fmt"
"log"
supermarket "github.com/cinc-project/cinc-supermarket-api"
)
func main() {
c, err := supermarket.NewClient(supermarket.Config{})
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
opts := supermarket.ListOptions{Items: 100, Order: "most_downloaded"}
for {
page, _, err := c.Cookbooks.List(ctx, opts)
if err != nil {
log.Fatal(err)
}
for _, cb := range page.Items {
fmt.Println(cb.Name)
}
if !page.HasMore() {
break
}
opts.Start = page.NextStart()
}
}
Output:
Index ¶
- Constants
- Variables
- func CompareVersions(a, b string) int
- func LatestVersion(versions []string) string
- func LoadKeyFile(path string) (*rsa.PrivateKey, error)
- func ParseKey(pemBytes []byte) (*rsa.PrivateKey, error)
- func VersionFromURL(s string) string
- type Client
- type Config
- type Contingent
- type Cookbook
- type CookbookMetrics
- type CookbookSummary
- type CookbookVersion
- type CookbooksService
- func (s *CookbooksService) Contingent(ctx context.Context, name string) ([]Contingent, *Response, error)
- func (s *CookbooksService) Delete(ctx context.Context, name string) (*Cookbook, *Response, error)
- func (s *CookbooksService) DeleteVersion(ctx context.Context, name, version string) (*CookbookVersion, *Response, error)
- func (s *CookbooksService) Download(ctx context.Context, name, version string) (io.ReadCloser, *Response, error)
- func (s *CookbooksService) Get(ctx context.Context, name string) (*Cookbook, *Response, error)
- func (s *CookbooksService) GetVersion(ctx context.Context, name, version string) (*CookbookVersion, *Response, error)
- func (s *CookbooksService) List(ctx context.Context, opts ListOptions) (Page[CookbookSummary], *Response, error)
- func (s *CookbooksService) Share(ctx context.Context, name, category string, tarball io.Reader) (*ShareResult, *Response, error)
- type Downloads
- type ErrorResponse
- type Health
- type HealthPostgreSQL
- type HealthRedis
- type HealthService
- type HealthSidekiq
- type HealthSupermarket
- type ListOptions
- type Option
- type Page
- type QualityMetric
- type Response
- type SearchOptions
- type SearchService
- type ShareResult
- type Tool
- type ToolSearchOptions
- type ToolSummary
- type ToolsListOptions
- type ToolsService
- func (s *ToolsService) Get(ctx context.Context, slug string) (*Tool, *Response, error)
- func (s *ToolsService) List(ctx context.Context, opts ToolsListOptions) (Page[ToolSummary], *Response, error)
- func (s *ToolsService) Search(ctx context.Context, opts ToolSearchOptions) (Page[ToolSummary], *Response, error)
- type Universe
- type UniverseEntry
- type UniverseService
- type UniverseVersion
- type User
- type UserCookbooks
- type UserTools
- type UsersService
Examples ¶
Constants ¶
const ( OrderByName = "by_name" OrderRecentlyUpdated = "recently_updated" OrderRecentlyAdded = "recently_added" OrderMostDownloaded = "most_downloaded" OrderMostFollowed = "most_followed" )
Cookbook list orderings for ListOptions.Order.
const ( ToolTypeKnifePlugin = "knife_plugin" ToolTypeOhaiPlugin = "ohai_plugin" ToolTypeChefInfraTool = "chef_infra_tool" ToolTypeChefInfraHandler = "chef_infra_handler" ToolTypeKitchenDriver = "kitchen_driver" ToolTypePowerShellModule = "powershell_module" ToolTypeDSCResource = "dsc_resource" ToolTypeComplianceProfile = "compliance_profile" )
Tool types, for ToolSearchOptions.Type. These are the values Supermarket accepts; it ignores any other.
const DefaultBaseURL = "https://supermarket.chef.io"
DefaultBaseURL is the public Supermarket instance hosted by Progress.
const ToolOrderRecentlyAdded = "recently_added"
ToolOrderRecentlyAdded is the only tool ordering Supermarket supports besides the default (by name).
Variables ¶
var ( ErrNotFound = errors.New("supermarket: not found") ErrForbidden = errors.New("supermarket: forbidden") ErrInvalidData = errors.New("supermarket: invalid data") ErrUnauthenticatedWrite = errors.New("supermarket: write requires Username and Key") // ErrInvalidArgument is returned locally, without contacting the server, // when a caller passes a blank value for a required path segment such as // a cookbook name or version. ErrInvalidArgument = errors.New("supermarket: invalid argument") // ErrConflict matches a 409, which Supermarket returns when deleting the // only remaining version of a cookbook. ErrConflict = errors.New("supermarket: conflict") // ErrRateLimited matches a 429 that outlasted the client's retries. ErrRateLimited = errors.New("supermarket: rate limited") )
Sentinel errors for use with errors.Is. Supermarket reports a missing resource as 404 with error_code NOT_FOUND; Unwrap maps the error_code (and, failing that, the status) to ErrNotFound, so match on the sentinel rather than the status code.
Functions ¶
func CompareVersions ¶
CompareVersions compares two cookbook version strings using a relaxed semver ordering and returns -1, 0, or 1 in the usual sense (a<b, a==b, a>b).
Numeric base segments are compared numerically (so 1.10.0 > 1.2.0), missing trailing segments are treated as zero (1.0 == 1.0.0), and an empty string sorts below everything. A base segment that is not numeric is compared lexically and ranks above a numeric one, so a malformed version such as 1.0.x is ordered consistently rather than collapsing onto 1.0.0. A clean release outranks any pre-release of the same base; pre-release identifiers are compared per semver §11 (dot-separated, all-numeric identifiers compared numerically and ranking below alphanumeric ones, with a larger set of fields winning when all earlier ones are equal). Build metadata (everything after '+') is ignored. Supermarket versions are overwhelmingly plain "X.Y.Z", so this avoids pulling in a full semver dependency while still ordering the occasional pre-release sensibly.
Example ¶
package main
import (
"fmt"
supermarket "github.com/cinc-project/cinc-supermarket-api"
)
func main() {
fmt.Println(supermarket.CompareVersions("1.10.0", "1.2.0"))
fmt.Println(supermarket.CompareVersions("1.0", "1.0.0"))
fmt.Println(supermarket.CompareVersions("2.0.0-rc.1", "2.0.0"))
}
Output: 1 0 -1
func LatestVersion ¶
LatestVersion returns the highest version in versions per CompareVersions, or "" when versions is empty.
Example ¶
package main
import (
"fmt"
supermarket "github.com/cinc-project/cinc-supermarket-api"
)
func main() {
fmt.Println(supermarket.LatestVersion([]string{"1.2.0", "1.10.0", "1.9.3", "2.0.0-beta"}))
}
Output: 2.0.0-beta
func LoadKeyFile ¶
func LoadKeyFile(path string) (*rsa.PrivateKey, error)
LoadKeyFile reads and parses an RSA private key from a file path.
Example ¶
Write endpoints are signed with the RSA key registered on the user's Supermarket profile. A client without Username and Key returns ErrUnauthenticatedWrite from them without contacting the server.
package main
import (
"context"
"log"
supermarket "github.com/cinc-project/cinc-supermarket-api"
)
func main() {
key, err := supermarket.LoadKeyFile("/home/me/.chef/me.pem")
if err != nil {
log.Fatal(err)
}
c, err := supermarket.NewClient(supermarket.Config{
Username: "me",
Key: key,
})
if err != nil {
log.Fatal(err)
}
if _, _, err := c.Cookbooks.DeleteVersion(context.Background(), "my-cookbook", "0.1.0"); err != nil {
log.Fatal(err)
}
}
Output:
func ParseKey ¶
func ParseKey(pemBytes []byte) (*rsa.PrivateKey, error)
ParseKey parses a PEM-encoded RSA private key (PKCS#1 or PKCS#8).
func VersionFromURL ¶
VersionFromURL extracts the version segment from a Supermarket version URL like https://supermarket.chef.io/api/v1/cookbooks/nginx/versions/12_0_4 (optionally followed by /download or a query), returning "12.0.4". Supermarket encodes dots as underscores in these paths; either form is tolerated, so a bare "12.0.4" or "12_0_4" passes through unchanged.
Input that is not a version returns "". Previously the underscore-to-dot rewrite was applied unconditionally to whatever was left after trimming, which turned "my_cookbook" into "my.cookbook" and a URL with no /versions/ segment into "https:" — plausible-looking values that were never versions.
Example ¶
package main
import (
"fmt"
supermarket "github.com/cinc-project/cinc-supermarket-api"
)
func main() {
fmt.Println(supermarket.VersionFromURL("https://supermarket.chef.io/api/v1/cookbooks/nginx/versions/12_0_4"))
fmt.Println(supermarket.VersionFromURL("https://supermarket.chef.io/api/v1/cookbooks/nginx/versions/12_0_4/download"))
fmt.Printf("%q\n", supermarket.VersionFromURL("https://supermarket.chef.io/api/v1/cookbooks/nginx"))
}
Output: 12.0.4 12.0.4 ""
Types ¶
type Client ¶
type Client struct {
// Services.
Cookbooks *CookbooksService
Search *SearchService
Tools *ToolsService
Users *UsersService
Universe *UniverseService
Health *HealthService
// contains filtered or unexported fields
}
Client is a Chef Supermarket API client. It is safe for concurrent use.
A Client with no Username/Key may call only the anonymous read endpoints; write endpoints (share, delete) return ErrUnauthenticatedWrite without contacting the server.
type Config ¶
type Config struct {
BaseURL string // http or https URL; defaults to DefaultBaseURL
Username string // Supermarket username (write endpoints only)
Key *rsa.PrivateKey // RSA private key registered on the user's profile (write endpoints only)
}
Config holds the parameters for constructing a Client. Username and Key are only needed for the write endpoints (share / delete); read endpoints work with an empty Config.
type Contingent ¶ added in v1.0.0
type Contingent struct {
Name string `json:"name"` // name of the dependent cookbook
Version string `json:"version"` // version of the dependent cookbook
URL string `json:"url"` // API URL of that cookbook version
}
Contingent is one cookbook version that depends on the cookbook passed to Cookbooks.Contingent.
type Cookbook ¶
type Cookbook struct {
Name string `json:"name"`
Maintainer string `json:"maintainer"`
Description string `json:"description"`
Category string `json:"category"`
LatestVersion string `json:"latest_version"`
ExternalURL string `json:"external_url"`
SourceURL string `json:"source_url"`
IssuesURL string `json:"issues_url"`
AverageRating *float64 `json:"average_rating"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Deprecated bool `json:"deprecated"`
// Replacement is the API URL of the cookbook suggested in place of a
// deprecated one. Supermarket sends it only when Deprecated is true and
// a replacement was named; otherwise it is empty.
Replacement string `json:"replacement"`
UpForAdoption bool `json:"up_for_adoption"`
Versions []string `json:"versions"`
Metrics CookbookMetrics `json:"metrics"`
}
Cookbook is the full cookbook representation returned by GET /cookbooks/:name.
type CookbookMetrics ¶
type CookbookMetrics struct {
Downloads Downloads `json:"downloads"`
Followers int `json:"followers"`
Collaborators int `json:"collaborators"`
}
CookbookMetrics is the metrics sub-object of a Cookbook.
type CookbookSummary ¶
type CookbookSummary struct {
Name string `json:"cookbook_name"`
Description string `json:"cookbook_description"`
URL string `json:"cookbook"`
Maintainer string `json:"cookbook_maintainer"`
}
CookbookSummary is the lighter shape returned by list and search.
type CookbookVersion ¶
type CookbookVersion struct {
Version string `json:"version"`
License string `json:"license"`
TarballSize int64 `json:"tarball_file_size"`
AverageRating *float64 `json:"average_rating"`
PublishedAt time.Time `json:"published_at"`
Cookbook string `json:"cookbook"` // URL of the cookbook
File string `json:"file"` // URL of the tarball
Dependencies map[string]string `json:"dependencies"`
// Supports maps platform name to a version constraint. The API
// returns this under the "supports" key (mirroring metadata.rb).
Supports map[string]string `json:"supports"`
QualityMetrics []QualityMetric `json:"quality_metrics"`
}
CookbookVersion is the full version representation returned by GET /cookbooks/:name/versions/:version.
type CookbooksService ¶
type CookbooksService struct {
// contains filtered or unexported fields
}
CookbooksService accesses the /cookbooks endpoints.
func (*CookbooksService) Contingent ¶
func (s *CookbooksService) Contingent(ctx context.Context, name string) ([]Contingent, *Response, error)
Contingent returns the cookbook versions that depend on the named cookbook. A cookbook nothing depends on yields an empty slice.
func (*CookbooksService) Delete ¶
Delete removes an entire cookbook from Supermarket. The caller must own the cookbook (or be a Supermarket admin).
func (*CookbooksService) DeleteVersion ¶
func (s *CookbooksService) DeleteVersion(ctx context.Context, name, version string) (*CookbookVersion, *Response, error)
DeleteVersion removes a single version of a cookbook.
func (*CookbooksService) Download ¶
func (s *CookbooksService) Download(ctx context.Context, name, version string) (io.ReadCloser, *Response, error)
Download fetches the gzipped tarball for a cookbook version. The caller owns closing the returned body. Like GetVersion the version may be "latest" or any Semver form.
The download is not subject to the client's total-transaction timeout, which would otherwise truncate a large tarball mid-read. Bound it with ctx.
func (*CookbooksService) Get ¶
Get returns the full record for a single cookbook by name.
Example ¶
Read endpoints are anonymous, so a zero Config talks to the public Supermarket without credentials.
package main
import (
"context"
"fmt"
"log"
"time"
supermarket "github.com/cinc-project/cinc-supermarket-api"
)
func main() {
c, err := supermarket.NewClient(supermarket.Config{})
if err != nil {
log.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
cb, _, err := c.Cookbooks.Get(ctx, "apache2")
if err != nil {
log.Fatal(err)
}
fmt.Println(cb.Name, cb.LatestVersion)
}
Output:
func (*CookbooksService) GetVersion ¶
func (s *CookbooksService) GetVersion(ctx context.Context, name, version string) (*CookbookVersion, *Response, error)
GetVersion returns a single cookbook version. The version may be "latest" or a Semver string in either dotted ("1.2.3") or underscore ("1_2_3") form; the dotted form is converted automatically.
func (*CookbooksService) List ¶
func (s *CookbooksService) List(ctx context.Context, opts ListOptions) (Page[CookbookSummary], *Response, error)
List paginates the cookbook index.
func (*CookbooksService) Share ¶
func (s *CookbooksService) Share(ctx context.Context, name, category string, tarball io.Reader) (*ShareResult, *Response, error)
Share uploads a new cookbook version. tarball is the gzipped tar of the cookbook directory (must contain metadata.json at its root); category is the Supermarket category string (e.g. "Web Servers"). Requires Username and Key on the Client.
Supermarket answers a successful share with only the cookbook's API URL, returned as ShareResult.URI; fetch the cookbook with Get for its details.
type Downloads ¶
Downloads splits a cookbook's download counter into the all-time total and a per-version breakdown.
type ErrorResponse ¶
type ErrorResponse struct {
Method string // request method
Path string // request path
StatusCode int // HTTP status code
Code string // server-supplied error_code (e.g. NOT_FOUND)
Messages []string // server-supplied error_messages
}
ErrorResponse describes a non-2xx response from Supermarket.
func (*ErrorResponse) Error ¶
func (e *ErrorResponse) Error() string
func (*ErrorResponse) Unwrap ¶
func (e *ErrorResponse) Unwrap() error
Unwrap maps the error_code (preferred) or HTTP status to a sentinel error for errors.Is.
type Health ¶
type Health struct {
Status string `json:"status"`
Supermarket HealthSupermarket `json:"supermarket"`
PostgreSQL HealthPostgreSQL `json:"postgresql"`
Sidekiq HealthSidekiq `json:"sidekiq"`
Redis HealthRedis `json:"redis"`
// Features maps each feature flag (tools, fieri, announcement, github,
// no_crawl) to whether it is enabled.
Features map[string]bool `json:"features"`
}
Health is the status object returned by /health (and the /status alias). Status is "ok" when PostgreSQL, Redis and Sidekiq are all reachable. A subsystem that could not be reached reports only its Status ("unreachable" or "unknown"), leaving its metrics zero.
type HealthPostgreSQL ¶ added in v1.0.0
type HealthPostgreSQL struct {
Status string `json:"status"`
WaitingOnLock int `json:"waiting_on_lock"`
Connections int `json:"connections"`
}
HealthPostgreSQL describes the database connection.
type HealthRedis ¶ added in v1.0.0
type HealthRedis struct {
Status string `json:"status"`
UptimeInSeconds int64 `json:"uptime_in_seconds"`
ConnectedClients int `json:"connected_clients"`
UsedMemory int64 `json:"used_memory"`
UsedMemoryPeak int64 `json:"used_memory_peak"`
}
HealthRedis describes the Redis server.
type HealthService ¶
type HealthService struct {
// contains filtered or unexported fields
}
HealthService accesses the health / metrics endpoints.
type HealthSidekiq ¶ added in v1.0.0
type HealthSidekiq struct {
Status string `json:"status"`
Latency float64 `json:"latency"` // seconds the oldest queued job has waited
QueuedJobs int `json:"queued_jobs"`
ScheduledJobs int `json:"scheduled_jobs"`
RetryableJobs int `json:"retryable_jobs"`
DeadJobs int `json:"dead_jobs"`
TotalProcessed int64 `json:"total_processed"`
TotalFailed int64 `json:"total_failed"`
ActiveWorkers int `json:"active_workers"`
}
HealthSidekiq describes the background job queue.
type HealthSupermarket ¶ added in v1.0.0
type HealthSupermarket struct {
ExpiredOCIDTokens int `json:"expired_ocid_tokens"`
}
HealthSupermarket holds application-level health figures.
type ListOptions ¶
type ListOptions struct {
Start int
Items int
// Order, when set, is one of the Order* constants. The server sorts
// by name when it is empty or unrecognized, and always lists
// deprecated cookbooks after the rest.
Order string
// User, when set, restricts the result set to cookbooks owned by
// that Supermarket username.
User string
// Platforms, when set, restricts the result set to cookbooks whose
// versions declare support for any of these platforms (e.g. "debian").
Platforms []string
}
ListOptions configures GET /cookbooks.
type Option ¶
type Option func(*options)
Option customizes a Client.
func WithHTTPClient ¶
WithHTTPClient sets a custom *http.Client. A nil client is ignored.
func WithMaxRetries ¶
WithMaxRetries sets the retry count for idempotent (GET) requests.
func WithRetryBackoff ¶ added in v1.0.0
WithRetryBackoff sets the base delay between retries of an idempotent (GET) request. Waits grow exponentially from this value and are jittered. Zero disables waiting entirely; a negative value is ignored.
func WithRootCAs ¶ added in v1.0.0
WithRootCAs sets the certificate authorities the client trusts when verifying the server, replacing the system pool. Use it to reach a Supermarket whose certificate is issued by a private or internal CA without disabling verification. A nil pool is ignored.
Like WithSkipTLSVerify it requires the client's transport to be an *http.Transport; combining it with a custom RoundTripper is a NewClient error.
Example ¶
A private Supermarket whose certificate is issued by an internal CA is reached by trusting that CA, which keeps certificate verification on.
package main
import (
"context"
"crypto/x509"
"fmt"
"log"
"os"
supermarket "github.com/cinc-project/cinc-supermarket-api"
)
func main() {
pem, err := os.ReadFile("/etc/ssl/internal-ca.pem")
if err != nil {
log.Fatal(err)
}
pool := x509.NewCertPool()
if !pool.AppendCertsFromPEM(pem) {
log.Fatal("no certificates found in internal-ca.pem")
}
c, err := supermarket.NewClient(
supermarket.Config{BaseURL: "https://supermarket.example.internal"},
supermarket.WithRootCAs(pool),
)
if err != nil {
log.Fatal(err)
}
cb, _, err := c.Cookbooks.Get(context.Background(), "apache2")
if err != nil {
log.Fatal(err)
}
fmt.Println(cb.Name, cb.LatestVersion)
}
Output:
func WithSkipTLSVerify ¶
WithSkipTLSVerify disables TLS certificate verification, leaving the connection open to interception. It is off by default and meant for local testing only; to reach a Supermarket whose certificate comes from a private CA, use WithRootCAs, which keeps verification on.
It requires the client's transport to be an *http.Transport, since that is where the TLS config lives. Combining it with a custom RoundTripper is a NewClient error rather than a silent downgrade to http.DefaultTransport.
type Page ¶
type Page[T any] struct { Start int `json:"start"` Total int `json:"total"` Items []T `json:"items"` }
Page is the envelope every Supermarket list/search response uses. Items carries the actual result rows; Start is the offset of the first.
Total is only as good as the server makes it. Supermarket reports the number of cookbooks on the whole server for Search.Cookbooks and for a Cookbooks.List filtered by User or Platforms, and the size of the returned page for Tools.Search. Only an unfiltered Cookbooks.List or Tools.List reports a true total. A page with no items is the reliable end-of-results signal.
type QualityMetric ¶
type QualityMetric struct {
Name string `json:"name"`
Failed bool `json:"failed"`
Feedback string `json:"feedback"`
}
QualityMetric is one entry in a cookbook version's quality_metrics array: the Fieri/cookstyle evaluation results shown on the version page (collaborator count, version tag, cookstyle, no-binaries, etc.).
type Response ¶
Response wraps the raw HTTP response returned by an API call. It embeds *http.Response, so StatusCode, Header and Body are read directly off it.
For the decoding calls (everything returning a parsed type) the body has already been consumed and closed by the time the caller sees the Response, so it is useful only for its status and headers.
The streaming calls — Universe.GetStream and Cookbooks.Download — are the exception: they hand back the still-open body as their first return value, and Response.Body is that same ReadCloser. Closing it is the caller's job either way.
type SearchOptions ¶
SearchOptions configures a search query. Q is required; Start and Items follow the same convention as ListOptions.
type SearchService ¶
type SearchService struct {
// contains filtered or unexported fields
}
SearchService accesses the fuzzy-search endpoints.
func (*SearchService) Cookbooks ¶
func (s *SearchService) Cookbooks(ctx context.Context, opts SearchOptions) (Page[CookbookSummary], *Response, error)
Cookbooks runs a fuzzy search over cookbook name, description, and maintainer.
type ShareResult ¶ added in v1.0.0
type ShareResult struct {
// https://supermarket.chef.io/api/v1/cookbooks/apache2.
URI string `json:"uri"`
}
ShareResult is the response to a successful Cookbooks.Share.
type Tool ¶
type Tool struct {
Name string `json:"name"`
Slug string `json:"slug"`
Type string `json:"type"`
SourceURL string `json:"source_url"`
Description string `json:"description"`
Instructions string `json:"instructions"` // markdown
Owner string `json:"owner"`
UpForAdoption bool `json:"up_for_adoption"`
}
Tool is the full record returned by GET /tools/:slug.
type ToolSearchOptions ¶ added in v1.0.0
type ToolSearchOptions struct {
Q string // query; empty matches every tool
Start int
Items int
Type string // one of the ToolType* constants; empty means any type
Order string // ToolOrderRecentlyAdded, or empty for by name
}
ToolSearchOptions configures GET /tools-search.
type ToolSummary ¶
type ToolSummary struct {
Name string `json:"tool_name"`
Type string `json:"tool_type"`
SourceURL string `json:"tool_source_url"`
Description string `json:"tool_description"`
Owner string `json:"tool_owner"`
URL string `json:"tool"`
}
ToolSummary is the lighter shape returned by list and search.
type ToolsListOptions ¶
type ToolsListOptions struct {
Start int
Items int
// Order, when set, is ToolOrderRecentlyAdded.
Order string
}
ToolsListOptions configures GET /tools.
type ToolsService ¶
type ToolsService struct {
// contains filtered or unexported fields
}
ToolsService accesses the /tools endpoints.
func (*ToolsService) List ¶
func (s *ToolsService) List(ctx context.Context, opts ToolsListOptions) (Page[ToolSummary], *Response, error)
List paginates the tools index.
func (*ToolsService) Search ¶
func (s *ToolsService) Search(ctx context.Context, opts ToolSearchOptions) (Page[ToolSummary], *Response, error)
Search runs a fuzzy search over the tools index.
Supermarket reports Total for this endpoint as the number of items in the returned page, not the number of matches, so Page.HasMore cannot tell whether more pages exist. Request the next Start until a page comes back empty.
type Universe ¶
type Universe map[string]map[string]UniverseVersion
Universe is the full dependency graph of every cookbook version on the server. It is keyed by cookbook name then by version string.
type UniverseEntry ¶ added in v1.0.0
type UniverseEntry struct {
Cookbook string
Version string
UniverseVersion
}
UniverseEntry is one cookbook version from the universe.
type UniverseService ¶
type UniverseService struct {
// contains filtered or unexported fields
}
UniverseService accesses the /universe endpoint.
func (*UniverseService) Entries ¶ added in v1.0.0
func (s *UniverseService) Entries(ctx context.Context) iter.Seq2[UniverseEntry, error]
Entries decodes the universe incrementally and yields one entry per cookbook version, so memory stays flat however large the document is. The request is sent when iteration starts, not when Entries is called.
It is built on GetStream: there is no total-transaction timeout, so bound the download with ctx. A request error, an error response, a malformed or truncated document, or ctx being cancelled mid-stream yields a single (zero, err) and ends the iteration; a clean end means the whole document was read. The response body is closed when iteration ends, including when the caller breaks out of the loop early.
func (*UniverseService) Get ¶
Get returns the entire universe in one shot. The payload can be tens of megabytes; prefer Entries when memory pressure matters.
func (*UniverseService) GetStream ¶
func (s *UniverseService) GetStream(ctx context.Context) (io.ReadCloser, *Response, error)
GetStream returns the universe body as a raw io.ReadCloser so the caller can decode it incrementally with json.Decoder. The caller owns closing the body. Most callers want Entries, which does that decoding and yields one UniverseEntry per cookbook version.
Streaming responses are not subject to the client's total-transaction timeout — a multi-megabyte universe would otherwise be truncated mid-read. Bound the download with ctx.
Example ¶
GetStream hands back the raw /universe body so it can be decoded one cookbook at a time instead of holding the whole graph in memory. Bound the download with ctx: the client's total-transaction timeout does not apply to streams.
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"time"
supermarket "github.com/cinc-project/cinc-supermarket-api"
)
func main() {
c, err := supermarket.NewClient(supermarket.Config{})
if err != nil {
log.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
body, _, err := c.Universe.GetStream(ctx)
if err != nil {
log.Fatal(err)
}
defer body.Close()
dec := json.NewDecoder(body)
if _, err := dec.Token(); err != nil { // opening '{'
log.Fatal(err)
}
for dec.More() {
tok, err := dec.Token() // cookbook name
if err != nil {
log.Fatal(err)
}
var versions map[string]supermarket.UniverseVersion
if err := dec.Decode(&versions); err != nil {
log.Fatal(err)
}
fmt.Println(tok.(string), len(versions))
}
if _, err := dec.Token(); err != nil { // closing '}'
log.Fatal(err)
}
}
Output:
type UniverseVersion ¶
type UniverseVersion struct {
// LocationType is "opscode": Supermarket keeps the legacy value because
// Berkshelf matches on it.
LocationType string `json:"location_type"`
// LocationPath is the API base URL the version is served from.
LocationPath string `json:"location_path"`
// DownloadURL is the URL of this version's tarball.
DownloadURL string `json:"download_url"`
Dependencies map[string]string `json:"dependencies"`
}
UniverseVersion is one entry in the universe graph.
type User ¶
type User struct {
Username string `json:"username"`
Name string `json:"name"`
Company string `json:"company"`
GitHub []string `json:"github"`
Twitter string `json:"twitter"`
Slack string `json:"slack"`
Cookbooks UserCookbooks `json:"cookbooks"`
Tools UserTools `json:"tools"`
}
User is the profile representation returned by GET /users/:username.
type UserCookbooks ¶
type UserCookbooks struct {
Owns map[string]string `json:"owns"`
Collaborates map[string]string `json:"collaborates"`
Follows map[string]string `json:"follows"`
}
UserCookbooks groups the cookbook relationships on a user profile.
Supermarket serializes each relationship as a JSON object mapping the cookbook name to its API URL (e.g. {"apache2": ".../cookbooks/apache2"}), NOT as an array of cookbook records — and it omits a relationship key entirely when it's empty, so an absent group decodes to a nil map. The contract suite (contract_live_test.go) is what pins this shape against the live API.