converter

package
v1.41.0 Latest Latest
Warning

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

Go to latest
Published: Jan 7, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package converter provides version conversion for OpenAPI Specification documents.

The converter supports OAS 2.0 ↔ OAS 3.x conversions, performing best-effort conversion with detailed issue tracking. Features converted include servers, schemas, parameters, security schemes, and request/response bodies. The converter preserves the input file format (JSON or YAML) in the ConversionResult.SourceFormat field, allowing tools to maintain format consistency when writing output.

Quick Start

Convert a file using functional options:

result, err := converter.ConvertWithOptions(
	converter.WithFilePath("swagger.yaml"),
	converter.WithTargetVersion("3.0.3"),
)
if err != nil {
	log.Fatal(err)
}
if result.HasCriticalIssues() {
	fmt.Printf("%d critical issue(s)\n", result.CriticalCount)
}

Or use a reusable Converter instance:

c := converter.New()
c.StrictMode = false
result1, _ := c.Convert("api1.yaml", "3.0.3")
result2, _ := c.Convert("api2.yaml", "3.0.3")

Conversion Issues

The converter tracks three severity levels: Info (conversion choices), Warning (lossy conversions), and Critical (features that cannot be converted). Some OAS 3.x features (webhooks, callbacks, links, TRACE method) cannot convert to OAS 2.0. Some OAS 2.0 features (collectionFormat, allowEmptyValue) may not map perfectly to OAS 3.x. See the examples in example_test.go for handling issues.

Converting with the Validator Package

Always validate converted documents for the target version:

convResult, _ := converter.ConvertWithOptions(
	converter.WithFilePath("swagger.yaml"),
	converter.WithTargetVersion("3.0.3"),
)
data, _ := yaml.Marshal(convResult.Document)
tmpFile := "temp.yaml"
os.WriteFile(tmpFile, data, 0600)
valResult, _ := validator.ValidateWithOptions(
	validator.WithFilePath(tmpFile),
	validator.WithIncludeWarnings(true),
)
if !valResult.Valid {
	fmt.Printf("Conversion produced invalid document\n")
}

See the exported ConversionResult and ConversionIssue types for complete details.

Overlay Integration

Apply overlays before or after conversion:

result, err := converter.ConvertWithOptions(
    converter.WithFilePath("swagger.yaml"),
    converter.WithTargetVersion("3.0.3"),
    converter.WithPreConversionOverlayFile("fix-v2.yaml"),   // Fix v2-specific issues
    converter.WithPostConversionOverlayFile("enhance.yaml"), // Add v3-specific extensions
)

Pre-conversion overlays are useful for normalizing or fixing the source document. Post-conversion overlays can add version-specific extensions to the result.

Chaining with Other Packages

Use ConversionResult.ToParseResult to convert the result for use with other packages:

// Convert to OAS 3.1
convResult, _ := converter.ConvertWithOptions(
    converter.WithFilePath("swagger.yaml"),
    converter.WithTargetVersion("3.1.0"),
)

// Validate the converted result
v := validator.New()
validationResult, _ := v.ValidateParsed(*convResult.ToParseResult())

// Or join with other specifications
j := joiner.New(joiner.DefaultConfig())
joinResult, _ := j.JoinParsed([]parser.ParseResult{
    *convResult.ToParseResult(),
    otherSpec,
})

// Or diff against the original
diffResult, _ := differ.DiffWithOptions(
    differ.WithSourceFilePath("swagger.yaml"),
    differ.WithTargetParsed(*convResult.ToParseResult()),
)

The returned parser.ParseResult uses the target version (post-conversion) for version fields and converts all conversion issues to warnings.

Conversion integrates with other oastools packages:

Example

Example demonstrates basic conversion using functional options

package main

import (
	"fmt"
	"log"

	"github.com/erraggy/oastools/converter"
)

func main() {
	// Convert an OAS 2.0 specification to OAS 3.0.3
	result, err := converter.ConvertWithOptions(
		converter.WithFilePath("testdata/petstore-2.0.yaml"),
		converter.WithTargetVersion("3.0.3"),
	)
	if err != nil {
		log.Fatal(err)
	}

	// Check for critical issues
	if result.HasCriticalIssues() {
		fmt.Printf("Conversion completed with %d critical issue(s)\n", result.CriticalCount)
		return
	}

	fmt.Printf("Successfully converted from %s to %s\n", result.SourceVersion, result.TargetVersion)
	fmt.Printf("Issues: %d info, %d warnings, %d critical\n",
		result.InfoCount, result.WarningCount, result.CriticalCount)
}
Example (ComplexConversion)

Example_complexConversion demonstrates converting a complex OAS 2.0 document with OAuth2 flows, custom security schemes, and polymorphic schemas to OAS 3.0.

package main

import (
	"fmt"
	"log"

	"github.com/erraggy/oastools/converter"
)

func main() {
	// Convert a complex OAS 2.0 document with strict mode disabled
	// to allow for lossy conversions (e.g., allowEmptyValue is dropped)
	result, err := converter.ConvertWithOptions(
		converter.WithFilePath("testdata/petstore-2.0.yaml"),
		converter.WithTargetVersion("3.0.3"),
		converter.WithStrictMode(false), // Allow lossy conversions
		converter.WithIncludeInfo(true), // Include informational messages
	)

	if err != nil {
		log.Fatal(err)
	}

	// Review conversion issues to understand the changes
	fmt.Printf("Conversion from %s to %s:\n", result.SourceVersion, result.TargetVersion)
	fmt.Printf("- Critical issues: %d\n", result.CriticalCount)
	fmt.Printf("- Warnings: %d\n", result.WarningCount)
	fmt.Printf("- Info messages: %d\n", result.InfoCount)

	// Important conversions in OAS 2.0 → 3.0:
	// - OAuth2 flows are restructured under components.securitySchemes
	// - `host`, `basePath`, `schemes` → `servers` array with URL templates
	// - `definitions` → `components.schemas`
	// - `consumes`/`produces` → requestBody.content / responses.*.content
	// - Body parameters → requestBody objects

	// Check if conversion was successful despite issues
	if !result.HasCriticalIssues() {
		fmt.Println("\nConversion completed successfully")
	}
}
Example (HandleConversionIssues)

Example_handleConversionIssues demonstrates processing conversion issues

package main

import (
	"fmt"

	"github.com/erraggy/oastools/converter"
)

func main() {
	result, _ := converter.ConvertWithOptions(
		converter.WithFilePath("openapi.yaml"),
		converter.WithTargetVersion("2.0"),
	)

	// Categorize issues by severity
	for _, issue := range result.Issues {
		switch issue.Severity {
		case converter.SeverityCritical:
			fmt.Printf("CRITICAL [%s]: %s\n", issue.Path, issue.Message)
			if issue.Context != "" {
				fmt.Printf("  Context: %s\n", issue.Context)
			}
		case converter.SeverityError:
			fmt.Printf("ERROR [%s]: %s\n", issue.Path, issue.Message)
		case converter.SeverityWarning:
			fmt.Printf("WARNING [%s]: %s\n", issue.Path, issue.Message)
		case converter.SeverityInfo:
			fmt.Printf("INFO [%s]: %s\n", issue.Path, issue.Message)
		}
	}

	// Summary
	fmt.Printf("\nSummary: %d critical, %d warnings, %d info\n",
		result.CriticalCount, result.WarningCount, result.InfoCount)
}
Example (ToParseResult)

Example_toParseResult demonstrates using ToParseResult() to chain converter output with other packages like validator, fixer, or differ.

package main

import (
	"fmt"
	"log"

	"github.com/erraggy/oastools/converter"
)

func main() {
	// Convert an OAS 2.0 specification to OAS 3.0.3
	convResult, err := converter.ConvertWithOptions(
		converter.WithFilePath("../testdata/petstore-2.0.yaml"),
		converter.WithTargetVersion("3.0.3"),
	)
	if err != nil {
		log.Fatal(err)
	}

	// Convert to ParseResult for use with validator, fixer, differ, etc.
	parseResult := convResult.ToParseResult()

	// The ParseResult can now be used with other packages:
	// - validator.ValidateParsed(*parseResult)
	// - fixer.FixParsed(*parseResult)
	// - differ.DiffParsed(*baseResult, *parseResult)

	fmt.Printf("Source: %s\n", parseResult.SourcePath)
	fmt.Printf("Version: %s\n", parseResult.Version)
	fmt.Printf("Has document: %v\n", parseResult.Document != nil)
}
Output:

Source: converter
Version: 3.0.3
Has document: true

Index

Examples

Constants

View Source
const (
	// SeverityInfo indicates informational messages about conversion choices
	SeverityInfo = severity.SeverityInfo
	// SeverityWarning indicates lossy conversions or best-effort transformations
	SeverityWarning = severity.SeverityWarning
	// SeverityError indicates validation errors
	SeverityError = severity.SeverityError
	// SeverityCritical indicates features that cannot be converted (data loss)
	SeverityCritical = severity.SeverityCritical
)

Variables

This section is empty.

Functions

This section is empty.

Types

type ConversionIssue

type ConversionIssue = issues.Issue

ConversionIssue represents a single conversion issue or limitation

type ConversionResult

type ConversionResult struct {
	// Document contains the converted document (*parser.OAS2Document or *parser.OAS3Document)
	Document any
	// SourceVersion is the detected source OAS version string
	SourceVersion string
	// SourceOASVersion is the enumerated source OAS version
	SourceOASVersion parser.OASVersion
	// SourceFormat is the format of the source file (JSON or YAML)
	SourceFormat parser.SourceFormat
	// TargetVersion is the target OAS version string
	TargetVersion string
	// TargetOASVersion is the enumerated target OAS version
	TargetOASVersion parser.OASVersion
	// Issues contains all conversion issues grouped by severity
	Issues []ConversionIssue
	// InfoCount is the total number of info messages
	InfoCount int
	// WarningCount is the total number of warnings
	WarningCount int
	// CriticalCount is the total number of critical issues
	CriticalCount int
	// Success is true if conversion completed without critical issues
	Success bool
	// LoadTime is the time taken to load the source data
	LoadTime time.Duration
	// SourceSize is the size of the source data in bytes
	SourceSize int64
	// Stats contains statistical information about the source document
	Stats parser.DocumentStats
}

ConversionResult contains the results of converting an OpenAPI specification

func ConvertWithOptions added in v1.11.0

func ConvertWithOptions(opts ...Option) (*ConversionResult, error)

ConvertWithOptions converts an OpenAPI specification using functional options. This provides a flexible, extensible API that combines input source selection and configuration in a single function call.

When overlay options are provided, the conversion process follows these steps:

  1. Parse the source specification
  2. Apply pre-conversion overlay (if specified)
  3. Perform the version conversion
  4. Apply post-conversion overlay (if specified)

Example:

result, err := converter.ConvertWithOptions(
    converter.WithFilePath("swagger.yaml"),
    converter.WithTargetVersion("3.0.3"),
    converter.WithStrictMode(true),
    converter.WithPostConversionOverlayFile("enhance-v3.yaml"),
)

func (*ConversionResult) HasCriticalIssues

func (r *ConversionResult) HasCriticalIssues() bool

HasCriticalIssues returns true if there are any critical issues

func (*ConversionResult) HasWarnings

func (r *ConversionResult) HasWarnings() bool

HasWarnings returns true if there are any warnings

func (*ConversionResult) ToParseResult added in v1.40.0

func (r *ConversionResult) ToParseResult() *parser.ParseResult

ToParseResult converts the ConversionResult to a ParseResult for use with other packages like validator, fixer, and differ. Uses the target version (post-conversion) for version fields. The returned ParseResult has Document populated but Data is nil (consumers use Document, not Data). Conversion issues are formatted with severity prefix for filtering: "[critical] ✗ path: message", "[warning] ⚠ path: message", etc.

type Converter

type Converter struct {
	// StrictMode causes conversion to fail on any issues (even warnings)
	StrictMode bool
	// IncludeInfo determines whether to include informational messages
	IncludeInfo bool
	// UserAgent is the User-Agent string used when fetching URLs
	// Defaults to "oastools" if not set
	UserAgent string
	// SourceMap provides source location lookup for conversion issues.
	// When set, issues will include Line, Column, and File information.
	SourceMap *parser.SourceMap
}

Converter handles OpenAPI specification version conversion

func New

func New() *Converter

New creates a new Converter instance with default settings

func (*Converter) Convert

func (c *Converter) Convert(specPath string, targetVersion string) (*ConversionResult, error)

Convert converts an OpenAPI specification file to a target version

func (*Converter) ConvertParsed

func (c *Converter) ConvertParsed(parseResult parser.ParseResult, targetVersionStr string) (*ConversionResult, error)

ConvertParsed converts an already-parsed OpenAPI specification to a target version

type Option added in v1.11.0

type Option func(*convertConfig) error

Option is a function that configures a conversion operation

func WithFilePath added in v1.11.0

func WithFilePath(path string) Option

WithFilePath specifies a file path or URL as the input source

func WithIncludeInfo added in v1.11.0

func WithIncludeInfo(enabled bool) Option

WithIncludeInfo enables or disables informational messages Default: true

func WithParsed added in v1.11.0

func WithParsed(result parser.ParseResult) Option

WithParsed specifies a parsed ParseResult as the input source

func WithPostConversionOverlay added in v1.24.0

func WithPostConversionOverlay(o *overlay.Overlay) Option

WithPostConversionOverlay sets an overlay to be applied after conversion.

This is useful for adding v3-specific extensions or making adjustments to the converted document.

Example:

result, err := converter.ConvertWithOptions(
    converter.WithFilePath("swagger.yaml"),
    converter.WithTargetVersion("3.0.3"),
    converter.WithPostConversionOverlay(enhanceOverlay),
)

func WithPostConversionOverlayFile added in v1.24.0

func WithPostConversionOverlayFile(path string) Option

WithPostConversionOverlayFile sets an overlay file to be applied after conversion.

This is a convenience wrapper around WithPostConversionOverlay that parses the overlay file.

Example:

result, err := converter.ConvertWithOptions(
    converter.WithFilePath("swagger.yaml"),
    converter.WithTargetVersion("3.0.3"),
    converter.WithPostConversionOverlayFile("enhance-v3.yaml"),
)

func WithPreConversionOverlay added in v1.24.0

func WithPreConversionOverlay(o *overlay.Overlay) Option

WithPreConversionOverlay sets an overlay to be applied before conversion.

This is useful for fixing v2-specific issues before converting to v3, or normalizing a spec before version conversion.

Example:

result, err := converter.ConvertWithOptions(
    converter.WithFilePath("swagger.yaml"),
    converter.WithTargetVersion("3.0.3"),
    converter.WithPreConversionOverlay(fixOverlay),
)

func WithPreConversionOverlayFile added in v1.24.0

func WithPreConversionOverlayFile(path string) Option

WithPreConversionOverlayFile sets an overlay file to be applied before conversion.

This is a convenience wrapper around WithPreConversionOverlay that parses the overlay file.

Example:

result, err := converter.ConvertWithOptions(
    converter.WithFilePath("swagger.yaml"),
    converter.WithTargetVersion("3.0.3"),
    converter.WithPreConversionOverlayFile("fix-v2.yaml"),
)

func WithSourceMap added in v1.27.0

func WithSourceMap(sm *parser.SourceMap) Option

WithSourceMap provides a SourceMap for populating line/column information in conversion issues. When set, issues will include source location details that enable IDE-friendly error reporting.

func WithStrictMode added in v1.11.0

func WithStrictMode(enabled bool) Option

WithStrictMode enables or disables strict mode (fail on any issues) Default: false

func WithTargetVersion added in v1.11.0

func WithTargetVersion(version string) Option

WithTargetVersion specifies the target OAS version for conversion Required option - must be one of: "2.0", "3.0.0", "3.0.1", "3.0.2", "3.0.3", "3.1.0", etc.

func WithUserAgent added in v1.11.0

func WithUserAgent(ua string) Option

WithUserAgent sets the User-Agent string for HTTP requests Default: "" (uses parser default)

type Severity

type Severity = severity.Severity

Severity indicates the severity level of a conversion issue

Jump to

Keyboard shortcuts

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