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, _ := supermarket.NewClient(supermarket.Config{})
cb, _, _ := c.Cookbooks.Get(context.Background(), "apache2")
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, _ := supermarket.LoadKeyFile("/home/me/.chef/me.pem")
c, _ := supermarket.NewClient(supermarket.Config{
Username: "me",
Key: key,
})
c.Cookbooks.Share(ctx, "apache2", "Web Servers", tarball)
All list and search endpoints share a paginated envelope; the generic Page[T] type carries the items along with Start/Items/Total for cursoring.
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 Cookbook
- type CookbookMetrics
- type CookbookSummary
- type CookbookVersion
- type CookbooksService
- func (s *CookbooksService) Contingent(ctx context.Context, name string) ([]CookbookSummary, *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) (*Cookbook, *Response, error)
- type Downloads
- type ErrorResponse
- type Health
- type HealthService
- type ListOptions
- type Option
- type Page
- type QualityMetric
- type Response
- type SearchOptions
- type SearchService
- type Tool
- 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 SearchOptions) (Page[ToolSummary], *Response, error)
- type Universe
- type UniverseService
- type UniverseVersion
- type User
- type UserCookbooks
- type UserTools
- type UsersService
Constants ¶
const DefaultBaseURL = "https://supermarket.chef.io"
DefaultBaseURL is the public Supermarket instance hosted by Progress.
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") )
Sentinel errors for use with errors.Is. Supermarket returns 400 for "not found" rather than 404; Unwrap normalizes both into ErrNotFound using the response's error_code field.
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.
func LatestVersion ¶
LatestVersion returns the highest version in versions per CompareVersions, or "" when versions is empty.
func LoadKeyFile ¶
func LoadKeyFile(path string) (*rsa.PrivateKey, error)
LoadKeyFile reads and parses an RSA private key from a file path.
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.
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 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"`
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) ([]CookbookSummary, *Response, error)
Contingent returns cookbooks that depend on the named cookbook.
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) 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) (*Cookbook, *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.
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"`
}
Health is the small status object returned by /health (and the /status alias).
type HealthService ¶
type HealthService struct {
// contains filtered or unexported fields
}
HealthService accesses the health / metrics endpoints.
type ListOptions ¶
type ListOptions struct {
Start int
Items int
// Order, when set, is one of: recently_updated, recently_added,
// most_downloaded, most_followed.
Order string
// User, when set, restricts the result set to cookbooks owned by
// that Supermarket username.
User 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 WithSkipTLSVerify ¶
WithSkipTLSVerify disables TLS certificate verification (testing only).
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 and Total describe where this slice sits inside the full result set.
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. The body has already been consumed and closed by the time the caller sees the Response.
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 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"`
}
Tool is the full record returned by GET /tools/:slug.
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 one of: recently_added.
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 SearchOptions) (Page[ToolSummary], *Response, error)
Search runs a fuzzy search over the tools index.
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 UniverseService ¶
type UniverseService struct {
// contains filtered or unexported fields
}
UniverseService accesses the /universe endpoint.
func (*UniverseService) Get ¶
Get returns the entire universe in one shot. The payload can be tens of megabytes; prefer GetStream 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.
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.
type UniverseVersion ¶
type UniverseVersion struct {
LocationPath string `json:"location_path"`
LocationType string `json:"location_type"` // "supermarket"
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.