Documentation
¶
Overview ¶
Package openapi provides OpenAPI 3.x and Swagger 2.0 specification parsing with CLI extensions support.
The openapi package parses and validates OpenAPI/Swagger specifications, automatically converting Swagger 2.0 to OpenAPI 3.0, and extracts all x-cli-* extensions for CLI generation. It supports loading specs from files, URLs, and embedded resources.
Supported Formats ¶
- OpenAPI 3.0.x (JSON/YAML)
- OpenAPI 3.1.x (JSON/YAML)
- Swagger 2.0 (auto-converted to OpenAPI 3.0)
CLI Extensions ¶
The parser extracts all x-cli-* extensions:
- x-cli-command: Override command name
- x-cli-aliases: Command aliases
- x-cli-hidden: Hide from help output
- x-cli-examples: Usage examples
- x-cli-auth: Authentication requirements
- x-cli-workflow: Multi-step workflows
- x-cli-async: Async operation polling
- x-cli-output: Output formatting
- x-cli-confirmation: Confirm before execution
- x-cli-preflight: Pre-execution checks
- x-cli-secret: Mark field as sensitive
- x-cli-deprecation: Deprecation metadata
Example Usage ¶
// Create parser
parser := openapi.NewParser()
// Parse from file
spec, err := parser.ParseFile(ctx, "openapi.yaml")
if err != nil {
log.Fatal(err)
}
// Get API info
info := spec.GetInfo()
fmt.Printf("API: %s v%s\n", info.Title, info.Version)
// Get operations
operations, _ := spec.GetOperations()
for _, op := range operations {
fmt.Printf("%s %s - %s\n", op.Method, op.Path, op.Summary)
}
Swagger 2.0 Conversion ¶
Swagger 2.0 specs are automatically detected and converted:
spec, _ := parser.Parse(ctx, swaggerData) // Returns OpenAPI 3.0 ParsedSpec fmt.Println(spec.OriginalVersion) // "2.0"
Validation ¶
By default, specs are validated during parsing. Disable with:
parser := openapi.NewParser() parser.DisableValidation = true
The parser supports remote $ref resolution when enabled:
parser.AllowRemoteRefs = true
All extensions are fully documented at: https://github.com/CliForge/cliforge/blob/main/docs/openapi-extensions.md
Index ¶
- func FormatChangelog(changes []*DetectedChange) string
- func GroupBySeverity(changes []*DetectedChange) map[ChangeSeverity][]*DetectedChange
- func GroupByType(changes []*DetectedChange) map[ChangeType][]*DetectedChange
- func IsBreaking(changes []*DetectedChange) bool
- type AuthConfig
- type AuthSettings
- type BackoffConfig
- type BrandingConfig
- type CLIAsync
- type CLIConfig
- type CLIConfirmation
- type CLIFileInput
- type CLIFlag
- type CLIInteractive
- type CLIOutput
- type CLIPlugin
- type CLIPreflight
- type CLIProgress
- type CLISecret
- type CLIWatch
- type CLIWorkflow
- type CacheSettings
- type CachedSpec
- type Change
- type ChangeDetector
- type ChangeSeverity
- type ChangeType
- type ChangelogEntry
- type ColorScheme
- type Deprecation
- type DeprecationInfo
- type DetectedChange
- type ExitCondition
- type FeatureSettings
- type InteractivePrompt
- type LoadOptions
- type Loader
- func (l *Loader) InvalidateCache(ctx context.Context, specURL string) error
- func (l *Loader) LoadFromData(ctx context.Context, data []byte) (*ParsedSpec, error)
- func (l *Loader) LoadFromFile(ctx context.Context, path string) (*ParsedSpec, error)
- func (l *Loader) LoadFromReader(ctx context.Context, r io.Reader) (*ParsedSpec, error)
- func (l *Loader) LoadFromURL(ctx context.Context, specURL string, options *LoadOptions) (*ParsedSpec, error)
- func (l *Loader) RefreshCache(ctx context.Context, specURL string) (*ParsedSpec, error)
- func (l *Loader) SetCacheTTL(ttl time.Duration)
- func (l *Loader) SetHTTPClient(client *http.Client)
- type OAuth2Flow
- type OAuth2Flows
- type Operation
- type OutputSettings
- type ParsedSpec
- type Parser
- type PollingConfig
- type PromptSource
- type ReconnectConfig
- type SpecCache
- type SpecExtensions
- type SpecInfo
- type SpecVersion
- type TableColumn
- type TableConfig
- type TokenStorage
- type ValidationError
- type ValidationResult
- type ValidationWarning
- type Validator
- type WorkflowOutput
- type WorkflowRequest
- type WorkflowStep
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func FormatChangelog ¶
func FormatChangelog(changes []*DetectedChange) string
FormatChangelog formats detected changes into a human-readable changelog string. It groups changes by severity and formats them as breaking changes, warnings, and new features.
func GroupBySeverity ¶
func GroupBySeverity(changes []*DetectedChange) map[ChangeSeverity][]*DetectedChange
GroupBySeverity groups changes by their severity (breaking, dangerous, safe). It returns a map where keys are severity levels and values are slices of changes.
func GroupByType ¶
func GroupByType(changes []*DetectedChange) map[ChangeType][]*DetectedChange
GroupByType groups changes by their type (added, removed, modified). It returns a map where keys are change types and values are slices of changes.
func IsBreaking ¶
func IsBreaking(changes []*DetectedChange) bool
IsBreaking returns true if any changes are breaking. It iterates through all detected changes and returns true if any have breaking severity.
Types ¶
type AuthConfig ¶
type AuthConfig struct {
Flows *OAuth2Flows `json:"flows"`
TokenStorage []TokenStorage `json:"token-storage"`
}
AuthConfig represents the x-auth-config security extension.
type AuthSettings ¶
type AuthSettings struct {
Type string `json:"type"` // oauth2, apikey, basic
Storage string `json:"storage"` // file, keyring, memory
AutoRefresh bool `json:"auto-refresh"`
}
AuthSettings contains authentication settings.
type BackoffConfig ¶
type BackoffConfig struct {
Enabled bool `json:"enabled"`
Multiplier float64 `json:"multiplier"`
MaxInterval int `json:"max-interval"` // seconds
}
BackoffConfig defines exponential backoff settings.
type BrandingConfig ¶
type BrandingConfig struct {
ASCIIArt string `json:"ascii-art"`
Colors *ColorScheme `json:"colors"`
Raw map[string]interface{} `json:"-"`
}
BrandingConfig contains branding settings.
type CLIAsync ¶
type CLIAsync struct {
Enabled bool `json:"enabled"`
StatusField string `json:"status-field"`
StatusEndpoint string `json:"status-endpoint"`
TerminalStates []string `json:"terminal-states"`
Polling *PollingConfig `json:"polling"`
}
CLIAsync represents the x-cli-async extension.
type CLIConfig ¶
type CLIConfig struct {
Name string `json:"name"`
Version string `json:"version"`
Description string `json:"description"`
Branding *BrandingConfig `json:"branding"`
Auth *AuthSettings `json:"auth"`
Output *OutputSettings `json:"output"`
Features *FeatureSettings `json:"features"`
Cache *CacheSettings `json:"cache"`
Raw map[string]interface{} `json:"-"` // Raw extension data
}
CLIConfig represents the x-cli-config global extension.
type CLIConfirmation ¶
type CLIConfirmation struct {
Enabled bool `json:"enabled"`
Message string `json:"message"`
Flag string `json:"flag"`
}
CLIConfirmation represents the x-cli-confirmation extension.
type CLIFileInput ¶
type CLIFileInput struct {
Parameter string `json:"parameter"`
Accepts []string `json:"accepts"` // file extensions
MaxSize int64 `json:"max-size"`
Description string `json:"description"`
}
CLIFileInput represents the x-cli-file-input extension.
type CLIFlag ¶
type CLIFlag struct {
Name string `json:"name"`
Source string `json:"source"`
Flag string `json:"flag"`
Aliases []string `json:"aliases"`
Required bool `json:"required"`
Type string `json:"type"`
Enum []string `json:"enum"`
Default interface{} `json:"default"`
Description string `json:"description"`
}
CLIFlag represents a single x-cli-flags entry.
type CLIInteractive ¶
type CLIInteractive struct {
Enabled bool `json:"enabled"`
Prompts []*InteractivePrompt `json:"prompts"`
}
CLIInteractive represents the x-cli-interactive extension.
type CLIOutput ¶
type CLIOutput struct {
Format string `json:"format"`
SuccessMessage string `json:"success-message"`
ErrorMessage string `json:"error-message"`
WatchStatus bool `json:"watch-status"`
Table *TableConfig `json:"table"`
}
CLIOutput represents the x-cli-output extension.
type CLIPlugin ¶
type CLIPlugin struct {
Name string `json:"name"`
Description string `json:"description"`
Command string `json:"command"`
Executable string `json:"executable"`
Args []string `json:"args"`
}
CLIPlugin represents the x-cli-plugin extension.
type CLIPreflight ¶
type CLIPreflight struct {
Name string `json:"name"`
Description string `json:"description"`
Endpoint string `json:"endpoint"`
Method string `json:"method"`
Required bool `json:"required"`
SkipFlag string `json:"skip-flag"`
}
CLIPreflight represents x-cli-preflight checks.
type CLIProgress ¶
type CLIProgress struct {
Enabled *bool `json:"enabled"`
Type string `json:"type"` // spinner, bar, steps
ShowStepDescriptions *bool `json:"show-step-descriptions"`
ShowTimestamps *bool `json:"show-timestamps"`
Color string `json:"color"` // auto, always, never
}
CLIProgress represents the x-cli-progress extension.
type CLISecret ¶
type CLISecret struct {
Parameter string `json:"parameter"`
Masked bool `json:"masked"`
Storage string `json:"storage"` // env, keyring, prompt
EnvVar string `json:"env-var"`
}
CLISecret represents the x-cli-secret extension.
type CLIWatch ¶
type CLIWatch struct {
Enabled bool `json:"enabled"`
Type string `json:"type"` // sse, websocket, polling
Endpoint string `json:"endpoint"`
Events []string `json:"events"`
ExitConditions []*ExitCondition `json:"exit-on"`
Reconnect *ReconnectConfig `json:"reconnect"`
}
CLIWatch represents the x-cli-watch extension.
type CLIWorkflow ¶
type CLIWorkflow struct {
Steps []*WorkflowStep `json:"steps"`
Output *WorkflowOutput `json:"output"`
}
CLIWorkflow represents the x-cli-workflow extension.
type CacheSettings ¶
type CacheSettings struct {
Enabled bool `json:"enabled"`
TTL int `json:"ttl"` // seconds
Location string `json:"location"`
}
CacheSettings contains cache configuration.
type CachedSpec ¶
CachedSpec represents a cached OpenAPI spec with metadata.
type Change ¶
type Change struct {
Type string `json:"type"` // added, removed, modified, deprecated, security
Severity string `json:"severity"` // breaking, dangerous, safe
Description string `json:"description"`
Path string `json:"path"`
Migration string `json:"migration"`
Sunset string `json:"sunset"`
}
Change represents a single change in the changelog.
type ChangeDetector ¶
type ChangeDetector struct {
// IncludeNonBreaking includes non-breaking changes in results
IncludeNonBreaking bool
}
ChangeDetector detects changes between OpenAPI spec versions.
func NewChangeDetector ¶
func NewChangeDetector() *ChangeDetector
NewChangeDetector creates a new ChangeDetector instance.
func (*ChangeDetector) DetectChanges ¶
func (cd *ChangeDetector) DetectChanges(oldSpec, newSpec *ParsedSpec) ([]*DetectedChange, error)
DetectChanges compares two specs and returns detected changes.
type ChangeSeverity ¶
type ChangeSeverity string
ChangeSeverity represents the severity of a change.
const ( // ChangeSeverityBreaking represents a breaking change. ChangeSeverityBreaking ChangeSeverity = "breaking" // ChangeSeverityDangerous represents a potentially dangerous change. ChangeSeverityDangerous ChangeSeverity = "dangerous" // ChangeSeveritySafe represents a safe change. ChangeSeveritySafe ChangeSeverity = "safe" )
type ChangeType ¶
type ChangeType string
ChangeType represents the type of change.
const ( // ChangeTypeAdded represents a newly added element. ChangeTypeAdded ChangeType = "added" // ChangeTypeRemoved represents a removed element. ChangeTypeRemoved ChangeType = "removed" // ChangeTypeModified represents a modified element. ChangeTypeModified ChangeType = "modified" )
type ChangelogEntry ¶
type ChangelogEntry struct {
Date string `json:"date"`
Version string `json:"version"`
Changes []*Change `json:"changes"`
Added []string `json:"added,omitempty"`
Changed []string `json:"changed,omitempty"`
Deprecated []string `json:"deprecated,omitempty"`
Removed []string `json:"removed,omitempty"`
Breaking []string `json:"breaking,omitempty"`
IsCurrent bool `json:"is_current,omitempty"`
}
ChangelogEntry represents a single x-cli-changelog entry.
func GetChangelog ¶
func GetChangelog(spec *ParsedSpec) []ChangelogEntry
GetChangelog extracts changelog entries from a spec and returns them sorted by version. It returns changelog entries in descending order (newest first).
func GetLatestChanges ¶
func GetLatestChanges(spec *ParsedSpec, sinceVersion string) []ChangelogEntry
GetLatestChanges returns changes since a specific version. It filters changelog entries to include only versions newer than sinceVersion.
type ColorScheme ¶
ColorScheme defines CLI color scheme.
type Deprecation ¶
type Deprecation struct {
OperationID string `json:"operation_id"`
Method string `json:"method"`
Path string `json:"path"`
Parameter string `json:"parameter,omitempty"`
Sunset time.Time `json:"sunset,omitempty"`
Replacement string `json:"replacement,omitempty"`
Message string `json:"message,omitempty"`
DocsURL string `json:"docs_url,omitempty"`
Severity string `json:"severity"` // warning, critical
}
Deprecation represents a deprecated API endpoint or parameter.
type DeprecationInfo ¶
type DeprecationInfo struct {
Path string `json:"path"`
Deprecated bool `json:"deprecated"`
Sunset time.Time `json:"sunset"`
Replacement string `json:"replacement"`
Migration string `json:"migration"`
Level string `json:"level"` // info, warning, error
}
DeprecationInfo represents the x-cli-deprecation extension.
type DetectedChange ¶
type DetectedChange struct {
Type ChangeType
Severity ChangeSeverity
Path string
Description string
OldValue interface{}
NewValue interface{}
}
DetectedChange represents a detected change between spec versions.
type ExitCondition ¶
type ExitCondition struct {
Event string `json:"event"`
Condition string `json:"condition"`
Message string `json:"message"`
}
ExitCondition defines when to exit watch mode.
type FeatureSettings ¶
type FeatureSettings struct {
InteractiveMode bool `json:"interactive-mode"`
AutoComplete bool `json:"auto-complete"`
SelfUpdate bool `json:"self-update"`
Telemetry bool `json:"telemetry"`
}
FeatureSettings contains feature flags.
type InteractivePrompt ¶
type InteractivePrompt struct {
Parameter string `json:"parameter"`
Type string `json:"type"` // text, select, confirm, number, password
Message string `json:"message"`
Default interface{} `json:"default"`
Validation string `json:"validation"`
ValidationMessage string `json:"validation-message"`
Source *PromptSource `json:"source"`
}
InteractivePrompt represents a single interactive prompt.
type LoadOptions ¶
type LoadOptions struct {
// ForceRefresh bypasses cache and fetches fresh spec
ForceRefresh bool
// SkipConditional skips ETag-based conditional requests
SkipConditional bool
// Headers to include in HTTP request
Headers map[string]string
}
LoadOptions controls how specs are loaded.
type Loader ¶
type Loader struct {
// Parser is used to parse the loaded spec
Parser *Parser
// Cache stores loaded specs
Cache SpecCache
// HTTPClient for fetching remote specs
HTTPClient *http.Client
// CacheTTL is the cache time-to-live (default: 5 minutes)
CacheTTL time.Duration
}
Loader handles loading OpenAPI specs from various sources with caching.
func (*Loader) InvalidateCache ¶
InvalidateCache removes a cached spec.
func (*Loader) LoadFromData ¶
LoadFromData loads an OpenAPI spec from raw bytes.
func (*Loader) LoadFromFile ¶
LoadFromFile loads an OpenAPI spec from a file.
func (*Loader) LoadFromReader ¶
LoadFromReader loads an OpenAPI spec from an io.Reader.
func (*Loader) LoadFromURL ¶
func (l *Loader) LoadFromURL(ctx context.Context, specURL string, options *LoadOptions) (*ParsedSpec, error)
LoadFromURL loads an OpenAPI spec from a URL with caching support.
func (*Loader) RefreshCache ¶
RefreshCache forces a refresh of the cached spec for a URL.
func (*Loader) SetCacheTTL ¶
SetCacheTTL sets the cache time-to-live duration.
func (*Loader) SetHTTPClient ¶
SetHTTPClient sets a custom HTTP client.
type OAuth2Flow ¶
type OAuth2Flow struct {
AuthorizationURL string `json:"authorizationUrl"`
TokenURL string `json:"tokenUrl"`
RefreshURL string `json:"refreshUrl"`
Scopes map[string]string `json:"scopes"`
}
OAuth2Flow represents a single OAuth2 flow.
type OAuth2Flows ¶
type OAuth2Flows struct {
AuthorizationCode *OAuth2Flow `json:"authorizationCode"`
ClientCredentials *OAuth2Flow `json:"clientCredentials"`
Implicit *OAuth2Flow `json:"implicit"`
Password *OAuth2Flow `json:"password"`
}
OAuth2Flows contains OAuth2 flow configurations.
type Operation ¶
type Operation struct {
Method string
Path string
OperationID string
Summary string
Description string
Tags []string
Operation *openapi3.Operation
// CLI Extensions
CLICommand string
CLIAliases []string
CLIFlags []*CLIFlag
CLIInteractive *CLIInteractive
CLIPreflight []*CLIPreflight
CLIConfirmation *CLIConfirmation
CLIAsync *CLIAsync
CLIOutput *CLIOutput
CLIWorkflow *CLIWorkflow
CLIParentRes string
}
Operation represents an API operation with CLI extensions.
type OutputSettings ¶
type OutputSettings struct {
DefaultFormat string `json:"default-format"`
SupportedFormats []string `json:"supported-formats"`
}
OutputSettings contains output format settings.
type ParsedSpec ¶
type ParsedSpec struct {
// Spec is the OpenAPI 3.x specification
Spec *openapi3.T
// OriginalVersion indicates the original spec format
OriginalVersion SpecVersion
// Extensions contains all parsed x-cli-* extensions
Extensions *SpecExtensions
}
ParsedSpec represents a parsed OpenAPI specification with metadata.
func (*ParsedSpec) GetInfo ¶
func (ps *ParsedSpec) GetInfo() *SpecInfo
GetInfo returns basic information about the API from the spec.
func (*ParsedSpec) GetOperations ¶
func (ps *ParsedSpec) GetOperations() ([]*Operation, error)
GetOperations returns all operations from the spec with their CLI extensions.
type Parser ¶
type Parser struct {
// DisableValidation skips OpenAPI spec validation
DisableValidation bool
// AllowRemoteRefs enables loading remote $ref references
AllowRemoteRefs bool
}
Parser handles parsing of OpenAPI 3.x and Swagger 2.0 specifications.
func NewParser ¶
func NewParser() *Parser
NewParser creates a new Parser instance with default settings.
func (*Parser) Parse ¶
Parse parses an OpenAPI specification from a byte slice. Automatically detects Swagger 2.0 and converts to OpenAPI 3.0.
func (*Parser) ParseReader ¶
ParseReader parses an OpenAPI specification from an io.Reader.
type PollingConfig ¶
type PollingConfig struct {
Interval int `json:"interval"` // seconds
Timeout int `json:"timeout"` // seconds
Backoff *BackoffConfig `json:"backoff"`
}
PollingConfig defines polling behavior for async operations.
type PromptSource ¶
type PromptSource struct {
Endpoint string `json:"endpoint"`
ValueField string `json:"value-field"`
DisplayField string `json:"display-field"`
Filter string `json:"filter"`
}
PromptSource defines where to fetch select options from.
type ReconnectConfig ¶
type ReconnectConfig struct {
Enabled bool `json:"enabled"`
MaxAttempts int `json:"max-attempts"`
IntervalSecs int `json:"interval"`
}
ReconnectConfig defines reconnection behavior.
type SpecCache ¶
type SpecCache interface {
// Get retrieves a cached spec
Get(ctx context.Context, key string) (*CachedSpec, error)
// Set stores a spec in cache
Set(ctx context.Context, key string, spec *CachedSpec) error
// Invalidate removes a spec from cache
Invalidate(ctx context.Context, key string) error
}
SpecCache defines the interface for caching loaded specs.
type SpecExtensions ¶
type SpecExtensions struct {
// Global configuration
Config *CLIConfig
// Auth configuration
AuthConfig *AuthConfig
// Changelog entries
Changelog []ChangelogEntry
// Deprecations
Deprecations []*DeprecationInfo
}
SpecExtensions contains all CLI extensions from the OpenAPI spec.
func ParseSpecExtensions ¶
func ParseSpecExtensions(spec *openapi3.T) (*SpecExtensions, error)
ParseSpecExtensions extracts all CLI extensions from the OpenAPI spec.
type SpecInfo ¶
type SpecInfo struct {
Title string
Version string
Description string
CLIVersion string
MinCLIVersion string
}
SpecInfo contains basic information about the API specification.
type SpecVersion ¶
type SpecVersion string
SpecVersion indicates the OpenAPI specification version.
const ( // SpecVersionSwagger2 represents Swagger 2.0 / OpenAPI 2.0 SpecVersionSwagger2 SpecVersion = "2.0" // SpecVersionOpenAPI3 represents OpenAPI 3.0.x SpecVersionOpenAPI3 SpecVersion = "3.0" // SpecVersionOpenAPI31 represents OpenAPI 3.1.x SpecVersionOpenAPI31 SpecVersion = "3.1" )
type TableColumn ¶
type TableColumn struct {
Field string `json:"field"`
Header string `json:"header"`
Transform string `json:"transform"`
Width int `json:"width"`
}
TableColumn defines a single table column.
type TableConfig ¶
type TableConfig struct {
Columns []*TableColumn `json:"columns"`
}
TableConfig defines table output configuration.
type TokenStorage ¶
type TokenStorage struct {
Type string `json:"type"` // file, keyring
Path string `json:"path"`
Service string `json:"service"`
KeyringBackends map[string]string `json:"keyring-backends"`
}
TokenStorage represents token storage configuration.
type ValidationError ¶
ValidationError represents a validation error.
func (ValidationError) Error ¶
func (e ValidationError) Error() string
Error returns a formatted error string.
type ValidationResult ¶
type ValidationResult struct {
Valid bool
Errors []ValidationError
Warnings []ValidationWarning
}
ValidationResult contains validation results.
type ValidationWarning ¶
ValidationWarning represents a validation warning.
func (ValidationWarning) String ¶
func (w ValidationWarning) String() string
String returns a formatted warning string.
type Validator ¶
type Validator struct {
// Strict enables strict validation mode
Strict bool
// AllowUnknownExtensions allows unknown x-cli-* extensions
AllowUnknownExtensions bool
}
Validator validates OpenAPI specs and CLI extensions.
func (*Validator) Validate ¶
func (v *Validator) Validate(ctx context.Context, spec *ParsedSpec) (*ValidationResult, error)
Validate validates a parsed spec and its CLI extensions.
type WorkflowOutput ¶
WorkflowOutput defines workflow output transformation.
type WorkflowRequest ¶
type WorkflowRequest struct {
Method string `json:"method"`
URL string `json:"url"`
Headers map[string]string `json:"headers"`
Body map[string]interface{} `json:"body"`
Query map[string]string `json:"query"`
}
WorkflowRequest defines an HTTP request in a workflow.
type WorkflowStep ¶
type WorkflowStep struct {
ID string `json:"id"`
Request *WorkflowRequest `json:"request"`
Condition string `json:"condition"`
ForEach string `json:"foreach"`
As string `json:"as"`
}
WorkflowStep represents a single workflow step.