raml

package module
v0.15.0 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2024 License: MIT Imports: 23 Imported by: 4

README

Go Report Card

RAML 1.0 parser for Go

[!WARNING] The parser is in active development. See supported features in the Supported features of RAML 1.0 specification section.

This is an implementation of RAML parser for Go according to the official RAML 1.0 specification.

This package aims to achieve the following:

  1. Provide a compliant RAML 1.0 parser.
  2. Provide an easy-to-use interface for parsing and validating RAML/data type definitions.
  3. Provide optimal performance and memory efficiency for API/data type definitions of any size.
  4. Provide additional, but not limited to, features built on top of parser, such as:
    1. Middlewares for popular HTTP frameworks that validates the requests/responses according to API definition.
    2. An HTTP gateway that validates requests/responses according to API definition.
    3. A language server built according to Language Server Protocol (LSP).
    4. A linter that may provide additional validations or style enforcement.
    5. Conversion of parsed structure into JSON Schema and back to RAML.

Why RAML?

RAML is a powerful modelling language that encourages design-first approach to API definitions by offering modularity and flexibility. Combined with a powerful type system with inheritance support that it offers, it also allows the developers to easily define complex data type schemas by leveraging both inheritance mechanism (by referencing a parent type with common properties) and modularity (by referencing common data type fragments).

RAML uses YAML as a markup language which also contributes to readability, especially in complex definitions.

For comparison, an example of a simple data type schema in RAML would be the following:

#%RAML 1.0 Library

types:
  CommonType:
    additionalProperties: false
    properties:
      id: string
      content: object
    example:
      id: sample.message
      content: {}

  DerivedType:
    type: CommonType # inherits from "CommonType"
    properties:
      content:
        properties:
          value: integer
    example:
      id: "metrics.message"
      content:
        value: 0

Where DerivedType would translate into the following JSON Schema using Draft-7 specification due to the lack of the inheritance support:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$ref": "#/definitions/DerivedType",
  "definitions": {
    "DerivedType": {
      "type": "object",
      "additionalProperties": false,
      "properties": {
        "id": {
          "type": "string"
        },
        "content": {
          "type": "object",
          "properties": {
            "value": {
              "type": "integer"
            }
          },
          "required": ["value"]
        }
      },
      "required": ["id", "content"]
    }
  }
}

What you can do with it

Create API definitions

RAML's primary objective is to provide a specification for maintainable, design-driven API definitions.

By using RAML, you can make a well-structured API definition that would be easy to read, maintain and use.

Validate data

Given a powerful type definition system, you can declaratively define your data schema and validate data instances against that schema.

Define static configuration

On top of the type definition system, RAML allows defining metadata using custom typed annotations. One of the ways in which a custom annotation can be used by processors is creating a static configuration that is validated against a specific schema. For example:

#%RAML 1.0 Library

types:
  # Define a data type for configuration
  Config:
    additionalProperties: false
    properties:
      host: string
      port: integer

annotationTypes:
  # Define a custom annotation that would be used to create an instance of a type
  ConfigInstance: Config

# Create an instance of a type.
(ConfigInstance):
  host: example.com
  port: 8080
And more

With all the features, there can be more creative cases that can be covered and are not limited to the mentioned use cases.

Supported features of RAML 1.0 specification

The following sections are currently implemented. See notes for each point:

  • RAML API definitions
  • RAML Data Types
    • Defining Types
    • Type Declarations
    • Built-in Types
      • The "Any" Type
      • Object Type
        • Property Declarations (explicit and pattern properties)
        • Additional Properties
        • Object Type Specialization
        • Using Discriminator
      • Array Type
      • Scalar Types
        • String
        • Number
        • Integer
        • Boolean
        • Date
        • File
        • Nil Type
      • Union Type (mostly supported, lacks enum support)
      • JSON Schema types (supported, but validation is not implemented)
      • Recursive types
    • User-defined Facets
    • Determine Default Types
    • Type Expressions
    • Type Inheritance
    • Multiple Inheritance (supported, but not fully compliant)
    • Inline Type Declarations
    • Defining Examples in RAML
      • Multiple Examples
      • Single Example
      • Validation against defined data type
  • Annotations
    • Declaring Annotation Types
    • Applying Annotations
      • Annotating Scalar-valued Nodes
      • Annotation Targets
      • Annotating types
  • Modularization
    • Includes
      • Library
        • NamedExample
        • DataType
        • AnnotationTypeDeclaration
        • DocumentationItem
        • ResourceType
        • Trait
        • Overlay
        • Extension
        • SecurityScheme
  • Conversion
    • Conversion to JSON Schema
    • Conversion to RAML
  • CLI
    • Validate
    • Convert to JSON Schema

Comparison to existing libraries

Table of libraries
Parser RAML 1.0 support Language
AML Modeling Framework Yes (full support) Scala/TypeScript
raml-js-parser Yes TypeScript
ramlfications No Python
go-raml Yes (partial support) Go
Performance

Complex project (7124 types, 148 libraries)

Project Type Time taken RAM taken
go-raml ~280ms ~48MB
AML Modeling Framework (TS) ~17s ~870MB

Simple project (<100 types, 1 library)

Project Type Time taken RAM taken
go-raml ~4ms ~12MB
AML Modeling Framework (TS) ~2s ~100MB

Installation

Library
go get -u github.com/acronis/go-raml
CLI

Go install

go install github.com/acronis/go-raml/cmd/raml@latest

Make install

make install

Library usage examples

Parser options

By default, parser outputs the resulting model as is and without validation. This means that information about all links and inheritance chains is unmodified. Be aware that the parser may generate recursive structures, depending on your definition, and you may need to implement recursion detection when traversing the model.

The parser currently provides two options:

  • raml.OptWithValidate() - performs validation of the resulting model (types inheritance validation, types facet validations, annotation types and instances validation, examples, defaults, instances, etc.). Also performs unwrap if raml.OptWithUnwrap() was not specified, but leaves the original types untouched.

  • raml.OptWithUnwrap() - performs an unwrap of the resulting model and replaces all definitions with unwrapped structures. Unwrap resolves the inheritance chain and links and compiles a complete type, with all properties of its parents/links.

[!NOTE] In most cases, the use of both flags is advised. If you need to access unmodified types, use only OptWithValidate(). Note that memory consumption may be higher and processing time may be longer since OptWithValidate() performs a dedicated copy and unwrap for each type.

Parsing from string

The following code will parse a RAML string, output a library model and print the common information about the defined type.

package main

import (
	"fmt"
	"log"
	"os"

	"github.com/acronis/go-raml"
)

func main() {
	// Get current working directory that will serve as a base path
	workDir, err := os.Getwd()
	if err != nil {
		log.Fatal(err)
	}

	// Define RAML 1.0 Library in a string
	content := `#%RAML 1.0 Library
types:
  BasicType: string
  ChildType:
    type: BasicType
    minLength: 5
`

	// Parse with validation
	// Here we omit OptWithUnwrap to show the difference between child and parent.
	r, err := raml.ParseFromString(content, "library.raml", workDir, raml.OptWithValidate())
	if err != nil {
		log.Fatal(err)
	}
	// Cast type to Library since our fragment is RAML 1.0 Library
	lib, _ := r.EntryPoint().(*raml.Library)
	base, _ := lib.Types.Get("ChildType")
	// Cast type to StringShape since child type inherits from a string type
	typ := base.Shape.(*raml.StringShape)
	fmt.Printf(
		"Type name: %s, type: %s, minLength: %d, location: %s\n",
		typ.Name, typ.Type, *typ.MinLength, typ.Location,
	)
	// Cast type to StringShape since parent type is string
	parentTyp := base.Inherits[0].Shape.(*raml.StringShape)
	fmt.Printf("Inherits from:\n")
	fmt.Printf(
		"Type name: %s, type: %s, minLength: %d, location: %s\n",
		parentTyp.Name, parentTyp.Type, parentTyp.MinLength, parentTyp.Location,
	)
}

The expected output is:

Type name: ChildType, type: string, minLength: 5, location: <absolute_path>/library.raml
Inherits from:
Type name: BasicType, type: string, minLength: 0, location: <absolute_path>/library.raml
Parsing from file

The following code will parse a RAML file, output a library model and print the common information about the defined type.

package main

import (
	"fmt"
	"log"

	"github.com/acronis/go-raml"
)

func main() {
	filePath := "<path_to_your_file>"
	r, err := raml.ParseFromPath(filePath, raml.OptWithValidate(), raml.OptWithUnwrap())
	if err != nil {
		log.Fatal(err)
	}
	// Assuming that the parsed fragment is a RAML Library
	lib, _ := r.EntryPoint().(*raml.Library)
	base, _ := lib.Types.Get("BasicType")
	fmt.Printf("Type name: %s, type: %s, location: %s", base.Name, base.Type, base.Location)
}
Validating data against type

Similar to JSON Schema, RAML data types provide a powerful validation mechanism against the defined type. The following simple example demonstrates how a defined type can be used to validate the values against the type.

package main

import (
	"fmt"
	"log"
	"os"

	"github.com/acronis/go-raml"
)

func main() {
	// Get current working directory that will serve as a base path
	workDir, err := os.Getwd()
	if err != nil {
		log.Fatal(err)
	}

	// Define RAML 1.0 Library in a string
	content := `#%RAML 1.0 Library
types:
  StringType:
    type: string
    minLength: 5
`

	// Parse with validation
	r, err := raml.ParseFromString(content, "library.raml", workDir, raml.OptWithValidate())
	if err != nil {
		log.Fatal(err)
	}
	// Cast type to Library since our fragment is RAML 1.0 Library
	lib, _ := r.EntryPoint().(*raml.Library)
	base, _ := lib.Types.Get("StringType")
	// Cast type to StringShape since defined type is a string
	typ := base.Shape.(*raml.StringShape)
	fmt.Printf(
		"Type name: %s, type: %s, minLength: %d, location: %s\n",
		typ.Name, typ.Type, *typ.MinLength, typ.Location,
	)
	fmt.Printf("Empty string: %v\n", base.Validate(""))
	fmt.Printf("Less than 5 characters: %v\n", base.Validate("abc"))
	fmt.Printf("More than 5 characters: %v\n", base.Validate("more than 5 chars"))
	fmt.Printf("Not a string: %v\n", base.Validate(123))
}

The expected output is:

Empty string: length must be greater than 5
Less than 5 characters: length must be greater than 5
More than 5 characters: <nil>
Not a string: invalid type, got int, expected string

CLI usage examples

Flags:

  • -v --verbosity count - increase verbosity level, one flag for each level, e.g. -v for DEBUG
  • -d --ensure-duplicates - ensure that there are no duplicates in tracebacks
Validate

The validate command validates the RAML file against the RAML 1.0 specification.

The following commands will validate the RAML files and output the validation errors.

One file

raml validate <path_to_your_file>.raml

Multiple files

raml validate <path_to_your_file1>.raml <path_to_your_file2>.raml <path_to_your_file3>.raml

Output example

% raml validate library.raml
[11:46:40.053] INFO: Validating RAML... {
  "path": "library.raml"
}
[11:46:40.060] ERROR: RAML is invalid {
  "tracebacks": {
    "traces": {
      "0": {
        "stack": {
          "0": {
            "message": "unwrap shapes",
            "position": "/tmp/library.raml:1",
            "severity": "error",
            "type": "parsing"
          },
          "1": {
            "message": "unwrap shape",
            "position": "/tmp/common.raml:15:5",
            "severity": "error",
            "type": "unwrapping"
          },
          "2": {
            "message": "merge shapes",
            "position": "/tmp/common.raml:15:5",
            "severity": "error",
            "type": "unwrapping"
          },
          "3": {
            "message": "merge shapes",
            "position": "/tmp/common.raml:15:5",
            "severity": "error",
            "type": "unwrapping"
          },
          "4": {
            "message": "inherit property: property: a",
            "position": "/tmp/common.raml:17:10",
            "severity": "error",
            "type": "unwrapping"
          },
          "5": {
            "message": "merge shapes",
            "position": "/tmp/common.raml:17:10",
            "severity": "error",
            "type": "unwrapping"
          },
          "6": {
            "message": "cannot inherit from different type: source: string: target: integer",
            "position": "/tmp/common.raml:17:10",
            "severity": "error",
            "type": "unwrapping"
          }
        }
      },
      "1": {
        "stack": {
          "0": {
            "message": "validate shapes",
            "position": "/tmp/library.raml:1",
            "severity": "error",
            "type": "parsing"
          },
          "1": {
            "message": "check type",
            "position": "/tmp/common.raml:8:5",
            "severity": "error",
            "type": "validating"
          },
          "2": {
            "message": "minProperties must be less than or equal to maxProperties",
            "position": "/tmp/common.raml:8:5",
            "severity": "error",
            "type": "validating"
          },
          "3": {
            "message": "unwrap shape",
            "position": "/tmp/common.raml:15:5",
            "severity": "error",
            "type": "validating"
          },
          "4": {
            "message": "merge shapes",
            "position": "/tmp/common.raml:15:5",
            "severity": "error",
            "type": "unwrapping"
          },
          "5": {
            "message": "merge shapes",
            "position": "/tmp/common.raml:15:5",
            "severity": "error",
            "type": "unwrapping"
          },
          "6": {
            "message": "inherit property: property: a",
            "position": "/tmp/common.raml:17:10",
            "severity": "error",
            "type": "unwrapping"
          },
          "7": {
            "message": "merge shapes",
            "position": "/tmp/common.raml:17:10",
            "severity": "error",
            "type": "unwrapping"
          },
          "8": {
            "message": "cannot inherit from different type: source: string: target: integer",
            "position": "/tmp/common.raml:17:10",
            "severity": "error",
            "type": "unwrapping"
          }
        }
      }
    }
  }
}
[11:46:40.092] ERROR: Command failed {
  "error": "errors have been found in the RAML files"
}

Documentation

Index

Constants

View Source
const (
	TypeAny          = "any"
	TypeString       = "string"
	TypeInteger      = "integer"
	TypeNumber       = "number"
	TypeBoolean      = "boolean"
	TypeDatetime     = "datetime"
	TypeDatetimeOnly = "datetime-only"
	TypeDateOnly     = "date-only"
	TypeTimeOnly     = "time-only"
	TypeArray        = "array"
	TypeObject       = "object"
	TypeFile         = "file"
	TypeNil          = "nil"
	TypeNull         = "null"
)

Standard types according to specification

View Source
const (
	TypeUnion     = "union"     // Can be used in RAML
	TypeJSON      = "json"      // Cannot be used in RAML
	TypeComposite = "composite" // Cannot be used in RAML
	TypeRecursive = "recursive" // Cannot be used in RAML
)

Special non-standard types

View Source
const (
	TagNull      = "!!null"
	TagInclude   = "!include"
	TagStr       = "!!str"
	TagTimestamp = "!!timestamp"
	TagInt       = "!!int"
)
View Source
const (
	FacetFormat               = "format"
	FacetEnum                 = "enum"
	FacetMinimum              = "minimum"
	FacetMaximum              = "maximum"
	FacetMultipleOf           = "multipleOf"
	FacetMinLength            = "minLength"
	FacetMaxLength            = "maxLength"
	FacetPattern              = "pattern"
	FacetFileTypes            = "fileTypes"
	FacetAdditionalProperties = "additionalProperties"
	FacetProperties           = "properties"
	FacetMinProperties        = "minProperties"
	FacetMaxProperties        = "maxProperties"
	FacetItems                = "items"
	FacetMinItems             = "minItems"
	FacetMaxItems             = "maxItems"
	FacetUniqueItems          = "uniqueItems"
	FacetDiscriminator        = "discriminator"
	FacetDiscriminatorValue   = "discriminatorValue"
	FacetDescription          = "description"
	FacetDisplayName          = "displayName"
	FacetStrict               = "strict"
	FacetRequired             = "required"
	FacetType                 = "type"
	FacetFacets               = "facets"
	FacetExample              = "example"
	FacetExamples             = "examples"
	FacetDefault              = "default"
	FacetAllowedTargets       = "allowedTargets"
)
View Source
const (
	DateTimeFormatRFC3339 = "rfc3339"
	DateTimeFormatRFC2616 = "rfc2616"
)
View Source
const (
	FormatDateTime = "date-time"
	FormatDate     = "date"
	FormatTime     = "time"
)
View Source
const (
	StacktraceTypeUnwrapping stacktrace.Type = "unwrapping"
	StacktraceTypeResolving  stacktrace.Type = "resolving"
	StacktraceTypeParsing    stacktrace.Type = "parsing"
	StacktraceTypeValidating stacktrace.Type = "validating"
	StacktraceTypeReading    stacktrace.Type = "reading"
	StacktraceTypeLoading    stacktrace.Type = "loading"
)
View Source
const (
	RFC2616 = "Mon, 02 Jan 2006 15:04:05 GMT"
	// NOTE: time.DateTime uses "2006-01-02 15:04:05" format which is different from date-time defined in RAML spec.
	DateTime = "2006-01-02T15:04:05"
)
View Source
const (
	ExampleValue = "value"
)
View Source
const HookBeforeBaseShapeInherit = "BaseShape.Inherit"
View Source
const HookBeforeBaseShapeInheritUnionSource = "BaseShape.inheritUnionSource"
View Source
const HookBeforeBaseShapeInheritUnionTarget = "BaseShape.inheritUnionTarget"
View Source
const HookBeforeParseDataType = "before:RAML.parseDataType"
View Source
const HookBeforeRAMLMakeConcreteShapeYAML = "before:RAML.makeConcreteShapeYAML"
View Source
const HookBeforeRAMLMakeNewShapeYAML = "before:RAML.makeNewShapeYAML"
View Source
const JSONSchemaVersion = "http://json-schema.org/draft-07/schema"

Version is the JSON Schema version.

Variables

View Source
var (
	// TrueSchema defines a schema with a true value
	TrueSchema = &JSONSchema{boolean: &[]bool{true}[0]}
	// FalseSchema defines a schema with a false value
	FalseSchema = &JSONSchema{boolean: &[]bool{false}[0]}
)
View Source
var ErrNil error
View Source
var ErrValueKeyNotFound = errors.New("value key not found")
View Source
var SetOfDateTimeFormats = map[string]struct{}{
	"rfc3339": {}, "rfc2616": {},
}

SetOfDateTimeFormats contains a set of date-time formats

View Source
var SetOfIntegerFormats = map[string]int8{

	"int8": 0, "int16": 1, "int32": 2, "int": 2, "int64": 3, "long": 3,
}

SetOfIntegerFormats contains a set of integer formats

View Source
var SetOfNumberFormats = map[string]struct{}{
	"float": {}, "double": {},
}

SetOfNumberFormats contains a set of number formats

View Source
var SetOfScalarTypes = map[string]struct{}{
	TypeString: {}, TypeInteger: {}, TypeNumber: {}, TypeBoolean: {}, TypeDatetime: {}, TypeDatetimeOnly: {},
	TypeDateOnly: {}, TypeTimeOnly: {}, TypeFile: {},
}

SetOfScalarTypes contains a set of scalar types

Functions

func CheckFragmentKind

func CheckFragmentKind(f *os.File, kind FragmentKind) error

func CutReferenceName added in v0.12.0

func CutReferenceName(refName string) (string, string, bool)

CutReferenceName cuts a reference name into two parts: before and after the dot.

func FixYamlError

func FixYamlError(err error) error

FixYamlError fixes the yaml type error from the given error.

func GetYamlError

func GetYamlError(err error) *yaml.TypeError

GetYamlError returns the yaml type error from the given error. nil if the error is not a yaml type error.

func IsCustomDomainExtensionNode

func IsCustomDomainExtensionNode(name string) bool

func NewNodePosition

func NewNodePosition(node *yaml.Node) *stacktrace.Position

NewNodePosition creates a new position from the given node.

func ReadHead

func ReadHead(f io.ReadSeeker) (string, error)

ReadHead reads, reset file and returns the trimmed first line of a file.

func ReadRawFile

func ReadRawFile(path string) (io.ReadCloser, error)

ReadRawFile reads a file

func StacktraceNew added in v0.14.0

func StacktraceNew(msg string, location string, opts ...stacktrace.Option) *stacktrace.StackTrace

func StacktraceNewWrapped added in v0.9.0

func StacktraceNewWrapped(msg string, err error, location string, opts ...stacktrace.Option) *stacktrace.StackTrace

func WithNodePosition

func WithNodePosition(node *yaml.Node) stacktrace.Option

WithNodePosition sets the position of the error to the position of the given node.

Types

type AnyShape

type AnyShape struct {
	*BaseShape
	// contains filtered or unexported fields
}

func (*AnyShape) Base

func (s *AnyShape) Base() *BaseShape

func (AnyShape) IsScalar added in v0.13.1

func (AnyShape) IsScalar() bool

type ArrayFacets

type ArrayFacets struct {
	Items       *BaseShape
	MinItems    *uint64
	MaxItems    *uint64
	UniqueItems *bool
}

ArrayFacets contains constraints for array shapes.

type ArrayShape

type ArrayShape struct {
	*BaseShape

	ArrayFacets
	// contains filtered or unexported fields
}

ArrayShape represents an array shape.

func (*ArrayShape) Base

func (s *ArrayShape) Base() *BaseShape

Base returns the base shape.

func (ArrayShape) IsScalar added in v0.13.1

func (ArrayShape) IsScalar() bool

type BaseShape

type BaseShape struct {
	Shape
	ID          int64
	Name        string
	DisplayName *string
	Description *string
	// TODO: Move Type to underlying Shape
	Type      string
	TypeLabel string // Used to store the label either the link or type value
	Example   *Example
	Examples  *Examples
	Inherits  []*BaseShape
	Alias     *BaseShape
	Default   *Node
	Required  *bool

	// To support !include of DataType fragment
	Link *DataType

	// CustomShapeFacets is a map of custom facets with values
	CustomShapeFacets *orderedmap.OrderedMap[string, *Node]
	// CustomShapeFacetDefinitions is an object properties share the same syntax with custom shape facets.
	CustomShapeFacetDefinitions *orderedmap.OrderedMap[string, Property]
	// CustomDomainProperties is a map of custom annotations
	CustomDomainProperties *orderedmap.OrderedMap[string, *DomainExtension]

	// NOTE: Not thread safe and should be used only in one method simultaneously.
	ShapeVisited bool

	Location string
	stacktrace.Position
	// contains filtered or unexported fields
}

func (*BaseShape) AliasTo added in v0.12.0

func (s *BaseShape) AliasTo(source *BaseShape) *BaseShape

func (*BaseShape) AppendRAMLHook added in v0.13.1

func (s *BaseShape) AppendRAMLHook(key HookKey, hook HookFunc)

func (*BaseShape) Check added in v0.12.0

func (s *BaseShape) Check() error

Check returns an error if type shape is invalid.

func (*BaseShape) ClearRAMLHooks added in v0.13.1

func (s *BaseShape) ClearRAMLHooks(key HookKey)

func (*BaseShape) Clone added in v0.12.0

func (s *BaseShape) Clone(clonedMap map[int64]*BaseShape) *BaseShape

Clone creates a deep copy of the shape.

Use this method to make a deep copy of the shape while preserving the relationships between shapes. Passed cloned map will be populated with cloned shape IDs that can be reused in subsequent Clone calls.

NOTE: If you need a completely independent copy of a shape, use CloneDetached method.

func (*BaseShape) CloneDetached added in v0.12.0

func (s *BaseShape) CloneDetached() *BaseShape

CloneDetached creates a detached deep copy of the shape.

Detached copy makes a deep copy of the shape, including parents, links and aliases. This makes the copied shape and its references completely independent from the original tree.

NOTE: To avoid excessive memory copies and allocation, this method must be used only when an independent shape copy is required. Otherwise, use Clone method.

func (*BaseShape) CloneShallow added in v0.15.0

func (s *BaseShape) CloneShallow() *BaseShape

CloneShallow creates a shallow copy of the shape.

func (*BaseShape) Inherit added in v0.12.0

func (s *BaseShape) Inherit(sourceBase *BaseShape) (*BaseShape, error)

func (*BaseShape) IsUnwrapped

func (s *BaseShape) IsUnwrapped() bool

IsUnwrapped returns true if the shape is unwrapped.

func (*BaseShape) PrepenRAMLHook added in v0.13.1

func (s *BaseShape) PrepenRAMLHook(key HookKey, hook HookFunc)

func (*BaseShape) RemoveRAMLHook added in v0.13.1

func (s *BaseShape) RemoveRAMLHook(key HookKey, hook HookFunc)

func (*BaseShape) SetShape added in v0.12.0

func (s *BaseShape) SetShape(shape Shape)

func (*BaseShape) SetUnwrapped added in v0.13.0

func (s *BaseShape) SetUnwrapped()

func (*BaseShape) String

func (s *BaseShape) String() string

String implements fmt.Stringer.

func (*BaseShape) Validate added in v0.12.0

func (s *BaseShape) Validate(v interface{}) error

type BooleanShape

type BooleanShape struct {
	*BaseShape

	EnumFacets
	// contains filtered or unexported fields
}

func (*BooleanShape) Base

func (s *BooleanShape) Base() *BaseShape

func (BooleanShape) IsScalar added in v0.13.1

func (BooleanShape) IsScalar() bool

type CustomErrorListener added in v0.13.1

type CustomErrorListener struct {
	*antlr.DefaultErrorListener // Embed default which ensures we fit the interface
	Stacktrace                  *stacktrace.StackTrace
	// contains filtered or unexported fields
}

func (*CustomErrorListener) SyntaxError added in v0.13.1

func (c *CustomErrorListener) SyntaxError(
	_ antlr.Recognizer,
	offendingSymbol interface{},
	_, _ int,
	msg string,
	_ antlr.RecognitionException,
)

type DataType

type DataType struct {
	ID    string
	Usage string
	Uses  *orderedmap.OrderedMap[string, *LibraryLink]
	Shape *BaseShape

	Location string
	// contains filtered or unexported fields
}

DataType is the RAML 1.0 DataType

func (*DataType) GetLocation

func (dt *DataType) GetLocation() string

func (*DataType) GetReferenceAnnotationType added in v0.12.0

func (dt *DataType) GetReferenceAnnotationType(refName string) (*BaseShape, error)

GetReferenceAnnotationType returns a reference annotation type by name, implementing the ReferenceAnnotationTypeGetter interface

func (*DataType) GetReferenceType added in v0.12.0

func (dt *DataType) GetReferenceType(refName string) (*BaseShape, error)

GetReferenceType returns a reference type by name, implementing the ReferenceTypeGetter interface

func (*DataType) UnmarshalYAML

func (dt *DataType) UnmarshalYAML(value *yaml.Node) error

type DateOnlyShape

type DateOnlyShape struct {
	*BaseShape
	// contains filtered or unexported fields
}

func (*DateOnlyShape) Base

func (s *DateOnlyShape) Base() *BaseShape

func (DateOnlyShape) IsScalar added in v0.13.1

func (DateOnlyShape) IsScalar() bool

type DateTimeOnlyShape

type DateTimeOnlyShape struct {
	*BaseShape
	// contains filtered or unexported fields
}

func (*DateTimeOnlyShape) Base

func (s *DateTimeOnlyShape) Base() *BaseShape

func (DateTimeOnlyShape) IsScalar added in v0.13.1

func (DateTimeOnlyShape) IsScalar() bool

type DateTimeShape

type DateTimeShape struct {
	*BaseShape

	FormatFacets
	// contains filtered or unexported fields
}

func (*DateTimeShape) Base

func (s *DateTimeShape) Base() *BaseShape

func (DateTimeShape) IsScalar added in v0.13.1

func (DateTimeShape) IsScalar() bool

type Definitions

type Definitions map[string]*JSONSchema

Definitions hold schema definitions. http://json-schema.org/latest/json-schema-validation.html#rfc.section.5.26 RFC draft-wright-json-schema-validation-00, section 5.26

type DomainExtension

type DomainExtension struct {
	ID        string
	Name      string
	Extension *Node
	DefinedBy *BaseShape

	Location string
	stacktrace.Position
	// contains filtered or unexported fields
}

type EnumFacets

type EnumFacets struct {
	Enum Nodes
}

type Example

type Example struct {
	ID          string
	Name        string
	DisplayName string
	Description string
	Data        *Node

	Strict                 bool
	CustomDomainProperties *orderedmap.OrderedMap[string, *DomainExtension]

	Location string
	stacktrace.Position
	// contains filtered or unexported fields
}

Example represents an example of a shape

type Examples

type Examples struct {
	ID  string
	Map *orderedmap.OrderedMap[string, *Example]

	// To support !include of NamedExample fragment
	Link *NamedExample

	Location string
	stacktrace.Position
}

Examples represents a collection of examples.

type FileFacets

type FileFacets struct {
	FileTypes Nodes
}

type FileShape

type FileShape struct {
	*BaseShape

	LengthFacets
	FileFacets
	// contains filtered or unexported fields
}

func (*FileShape) Base

func (s *FileShape) Base() *BaseShape

func (FileShape) IsScalar added in v0.13.1

func (FileShape) IsScalar() bool

type FormatFacets

type FormatFacets struct {
	Format *string
}

type FragmentKind

type FragmentKind int
const (
	FragmentUnknown FragmentKind = iota - 1
	FragmentLibrary
	FragmentDataType
	FragmentNamedExample
)

func IdentifyFragment

func IdentifyFragment(head string) (FragmentKind, error)

IdentifyFragment returns the kind of the fragment by its head.

type HookFunc added in v0.13.1

type HookFunc func(ctx context.Context, r *RAML, params ...any) error

type HookKey added in v0.13.1

type HookKey string
const HookBeforeFindAndMarkRecursion HookKey = "RAML.FindAndMarkRecursion"
const HookBeforeUnwrapShape HookKey = "RAML.UnwrapShape"
const HookBeforeValidateDataType HookKey = "RAML.validateDataType"
const HookBeforeValidateDomainExtensions HookKey = "RAML.validateDomainExtensions"
const HookBeforeValidateExamples HookKey = "RAML.validateExamples"
const HookBeforeValidateFragments HookKey = "RAML.validateFragments"
const HookBeforeValidateLibrary HookKey = "RAML.validateLibrary"
const HookBeforeValidateObjectShape HookKey = "RAML.validateObjectShape"
const HookBeforeValidateShapeCommons HookKey = "RAML.validateShapeCommons"
const HookBeforeValidateShapeFacets HookKey = "RAML.validateShapeFacets"
const HookBeforeValidateShapes HookKey = "RAML.ValidateShapes"
const HookBeforeValidateTypes HookKey = "RAML.validateTypes"

type IntegerFacets

type IntegerFacets struct {
	Minimum    *big.Int
	Maximum    *big.Int
	MultipleOf *float64
}

type IntegerShape

type IntegerShape struct {
	*BaseShape

	EnumFacets
	FormatFacets
	IntegerFacets
	// contains filtered or unexported fields
}

func (*IntegerShape) Base

func (s *IntegerShape) Base() *BaseShape

func (IntegerShape) IsScalar added in v0.13.1

func (IntegerShape) IsScalar() bool

type JSONSchema

type JSONSchema struct {
	Version     string      `json:"$schema,omitempty"`
	ID          string      `json:"$id,omitempty"`
	Ref         string      `json:"$ref,omitempty"`
	Definitions Definitions `json:"definitions,omitempty"`
	Comment     string      `json:"$comment,omitempty"`

	AllOf []*JSONSchema `json:"allOf,omitempty"`
	AnyOf []*JSONSchema `json:"anyOf,omitempty"`
	OneOf []*JSONSchema `json:"oneOf,omitempty"`
	Not   *JSONSchema   `json:"not,omitempty"`

	If   *JSONSchema `json:"if,omitempty"`
	Then *JSONSchema `json:"then,omitempty"`
	Else *JSONSchema `json:"else,omitempty"`

	Items *JSONSchema `json:"items,omitempty"`

	Properties           *orderedmap.OrderedMap[string, *JSONSchema] `json:"properties,omitempty"`
	PatternProperties    *orderedmap.OrderedMap[string, *JSONSchema] `json:"patternProperties,omitempty"`
	AdditionalProperties *bool                                       `json:"additionalProperties,omitempty"`
	PropertyNames        *JSONSchema                                 `json:"propertyNames,omitempty"`

	Type             string      `json:"type,omitempty"`
	Enum             []any       `json:"enum,omitempty"`
	Const            any         `json:"const,omitempty"`
	MultipleOf       json.Number `json:"multipleOf,omitempty"`
	Maximum          json.Number `json:"maximum,omitempty"`
	Minimum          json.Number `json:"minimum,omitempty"`
	MaxLength        *uint64     `json:"maxLength,omitempty"`
	MinLength        *uint64     `json:"minLength,omitempty"`
	Pattern          string      `json:"pattern,omitempty"`
	MaxItems         *uint64     `json:"maxItems,omitempty"`
	MinItems         *uint64     `json:"minItems,omitempty"`
	UniqueItems      *bool       `json:"uniqueItems,omitempty"`
	MaxContains      *uint64     `json:"maxContains,omitempty"`
	MinContains      *uint64     `json:"minContains,omitempty"`
	MaxProperties    *uint64     `json:"maxProperties,omitempty"`
	MinProperties    *uint64     `json:"minProperties,omitempty"`
	Required         []string    `json:"required,omitempty"`
	ContentEncoding  string      `json:"contentEncoding,omitempty"`
	ContentMediaType string      `json:"contentMediaType,omitempty"`

	Format string `json:"format,omitempty"`

	Title       string `json:"title,omitempty"`
	Description string `json:"description,omitempty"`
	Default     any    `json:"default,omitempty"`
	Examples    []any  `json:"examples,omitempty"`

	// TODO: There's no better way to serialize custom properties on the same level in Go.
	Extras map[string]any `json:"x-custom,omitempty"`
	// contains filtered or unexported fields
}

Schema represents a JSON Schema object type.

https://json-schema.org/draft-07/draft-handrews-json-schema-00.pdf

type JSONSchemaConverter

type JSONSchemaConverter struct {
	ShapeVisitor[JSONSchema]
	// contains filtered or unexported fields
}

func NewJSONSchemaConverter

func NewJSONSchemaConverter(opts ...JSONSchemaConverterOpt) *JSONSchemaConverter

func (*JSONSchemaConverter) Convert

func (c *JSONSchemaConverter) Convert(s Shape) (*JSONSchema, error)

func (*JSONSchemaConverter) Visit

func (c *JSONSchemaConverter) Visit(s Shape) *JSONSchema

func (*JSONSchemaConverter) VisitAnyShape

func (c *JSONSchemaConverter) VisitAnyShape(s *AnyShape) *JSONSchema

func (*JSONSchemaConverter) VisitArrayShape

func (c *JSONSchemaConverter) VisitArrayShape(s *ArrayShape) *JSONSchema

func (*JSONSchemaConverter) VisitBooleanShape

func (c *JSONSchemaConverter) VisitBooleanShape(s *BooleanShape) *JSONSchema

func (*JSONSchemaConverter) VisitDateOnlyShape

func (c *JSONSchemaConverter) VisitDateOnlyShape(s *DateOnlyShape) *JSONSchema

func (*JSONSchemaConverter) VisitDateTimeOnlyShape

func (c *JSONSchemaConverter) VisitDateTimeOnlyShape(s *DateTimeOnlyShape) *JSONSchema

func (*JSONSchemaConverter) VisitDateTimeShape

func (c *JSONSchemaConverter) VisitDateTimeShape(s *DateTimeShape) *JSONSchema

func (*JSONSchemaConverter) VisitFileShape

func (c *JSONSchemaConverter) VisitFileShape(s *FileShape) *JSONSchema

func (*JSONSchemaConverter) VisitIntegerShape

func (c *JSONSchemaConverter) VisitIntegerShape(s *IntegerShape) *JSONSchema

func (*JSONSchemaConverter) VisitJSONShape

func (c *JSONSchemaConverter) VisitJSONShape(s *JSONShape) *JSONSchema

func (*JSONSchemaConverter) VisitNilShape

func (c *JSONSchemaConverter) VisitNilShape(s *NilShape) *JSONSchema

func (*JSONSchemaConverter) VisitNumberShape

func (c *JSONSchemaConverter) VisitNumberShape(s *NumberShape) *JSONSchema

func (*JSONSchemaConverter) VisitObjectShape

func (c *JSONSchemaConverter) VisitObjectShape(s *ObjectShape) *JSONSchema

func (*JSONSchemaConverter) VisitRecursiveShape

func (c *JSONSchemaConverter) VisitRecursiveShape(s *RecursiveShape) *JSONSchema

func (*JSONSchemaConverter) VisitStringShape

func (c *JSONSchemaConverter) VisitStringShape(s *StringShape) *JSONSchema

func (*JSONSchemaConverter) VisitTimeOnlyShape

func (c *JSONSchemaConverter) VisitTimeOnlyShape(s *TimeOnlyShape) *JSONSchema

func (*JSONSchemaConverter) VisitUnionShape

func (c *JSONSchemaConverter) VisitUnionShape(s *UnionShape) *JSONSchema

type JSONSchemaConverterOpt

type JSONSchemaConverterOpt interface {
	Apply(*JSONSchemaConverterOptions)
}

func WithOmitRefs

func WithOmitRefs(omitRefs bool) JSONSchemaConverterOpt

type JSONSchemaConverterOptions

type JSONSchemaConverterOptions struct {
	// contains filtered or unexported fields
}

type JSONShape

type JSONShape struct {
	*BaseShape

	Schema *JSONSchema
	Raw    string
	// contains filtered or unexported fields
}

func (*JSONShape) Base

func (s *JSONShape) Base() *BaseShape

func (JSONShape) IsScalar added in v0.13.1

func (JSONShape) IsScalar() bool

type LengthFacets

type LengthFacets struct {
	MaxLength *uint64
	MinLength *uint64
}

type Library

type Library struct {
	ID              string
	Usage           string
	AnnotationTypes *orderedmap.OrderedMap[string, *BaseShape]
	// TODO: Specific to API fragments. Not supported yet.
	// ResourceTypes   map[string]interface{} `yaml:"resourceTypes"`
	Types *orderedmap.OrderedMap[string, *BaseShape]
	Uses  *orderedmap.OrderedMap[string, *LibraryLink]

	CustomDomainProperties *orderedmap.OrderedMap[string, *DomainExtension]

	Location string
	// contains filtered or unexported fields
}

Library is the RAML 1.0 Library

func (*Library) GetLocation

func (l *Library) GetLocation() string

func (*Library) GetReferenceAnnotationType added in v0.12.0

func (l *Library) GetReferenceAnnotationType(refName string) (*BaseShape, error)

GetReferenceAnnotationType returns a reference annotation type by name, implementing the ReferenceAnnotationTypeGetter interface

func (*Library) GetReferenceType added in v0.12.0

func (l *Library) GetReferenceType(refName string) (*BaseShape, error)

GetReferenceType returns a reference type by name, implementing the ReferenceTypeGetter interface

func (*Library) UnmarshalYAML

func (l *Library) UnmarshalYAML(value *yaml.Node) error

UnmarshalYAML unmarshals a Library from a yaml.Node, implementing the yaml.Unmarshaler interface

type LibraryLink struct {
	ID    string
	Value string

	Link *Library

	Location string
	stacktrace.Position
}

type LocationGetter

type LocationGetter interface {
	GetLocation() string
}

type MockShape added in v0.13.1

type MockShape struct {
	BaseShape              *BaseShape
	MockInherit            func(source Shape) (Shape, error)
	MockCheck              func() error
	MockClone              func(base *BaseShape, clonedMap map[int64]*BaseShape) Shape
	MockValidate           func(v interface{}, ctxPath string) error
	MockUnmarshalYAMLNodes func(v []*yaml.Node) error
	MockString             func() string
	MockIsScalar           func() bool
}

MockShape is a mock implementation of the Shape interface

func (MockShape) Base added in v0.13.1

func (u MockShape) Base() *BaseShape

func (MockShape) IsScalar added in v0.13.1

func (u MockShape) IsScalar() bool

func (MockShape) String added in v0.13.1

func (u MockShape) String() string

type NamedExample

type NamedExample struct {
	ID  string
	Map *orderedmap.OrderedMap[string, *Example]

	Location string
	// contains filtered or unexported fields
}

NamedExample is the RAML 1.0 NamedExample

func (*NamedExample) GetLocation

func (ne *NamedExample) GetLocation() string

func (*NamedExample) GetReferenceAnnotationType added in v0.12.0

func (ne *NamedExample) GetReferenceAnnotationType(_ string) (*BaseShape, error)

GetReferenceAnnotationType returns a reference annotation type by name, implementing the ReferenceAnnotationTypeGetter interface

func (*NamedExample) GetReferenceType added in v0.12.0

func (ne *NamedExample) GetReferenceType(_ string) (*BaseShape, error)

GetReferenceType returns a reference type by name, implementing the ReferenceTypeGetter interface

func (*NamedExample) UnmarshalYAML

func (ne *NamedExample) UnmarshalYAML(value *yaml.Node) error

type NilShape

type NilShape struct {
	*BaseShape
	// contains filtered or unexported fields
}

func (*NilShape) Base

func (s *NilShape) Base() *BaseShape

func (NilShape) IsScalar added in v0.13.1

func (NilShape) IsScalar() bool

type Node

type Node struct {
	ID    string
	Value any

	Location string
	stacktrace.Position
	// contains filtered or unexported fields
}

func (*Node) String

func (n *Node) String() string

type Nodes

type Nodes []*Node

func (Nodes) String

func (n Nodes) String() string

type NumberFacets

type NumberFacets struct {
	// Minimum and maximum are unset since there's no theoretical minimum and maximum for numbers by default
	Minimum    *float64
	Maximum    *float64
	MultipleOf *float64
}

type NumberShape

type NumberShape struct {
	*BaseShape

	EnumFacets
	FormatFacets
	NumberFacets
	// contains filtered or unexported fields
}

func (*NumberShape) Base

func (s *NumberShape) Base() *BaseShape

func (NumberShape) IsScalar added in v0.13.1

func (NumberShape) IsScalar() bool

type ObjectFacets

type ObjectFacets struct {
	Discriminator        *string
	DiscriminatorValue   any
	AdditionalProperties *bool
	Properties           *orderedmap.OrderedMap[string, Property]
	PatternProperties    *orderedmap.OrderedMap[string, PatternProperty]
	MinProperties        *uint64
	MaxProperties        *uint64
}

ObjectFacets contains constraints for object shapes.

type ObjectShape

type ObjectShape struct {
	*BaseShape

	ObjectFacets
	// contains filtered or unexported fields
}

ObjectShape represents an object shape.

func (*ObjectShape) Base

func (s *ObjectShape) Base() *BaseShape

Base returns the base shape.

func (ObjectShape) IsScalar added in v0.13.1

func (ObjectShape) IsScalar() bool

type ParseOpt

type ParseOpt interface {
	Apply(*parserOptions)
}

func OptWithUnwrap

func OptWithUnwrap() ParseOpt

func OptWithValidate

func OptWithValidate() ParseOpt

type PatternProperty

type PatternProperty struct {
	Pattern *regexp.Regexp
	Base    *BaseShape
	// contains filtered or unexported fields
}

Property represents a pattern property of an object shape.

type Property

type Property struct {
	Name     string
	Base     *BaseShape
	Required bool
	// contains filtered or unexported fields
}

Property represents a property of an object shape.

type RAML

type RAML struct {
	// contains filtered or unexported fields
}

RAML is a store for all fragments and shapes. WARNING: Not thread-safe

func New

func New(ctx context.Context) *RAML

New creates a new RAML.

func ParseFromPath

func ParseFromPath(path string, opts ...ParseOpt) (*RAML, error)

func ParseFromPathCtx

func ParseFromPathCtx(ctx context.Context, path string, opts ...ParseOpt) (*RAML, error)

func ParseFromString

func ParseFromString(content string, fileName string, baseDir string, opts ...ParseOpt) (*RAML, error)

func ParseFromStringCtx

func ParseFromStringCtx(
	ctx context.Context, content string, fileName string,
	baseDir string, opts ...ParseOpt,
) (*RAML, error)

func (*RAML) AppendHook added in v0.13.1

func (r *RAML) AppendHook(key HookKey, hook HookFunc)

func (*RAML) ClearHooks added in v0.13.1

func (r *RAML) ClearHooks(key HookKey)

func (*RAML) EntryPoint

func (r *RAML) EntryPoint() Fragment

EntryPoint returns the entry point of the RAML.

func (*RAML) FindAndMarkRecursion added in v0.12.0

func (r *RAML) FindAndMarkRecursion(base *BaseShape) (*BaseShape, error)

FindAndMarkRecursion finds and marks recursion in the shape.

func (*RAML) GetAllAnnotations

func (r *RAML) GetAllAnnotations() []DomainExtension

GetAllAnnotations returns all annotations.

func (*RAML) GetAllAnnotationsPtr

func (r *RAML) GetAllAnnotationsPtr() []*DomainExtension

GetAllAnnotationsPtr returns all annotations as pointers.

func (*RAML) GetAnnotationTypeFromFragmentPtr

func (r *RAML) GetAnnotationTypeFromFragmentPtr(location string, typeName string) (*BaseShape, error)

GetTypeFromFragmentPtr returns a shape from a fragment.

func (*RAML) GetFragment

func (r *RAML) GetFragment(location string) Fragment

GetFragment returns a fragment.

func (*RAML) GetFragmentTypePtrs

func (r *RAML) GetFragmentTypePtrs(location string) map[string]*BaseShape

GetFragmentTypePtrs returns fragment shapes as pointers.

func (*RAML) GetLocation

func (r *RAML) GetLocation() string

GetLocation returns the location of the RAML.

func (*RAML) GetReferencedAnnotationType added in v0.12.0

func (r *RAML) GetReferencedAnnotationType(refName string, location string) (*BaseShape, error)

func (*RAML) GetReferencedType added in v0.12.0

func (r *RAML) GetReferencedType(refName string, location string) (*BaseShape, error)

func (*RAML) GetShapes

func (r *RAML) GetShapes() []*BaseShape

Shapes returns all shapes.

func (*RAML) GetTypeFromFragmentPtr

func (r *RAML) GetTypeFromFragmentPtr(location string, typeName string) (*BaseShape, error)

GetTypeFromFragmentPtr returns a shape from a fragment as a pointer.

func (*RAML) MakeBaseShape

func (r *RAML) MakeBaseShape(name string, location string, position *stacktrace.Position) *BaseShape

MakeBaseShape creates a new base shape which is a base for all shapes.

func (*RAML) MakeConcreteShapeYAML added in v0.12.0

func (r *RAML) MakeConcreteShapeYAML(base *BaseShape, shapeType string, shapeFacets []*yaml.Node) (Shape, error)

MakeConcreteShapeYAML creates a new concrete shape.

func (*RAML) MakeDataType

func (r *RAML) MakeDataType(path string) *DataType

func (*RAML) MakeEnum

func (r *RAML) MakeEnum(v *yaml.Node, location string) (Nodes, error)

func (*RAML) MakeJSONDataType added in v0.11.0

func (r *RAML) MakeJSONDataType(value []byte, path string) (*DataType, error)

func (*RAML) MakeJSONShape

func (r *RAML) MakeJSONShape(base *BaseShape, rawSchema string) (*JSONShape, error)

func (*RAML) MakeLibrary

func (r *RAML) MakeLibrary(path string) *Library

func (*RAML) MakeNamedExample

func (r *RAML) MakeNamedExample(path string) *NamedExample

func (*RAML) MakeNewShape added in v0.12.0

func (r *RAML) MakeNewShape(
	name string,
	shapeType string,
	location string,
	position *stacktrace.Position,
) (*BaseShape, Shape, error)

func (*RAML) MakeRecursiveShape added in v0.12.0

func (r *RAML) MakeRecursiveShape(headBase *BaseShape) *BaseShape

func (*RAML) ParseFromPath

func (r *RAML) ParseFromPath(path string, opts ...ParseOpt) error

func (*RAML) ParseFromString

func (r *RAML) ParseFromString(content string, fileName string, baseDir string, opts ...ParseOpt) error

func (*RAML) PrependHook added in v0.13.1

func (r *RAML) PrependHook(key HookKey, hook HookFunc)

func (*RAML) PutAnnotationTypeIntoFragment

func (r *RAML) PutAnnotationTypeIntoFragment(name string, location string, shape *BaseShape)

PutTypeIntoFragment puts a shape into a fragment.

func (*RAML) PutFragment

func (r *RAML) PutFragment(location string, fragment Fragment)

PutFragment puts a fragment.

func (*RAML) PutShape added in v0.12.0

func (r *RAML) PutShape(shape *BaseShape)

func (*RAML) PutTypeIntoFragment

func (r *RAML) PutTypeIntoFragment(name string, location string, shape *BaseShape)

PutTypeIntoFragment puts a shape into a fragment.

func (*RAML) RemoveHook added in v0.13.1

func (r *RAML) RemoveHook(key HookKey, hook HookFunc)

func (*RAML) SetEntryPoint

func (r *RAML) SetEntryPoint(entryPoint Fragment) *RAML

SetEntryPoint sets the entry point of the RAML.

func (*RAML) UnwrapShape

func (r *RAML) UnwrapShape(base *BaseShape) (*BaseShape, error)

UnwrapShape recursively copies and unwraps a shape in-place. Use Clone() to create a copy of a shape if necessary. Note that this method removes information about links.

func (*RAML) UnwrapShapes

func (r *RAML) UnwrapShapes() error

UnwrapShapes unwraps all shapes in the RAML in-place.

func (*RAML) ValidateShapes

func (r *RAML) ValidateShapes() error

type RdtVisitor

type RdtVisitor struct {
	rdt.BaserdtParserVisitor // Embedding the base visitor class
	// contains filtered or unexported fields
}

RdtVisitor defines a struct that implements the visitor

func NewRdtVisitor

func NewRdtVisitor(rml *RAML) *RdtVisitor

func (*RdtVisitor) Visit

func (visitor *RdtVisitor) Visit(tree antlr.ParseTree, target *UnknownShape) (Shape, error)

func (*RdtVisitor) VisitArray

func (visitor *RdtVisitor) VisitArray(ctx *rdt.ArrayContext, target *UnknownShape) (Shape, error)

func (*RdtVisitor) VisitChildren

func (visitor *RdtVisitor) VisitChildren(node antlr.RuleNode, target *UnknownShape) ([]*BaseShape, error)

func (*RdtVisitor) VisitEntrypoint

func (visitor *RdtVisitor) VisitEntrypoint(ctx *rdt.EntrypointContext, target *UnknownShape) (Shape, error)

func (*RdtVisitor) VisitExpression

func (visitor *RdtVisitor) VisitExpression(ctx *rdt.ExpressionContext, target *UnknownShape) (Shape, error)

func (*RdtVisitor) VisitGroup

func (visitor *RdtVisitor) VisitGroup(ctx *rdt.GroupContext, target *UnknownShape) (Shape, error)

func (*RdtVisitor) VisitOptional

func (visitor *RdtVisitor) VisitOptional(ctx *rdt.OptionalContext, target *UnknownShape) (Shape, error)

func (*RdtVisitor) VisitPrimitive

func (visitor *RdtVisitor) VisitPrimitive(ctx *rdt.PrimitiveContext, target *UnknownShape) (Shape, error)

func (*RdtVisitor) VisitReference

func (visitor *RdtVisitor) VisitReference(ctx *rdt.ReferenceContext, target *UnknownShape) (Shape, error)

func (*RdtVisitor) VisitType

func (visitor *RdtVisitor) VisitType(ctx *rdt.TypeContext, target *UnknownShape) (Shape, error)

func (*RdtVisitor) VisitUnion

func (visitor *RdtVisitor) VisitUnion(ctx *rdt.UnionContext, target *UnknownShape) (Shape, error)

type RecursiveShape

type RecursiveShape struct {
	*BaseShape

	Head *BaseShape
	// contains filtered or unexported fields
}

func (*RecursiveShape) Base

func (s *RecursiveShape) Base() *BaseShape

func (RecursiveShape) IsScalar added in v0.13.1

func (RecursiveShape) IsScalar() bool

type ReferenceAnnotationTypeGetter added in v0.12.0

type ReferenceAnnotationTypeGetter interface {
	GetReferenceAnnotationType(refName string) (*BaseShape, error)
}

type ReferenceTypeGetter added in v0.12.0

type ReferenceTypeGetter interface {
	GetReferenceType(refName string) (*BaseShape, error)
}

type Shape

type Shape interface {
	// Inherit is a ShapeInheritor
	ShapeInheritor
	ShapeBaser
	ShapeChecker
	// ShapeCloner Clones the shape and its children and points to specified base shape.
	ShapeCloner
	ShapeValidator

	fmt.Stringer
	IsScalar() bool
	// contains filtered or unexported methods
}

Shape is the interface that represents a RAML shape.

type ShapeBaser

type ShapeBaser interface {
	Base() *BaseShape
}

ShapeBaser is the interface that represents a retriever of a base shape.

type ShapeChecker

type ShapeChecker interface {
	// contains filtered or unexported methods
}

type ShapeCloner

type ShapeCloner interface {
	// contains filtered or unexported methods
}

ShapeCloner is the interface that provide clone implementation for a RAML shape.

type ShapeInheritor

type ShapeInheritor interface {
	// contains filtered or unexported methods
}

ShapeInheritor is the interface that represents an inheritor of a RAML shape.

type ShapeSetter added in v0.12.0

type ShapeSetter interface {
	SetShape(Shape)
}

type ShapeValidator

type ShapeValidator interface {
	// contains filtered or unexported methods
}

ShapeValidator is the interface that represents a validator of a RAML shape.

type ShapeVisitor

type ShapeVisitor[T any] interface {
	VisitObjectShape(s *ObjectShape) T
	VisitArrayShape(s *ArrayShape) T
	VisitStringShape(s *StringShape) T
	VisitNumberShape(s *NumberShape) T
	VisitIntegerShape(s *IntegerShape) T
	VisitBooleanShape(s *BooleanShape) T
	VisitFileShape(s *FileShape) T
	VisitUnionShape(s *UnionShape) T
	VisitDateTimeShape(s *DateTimeShape) T
	VisitDateTimeOnlyShape(s *DateTimeOnlyShape) T
	VisitDateOnlyShape(s *DateOnlyShape) T
	VisitTimeOnlyShape(s *TimeOnlyShape) T
	VisitRecursiveShape(s *RecursiveShape) T
	VisitJSONShape(s *JSONShape) T
	VisitAnyShape(s *AnyShape) T
	VisitNilShape(s *NilShape) T
}

type StringFacets

type StringFacets struct {
	LengthFacets
	Pattern *regexp.Regexp
}

type StringShape

type StringShape struct {
	*BaseShape

	EnumFacets
	StringFacets
	// contains filtered or unexported fields
}

func (*StringShape) Base

func (s *StringShape) Base() *BaseShape

func (StringShape) IsScalar added in v0.13.1

func (StringShape) IsScalar() bool

type TimeOnlyShape

type TimeOnlyShape struct {
	*BaseShape
	// contains filtered or unexported fields
}

func (*TimeOnlyShape) Base

func (s *TimeOnlyShape) Base() *BaseShape

func (TimeOnlyShape) IsScalar added in v0.13.1

func (TimeOnlyShape) IsScalar() bool

type UnionFacets

type UnionFacets struct {
	AnyOf []*BaseShape
}

UnionFacets contains constraints for union shapes.

type UnionShape

type UnionShape struct {
	*BaseShape

	EnumFacets
	UnionFacets
	// contains filtered or unexported fields
}

UnionShape represents a union shape.

func (*UnionShape) Base

func (s *UnionShape) Base() *BaseShape

Base returns the base shape.

func (UnionShape) IsScalar added in v0.13.1

func (UnionShape) IsScalar() bool

type UnknownShape

type UnknownShape struct {
	*BaseShape
	// contains filtered or unexported fields
}

func (*UnknownShape) Base

func (s *UnknownShape) Base() *BaseShape

func (UnknownShape) IsScalar added in v0.13.1

func (UnknownShape) IsScalar() bool

type Value

type Value[T any] struct {
	Value T
	stacktrace.Position
}

Directories

Path Synopsis
cmd
raml Module

Jump to

Keyboard shortcuts

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