converter

package
v1.23.2 Latest Latest
Warning

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

Go to latest
Published: Dec 12, 2025 License: MIT Imports: 9 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.

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)
}

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.

Example:

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

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

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
}

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 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