load

package
v1.29.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 16, 2026 License: Apache-2.0 Imports: 13 Imported by: 2

Documentation

Overview

Package load provides functions to load OpenAPI specifications from various sources.

Overview

The load package handles loading OpenAPI specs from files, URLs, stdin, and glob patterns. It automatically resolves $ref references and extracts version information from the spec.

Usage

Load a spec from a file, URL, or stdin:

source, _ := load.NewSource("openapi.yaml")
specInfo, err := load.NewSpecInfo(openapi3.NewLoader(), source)

Load multiple specs using glob patterns:

specInfos, err := load.NewSpecInfoFromGlob(openapi3.NewLoader(), "specs/*.yaml")

Preprocessing Options

Options can preprocess specs after loading to improve diff accuracy:

specInfo, err := load.NewSpecInfo(loader, source,
    load.WithFlattenAllOf(),      // Merge allOf schemas into single schema
    load.WithFlattenParams(),     // Move common path parameters to operations
    load.WithLowercaseHeaders(),  // Normalize header names to lowercase
)

These options use the flatten subpackages:

  • flatten/allof: merges allOf schemas for more accurate breaking change detection
  • flatten/commonparams: moves path-level parameters to operations for consistent comparison
  • flatten/headers: lowercases header names since HTTP headers are case-insensitive

SpecInfo

SpecInfo wraps a loaded spec with metadata:

  • Spec: the parsed openapi3.T object with resolved references
  • Url: the source path/URL the spec was loaded from
  • Version: the API version extracted from info.version

Index

Constants

This section is empty.

Variables

View Source
var ErrRefLooksLikeOption = errors.New("git revision must not start with '-'")

refBeforeColon returns the "<ref>" portion of a "<ref>:<path>" git revision, or the whole string when there is no colon. ErrRefLooksLikeOption is returned for a git revision starting with "-".

Refs are passed to git as operands. Without protection git parses a leading-dash operand as an OPTION, which is a real capability and not a theoretical one: "--output=<path>" on git show writes git's output to that path, giving an arbitrary file overwrite as the invoking user, and "--upload-pack=<program>" on git fetch makes git execute that program.

Every call site also passes --end-of-options, which instructs git to treat everything after it as an operand. This check is the belt to that braces: it does not depend on the git version (--end-of-options landed in git 2.24), and it fails with a clear message instead of a confusing git error.

No legitimate git revision begins with "-".

Functions

This section is empty.

Types

type ExternalRefError added in v1.18.1

type ExternalRefError struct {
	Ref string
}

ExternalRefError reports that a spec resolved an external $ref (an http(s) URL or a local file outside the git tree) while external refs were disallowed (IsExternalRefsAllowed=false, i.e. --allow-external-refs=false). Returned as a distinct type so callers can use errors.As to map it to a dedicated exit code, rather than matching the message text.

func (*ExternalRefError) Error added in v1.18.1

func (e *ExternalRefError) Error() string

type FlattenError added in v1.15.3

type FlattenError struct {
	Url string
	Err error
}

FlattenError reports a failure to merge allOf during WithFlattenAllOf. Returned wrapped so callers can use errors.As to distinguish a flatten failure (which happens after the spec has loaded successfully) from a genuine load failure.

func (*FlattenError) Error added in v1.15.3

func (e *FlattenError) Error() string

func (*FlattenError) Unwrap added in v1.15.3

func (e *FlattenError) Unwrap() error

type Option

type Option func(*openapi3.Loader, []*SpecInfo) ([]*SpecInfo, error)

Option functions can be used to preprocess specs after loading them

func GetOption

func GetOption(option Option, enable bool) Option

GetOption returns the requested option, or a no-op option when disabled.

func WithFlattenAllOf

func WithFlattenAllOf() Option

WithFlattenAllOf returns SpecInfos with flattened allOf

func WithFlattenParams

func WithFlattenParams() Option

WithFlattenParams returns SpecInfos with Common Parameters combined into operation parameters See here for Common Parameters definition: https://swagger.io/docs/specification/describing-parameters/

func WithLowercaseHeaders

func WithLowercaseHeaders() Option

WithLowercaseHeaders returns SpecInfos with header names converted to lowercase

type Source

type Source struct {
	Path string
	Uri  *url.URL
	Type SourceType

	// Fetch, when true, lets a git-revision source fetch a missing commit from
	// the "origin" remote before reading it (see the --fetch flag). It mutates
	// the local repository by downloading objects, so it is opt-in and defaults
	// to false; only SourceTypeGitRevision sources consult it.
	Fetch bool
}

func NewSource

func NewSource(path string) *Source

NewSource creates a Source by categorizing the input path as stdin, URL, git revision, or file. This function is intentionally infallible (does not return an error) to allow clean usage in struct literal initialization and avoid error handling boilerplate in hundreds of call sites throughout the codebase.

Categorization rules (evaluated in order):

  • "-" → SourceTypeStdin
  • Git revision syntax (e.g. "HEAD:openapi.yaml", "origin/main:api/openapi.yaml") → SourceTypeGitRevision
  • Valid http/https URLs → SourceTypeURL
  • Everything else (including URLs with unsupported schemes) → SourceTypeFile

Git revision syntax is "<ref>:<path>" where <ref> is any git ref (branch, tag, commit SHA, or expressions like HEAD~1) and <path> is the file path within the repo. Multi-file specs with relative $refs are fully supported — referenced files are also read via "git show".

Actual validation and error handling occurs later when the source is loaded, providing clean separation of concerns between categorization and I/O.

func (*Source) DisplayPath added in v1.12.0

func (source *Source) DisplayPath() string

DisplayPath returns the path suitable for display and source-location reporting. For git revisions it strips the ref prefix (e.g. "origin/main:openapi.yaml" → "openapi.yaml").

func (*Source) IsFile

func (source *Source) IsFile() bool

func (*Source) IsGitRevision added in v1.11.11

func (source *Source) IsGitRevision() bool

func (*Source) IsStdin

func (source *Source) IsStdin() bool

func (*Source) IsURL added in v1.24.0

func (source *Source) IsURL() bool

func (*Source) Out

func (source *Source) Out() string

func (*Source) ReadRaw added in v1.18.2

func (source *Source) ReadRaw() ([]byte, error)

ReadRaw returns the raw, unparsed bytes of the spec source. Unlike the loaders in this package (which parse into an openapi3.T), ReadRaw is for callers that need the original document bytes verbatim, e.g. uploading the spec to a remote service. It supports file and git-revision sources; for git revisions it reuses the same "git show" plumbing as the loaders, including authoritative blob-hash handling. Stdin and URL sources are not supported and return an error.

func (*Source) String

func (source *Source) String() string

type SourceType

type SourceType int
const (
	SourceTypeStdin SourceType = iota
	SourceTypeURL
	SourceTypeFile
	SourceTypeGitRevision
)

type SpecInfo

type SpecInfo struct {
	Url     string
	Spec    *openapi3.T
	Version string
	// Sources holds the raw text of every file that contributed to Spec, keyed
	// by resolved path, when loaded via NewSpecInfoWithCapture; nil otherwise.
	Sources map[string]string
}

SpecInfo contains information about an OpenAPI spec and its metadata

func NewSpecInfo

func NewSpecInfo(loader *openapi3.Loader, source *Source, options ...Option) (*SpecInfo, error)

NewSpecInfo creates a SpecInfo from a local file path, a URL, a git revision, or stdin

func NewSpecInfoFromData added in v1.18.6

func NewSpecInfoFromData(loader *openapi3.Loader, data []byte, name string, options ...Option) (*SpecInfo, error)

NewSpecInfoFromData creates a SpecInfo from raw OpenAPI bytes already held in memory, labeling its source as name. name is loaded as the spec's path, so source-location reporting (e.g. the file name shown for each change) uses it rather than a temp path or an empty value. It is the in-memory counterpart to NewSpecInfo: no filesystem access, so relative file $refs are not resolved (intra-spec "#/..." refs still are). As elsewhere in this package, callers comparing two specs should use a fresh loader per spec so the loader's document cache does not collide when both share a name.

func NewSpecInfoFromGlob

func NewSpecInfoFromGlob(loader *openapi3.Loader, glob string, options ...Option) ([]*SpecInfo, error)

NewSpecInfoFromGlob creates SpecInfos from local files matching the specified glob parameter

func NewSpecInfoFromGlobWithCapture added in v1.24.0

func NewSpecInfoFromGlobWithCapture(loader *openapi3.Loader, glob string, options ...Option) ([]*SpecInfo, error)

NewSpecInfoFromGlobWithCapture is NewSpecInfoFromGlob that also records each spec's contributing file texts into its Sources (see NewSpecInfoWithCapture).

func NewSpecInfoWithCapture added in v1.24.0

func NewSpecInfoWithCapture(loader *openapi3.Loader, source *Source, options ...Option) (*SpecInfo, error)

NewSpecInfoWithCapture is NewSpecInfo that also records the raw text of every file the loader reads (root and $ref'd) into SpecInfo.Sources, for slicing multi-file specs by origin file (the review bundle).

func (*SpecInfo) GetVersion

func (specInfo *SpecInfo) GetVersion() string

type SpecInfoPair

type SpecInfoPair struct {
	Base     *SpecInfo
	Revision *SpecInfo
}

func NewSpecInfoPair

func NewSpecInfoPair(specInfo1, specInfo2 *SpecInfo) *SpecInfoPair

func (*SpecInfoPair) GetBaseVersion

func (specInfoPair *SpecInfoPair) GetBaseVersion() string

func (*SpecInfoPair) GetRevisionVersion

func (specInfoPair *SpecInfoPair) GetRevisionVersion() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL