proto

package
v0.0.0-...-fbd6392 Latest Latest
Warning

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

Go to latest
Published: Apr 18, 2024 License: Apache-2.0 Imports: 12 Imported by: 1

Documentation

Overview

Package proto houses all logic for processing protocol buffers into an easy-to-use structure for creating diagrams outputFlag. The intention is to support a verity of diagram types such as Mermaid and Plant UML. Since Go does not support logical libraries, these are loaded via direction implementations. ToMermaid() and ToPlantUML(). Please note, since this is a Go implementation, the Plant UML diagrams are syntax only, and the Java diagram compiler is not currently used.

Index

Constants

View Source
const (
	Protobuf3Types = "double,float,int32,int64,uint32,uint64,sint32,sint64,fixed32,fixed64,sfixed32,sfixed64,bool,string,bytes"

	PrefixRepeated = "repeated"
	PrefixMap      = "map"
	PrefixReserved = "reserved"
	PrefixOptional = "optional"

	SpaceRemovalRegex = `\s+`
	Period            = "."
	Empty             = ""
	Space             = " "
	OpenBrace         = "{"
	CloseBrace        = "}"
	OpenBracket       = "["
	ClosedBracket     = "]"
	Semicolon         = ";"
	Comma             = ","
	Pipe              = "|"
	Hyphen            = "-"

	InlineCommentPrefix        = "//"
	MultiLineCommentInitiator  = "/*"
	MultilineCommentTerminator = "*/"
	OpenMap                    = "map<"
	CloseMap                   = ">"
	DoubleQuote                = `"`
	SingleQuote                = `'`
	EndL                       = "\n"
	CommentNewLine             = `:~:`
)

Constants used for parsing and interpretation

View Source
const (
	InfoColor  = "\033[1;32mINFO: %s\033[0m"
	ErrorColor = "\033[1;31mERROR: %s\033[0m"
	DebugColor = "\033[1;36mDEBUG: %s\033[0m"
)

From gist: https://gist.github.com/ik5/d8ecde700972d4378d87

View Source
const (
	MarkdownPadding = 2
)
View Source
const (
	ProtobufSuffix = ".proto"
)

Variables

View Source
var InvalidImport = errors.New("invalid import")

InvalidImport = used during import sequence of files.

View Source
var Log = &Logger{}

Log is the Package Logger

View Source
var RegisteredVisitors []Visitor
View Source
var RpcLinePattern = `rpc\s+(.*?)\((.*?)\)\s+returns\s+\((.*?)\)(.*)`
View Source
var SpaceRemover *regexp.Regexp

Functions

func ComputeFormat

func ComputeFormat(length int, value string) string

func DashLine

func DashLine(length int) string

func EnumToMarkdown

func EnumToMarkdown(enum *Enum, wc *WriterConfig) (body string, diagram string)

func EnumToMermaid

func EnumToMermaid(e *Enum) string

EnumToMermaid formats an Enum into mermaid text.

func Execute

func Execute()

func FormatLine

func FormatLine(in string) string

func FormatParametersForMermaid

func FormatParametersForMermaid(in []*Parameter) string

FormatParametersForMermaid formats parameters for services

func FormatRelationships

func FormatRelationships(name string, in []*Parameter) string

FormatRelationships formats a service relationship

func FormatServiceParameter

func FormatServiceParameter(parameters []*Parameter) string

func HandleDefaultAttribute

func HandleDefaultAttribute(out *Attribute, split []string)

HandleDefaultAttribute marshals a standard attribute type.

func HandleEnums

func HandleEnums(enums []*Enum, wc *WriterConfig) (body string)

func HandleMap

func HandleMap(out *Attribute, split []string)

handleMap marshals the attribute into a Map type by using multiple types for key and value.

func HandleMessages

func HandleMessages(messages []*Message, wc *WriterConfig) (body string)

func HandleOptional

func HandleOptional(out *Attribute, split []string)

HandleOptional marshals the attribute into an optional representation

func HandleRepeated

func HandleRepeated(out *Attribute, split []string)

HandleRepeated marshals the attribute into a repeated representation, e.g. List.

func Join

func Join(joinCharacter string, values ...string) string

func MessageToMarkdown

func MessageToMarkdown(message *Message, wc *WriterConfig) (body string, diagram string)

func MessageToMermaid

func MessageToMermaid(m *Message) string

MessageToMermaid formats a Message into mermaid text

func NormalizeName

func NormalizeName(in string) string

func PackageFormatImports

func PackageFormatImports(p *Package) (body string)

func PackageFormatOptions

func PackageFormatOptions(p *Package) (body string)

func PackageToMarkDown

func PackageToMarkDown(p *Package, wc *WriterConfig) string

func PackageToMermaid

func PackageToMermaid(p *Package) string

PackageToMermaid formats a Package into Mermaid syntax

func ParseInArgs

func ParseInArgs(values []string, rpc *Rpc)

func ParseOrdinal

func ParseOrdinal(in string) int

func ParseReturnArgs

func ParseReturnArgs(values []string, rpc *Rpc)

func ReadFileToArray

func ReadFileToArray(file *os.File) []string

func RemoveDoubleQuotes

func RemoveDoubleQuotes(in string) string

func RemoveNameQualification

func RemoveNameQualification(in string) string

RemoveNameQualification formats a parameter into a single name, this is due to a limitation in Mermaid that DOES NOT support fully qualified names.

func RemoveSemicolon

func RemoveSemicolon(in string) string

func ServiceToMarkdown

func ServiceToMarkdown(s *Service, wc *WriterConfig) string

func ServiceToMermaid

func ServiceToMermaid(s *Service) string

Formats a Service into mermaid text

func SetDebug

func SetDebug(debug bool)

SetDebug is used to enable the debugFlag outputFlag, useful for troubleshooting.

func ToMermaid

func ToMermaid(title string, rt interface{}) string

Types

type Annotation

type Annotation struct {
	Name  string
	Value any
}

Annotation is an inline structure applicable only to attributes

func NewAnnotation

func NewAnnotation(name string, value any) *Annotation

NewAnnotation is the Annotation Constructor

func ParseAnnotations

func ParseAnnotations(in string) []*Annotation

ParseAnnotations is used for reading the annotation line and marshalling it into the annotation structure.

type Attribute

type Attribute struct {
	*Qualified
	Repeated    bool
	Optional    bool
	Map         bool
	Kind        []string
	Ordinal     int
	Annotations []*Annotation
}

An Attribute is a component in the message structure.

func NewAttribute

func NewAttribute(namespace string, comment Comment) *Attribute

NewAttribute is the Attribute constructor

func (*Attribute) IsValid

func (a *Attribute) IsValid() bool

IsValid implements the Validatable interface

func (*Attribute) ToMermaid

func (a *Attribute) ToMermaid() string

ToMermaid implements a Mermaid Syntax per Attribute

type AttributeVisitor

type AttributeVisitor struct {
}

Visitor implementation for attributes

func NewAttributeVisitor

func NewAttributeVisitor() *AttributeVisitor

NewAttributeVisitor - Constructor for the AttributeVisitor

func (*AttributeVisitor) CanVisit

func (av *AttributeVisitor) CanVisit(in *Line) bool

CanVisit - Determines if the line is an attribute, it doesn't end in a brace, it's a map, repeated, optional, or can effectively be split

func (*AttributeVisitor) Visit

func (av *AttributeVisitor) Visit(_ Scanner, in *Line, namespace string) interface{}

Visit is used for marshalling an attribute into a struct.

type Comment

type Comment string

Comment is a string with additional methods

func (Comment) AddSpace

func (c Comment) AddSpace() Comment

AddSpace adds a space to the end of a Comment.

func (Comment) Append

func (c Comment) Append(other Comment) Comment

Append adds a comment to the end of an existing comment.

func (Comment) Clear

func (c Comment) Clear() Comment

Clear truncates the comment

func (Comment) ToMarkdownBlockQuote

func (c Comment) ToMarkdownBlockQuote() string

func (Comment) ToMarkdownText

func (c Comment) ToMarkdownText(linebreak bool) string

func (Comment) ToMermaid

func (c Comment) ToMermaid() string

func (Comment) TrimSpace

func (c Comment) TrimSpace() Comment

TrimSpace removes any double space or padding spaces from the comment.

type CommentVisitor

type CommentVisitor struct {
}

CommentVisitor is responsible for reading and recoding comment lines, it DOES NOT handle inline comments because of how the

func (*CommentVisitor) CanVisit

func (cv *CommentVisitor) CanVisit(in *Line) bool

CanVisit Determines if the line is a coment

func (*CommentVisitor) Visit

func (cv *CommentVisitor) Visit(scanner Scanner, in *Line, _ string) interface{}

Visit marshals a line into a Comment struct.

type Enum

type Enum struct {
	*Qualified
	Values []*EnumValue
}

Enum represents a Proto Enum type.

func NewEnum

func NewEnum(q string, name string, comment Comment) *Enum

NewEnum is the Enum Constructor

type EnumValue

type EnumValue struct {
	Namespace string
	Ordinal   int
	Value     string
	Comment   Comment
}

EnumValue is the representation of an internal enum value.

func NewEnumValue

func NewEnumValue(namespace string, ordinal string, value string, comment Comment) *EnumValue

NewEnumValue is the EnumValue constructor

type EnumValueVisitor

type EnumValueVisitor struct {
}

EnumValueVisitor is responsible evaluating and processing Protobuf Enumerations.

func (EnumValueVisitor) CanVisit

func (evv EnumValueVisitor) CanVisit(in *Line) bool

CanVisit determines if the line is an enumeration.

func (EnumValueVisitor) Visit

func (evv EnumValueVisitor) Visit(_ Scanner, in *Line, namespace string) interface{}

Visit marshals a line into an enumeration

type EnumVisitor

type EnumVisitor struct {
	Visitors []Visitor
}

EnumVisitor is responsible for evaluation and marshalling of an Enum entity.

func NewEnumVisitor

func NewEnumVisitor() *EnumVisitor

NewEnumVisitor creates an EnumVisitor

func (*EnumVisitor) CanVisit

func (ev *EnumVisitor) CanVisit(in *Line) bool

CanVisit determines if the current line is an enumeration.

func (*EnumVisitor) Visit

func (ev *EnumVisitor) Visit(scanner Scanner, in *Line, namespace string) interface{}

Visit marshals a line and subsequent lines of the enumeration until the terminator is found.

type Import

type Import struct {
	Path    string
	Comment Comment
}

Import represents an importable file

func NewImport

func NewImport(path string) *Import

NewImport is the import constructor

type ImportVisitor

type ImportVisitor struct {
}

func (*ImportVisitor) CanVisit

func (iv *ImportVisitor) CanVisit(in *Line) bool

func (*ImportVisitor) Visit

func (iv *ImportVisitor) Visit(_ Scanner, in *Line, _ string) interface{}

type Line

type Line struct {
	Syntax  string
	Token   string
	Comment Comment
}

Line is a split line for syntax, token, and comment

func NewLine

func NewLine(in string) *Line

func (*Line) SplitSyntax

func (l *Line) SplitSyntax() []string

SplitSyntax breaks the syntax line on Space the character

type Logger

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

Logger is a simplified logger for making the code and outputFlag readable.

func (Logger) Debug

func (l Logger) Debug(in string)

Debug prints messages with a DEBUG prefix and only if debugFlag is enabled.

func (Logger) Debugf

func (l Logger) Debugf(in string, args ...any)

Debugf prints a formatted debugFlag string.

func (Logger) Error

func (l Logger) Error(in string)

Error prints a red error outputFlag

func (Logger) Errorf

func (l Logger) Errorf(in string, args ...any)

Errorf prints a formatted error

func (Logger) Info

func (l Logger) Info(in string)

Info prints an information statement to outputFlag in teal.

func (Logger) Infof

func (l Logger) Infof(in string, args ...any)

Infof prints a formatted info stream

type MarkdownTable

type MarkdownTable struct {
	Header        []string
	ColumnLengths []int
	Data          [][]string
}

func NewMarkdownTable

func NewMarkdownTable() *MarkdownTable

func (*MarkdownTable) AddHeader

func (mt *MarkdownTable) AddHeader(names ...string)

func (*MarkdownTable) EvaluateWidth

func (mt *MarkdownTable) EvaluateWidth(i int, d string)

func (*MarkdownTable) Insert

func (mt *MarkdownTable) Insert(data ...string)

func (*MarkdownTable) String

func (mt *MarkdownTable) String() string

type Message

type Message struct {
	*Qualified
	Attributes []*Attribute
	Messages   []*Message
	Enums      []*Enum
	Reserved   []*Reserved
}

Message represents a message / struct body

func NewMessage

func NewMessage() *Message

NewMessage creates a new message

func (*Message) HasAttributes

func (m *Message) HasAttributes() bool

func (*Message) HasEnums

func (m *Message) HasEnums() bool

func (*Message) HasMessages

func (m *Message) HasMessages() bool

type MessageVisitor

type MessageVisitor struct {
}

MessageVisitor is used for interpreting message text

func (*MessageVisitor) CanVisit

func (mv *MessageVisitor) CanVisit(in *Line) bool

CanVisit visits if the line starts with 'message' and ends with an open brace '{'

func (*MessageVisitor) Visit

func (mv *MessageVisitor) Visit(scanner Scanner, in *Line, namespace string) interface{}

Visit evaluates the current line and parses the message until the closed brace is evaluated.

type NamedValue

type NamedValue struct {
	Name    string
	Value   string
	Comment Comment
}

NamedValue is super class to capture names and values for typed lines.

func (*NamedValue) GetAnchor

func (namedValue *NamedValue) GetAnchor() string

type Option

type Option struct {
	*NamedValue
}

type OptionVisitor

type OptionVisitor struct {
}

func (*OptionVisitor) CanVisit

func (ov *OptionVisitor) CanVisit(in *Line) bool

func (*OptionVisitor) Visit

func (ov *OptionVisitor) Visit(_ Scanner, in *Line, _ string) interface{}

type Package

type Package struct {
	Path     string
	Name     string
	Comment  Comment
	Options  []*Option
	Imports  []*Import
	Messages []*Message
	Enums    []*Enum
	Services []*Service
}

Package is the top level structure of any protobuf

func NewPackage

func NewPackage(path string) *Package

func (*Package) Read

func (p *Package) Read(debug bool) error

func (*Package) ToMarkdownWithDiagram

func (p *Package) ToMarkdownWithDiagram() string

type PackageVisitor

type PackageVisitor struct {
}

func (*PackageVisitor) CanVisit

func (pv *PackageVisitor) CanVisit(in *Line) bool

func (*PackageVisitor) Visit

func (pv *PackageVisitor) Visit(_ Scanner, in *Line, _ string) interface{}

type Parameter

type Parameter struct {
	Stream bool
	Type   string
}

func NewParameter

func NewParameter(stream bool, t string) *Parameter

type ProtobufFileScanner

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

ProtobufFileScanner is a specialized scanner for reading protobuf 3 files.

func (ProtobufFileScanner) Buffer

func (sw ProtobufFileScanner) Buffer(buf []byte, max int)

Buffer is a delegate method to the underline scanner

func (ProtobufFileScanner) Bytes

func (sw ProtobufFileScanner) Bytes() []byte

Bytes is a delegate method to the underline scanner

func (ProtobufFileScanner) Err

func (sw ProtobufFileScanner) Err() error

Err is a delegate method to the underline scanner

func (ProtobufFileScanner) ReadLine

func (sw ProtobufFileScanner) ReadLine() *Line

ReadLine is an addition to the buffered reader responsible for interpreting the line of the protobuf for the AST.

func (ProtobufFileScanner) Scan

func (sw ProtobufFileScanner) Scan() bool

Scan is a delegate method to the underline scanner

func (ProtobufFileScanner) Split

func (sw ProtobufFileScanner) Split(splitFunction bufio.SplitFunc)

Split is a delegate method to the underline scanner

func (ProtobufFileScanner) Text

func (sw ProtobufFileScanner) Text() string

Text is a specialization of the Text function, ensuring the line read is ready for processing.

type Qualified

type Qualified struct {
	Qualifier string
	Name      string
	Comment   Comment
}

Qualified is a super class to capture namespace aware attributes and enums

type Reserved

type Reserved struct {
	Start int32
	End   int32
}

func NewReserved

func NewReserved(start int32, end int32) *Reserved

type ReservedVisitor

type ReservedVisitor struct {
}

func (*ReservedVisitor) CanVisit

func (rv *ReservedVisitor) CanVisit(line *Line) bool

func (*ReservedVisitor) Visit

func (rv *ReservedVisitor) Visit(_ Scanner, in *Line, _ string) interface{}

type Rpc

type Rpc struct {
	*Qualified
	InputParameters  []*Parameter
	ReturnParameters []*Parameter
	Options          []*RpcOption
}

func NewRpc

func NewRpc(namespace string, name string, comment Comment) *Rpc

func (*Rpc) AddInputParameter

func (rpc *Rpc) AddInputParameter(params ...*Parameter)

func (*Rpc) AddReturnParameter

func (rpc *Rpc) AddReturnParameter(params ...*Parameter)

func (*Rpc) AddRpcOption

func (rpc *Rpc) AddRpcOption(options ...*RpcOption)

type RpcOption

type RpcOption struct {
	*Qualified
	Body string
}

func NewRpcOption

func NewRpcOption(namespace string, name string, comment Comment, body string) *RpcOption

type RpcVisitor

type RpcVisitor struct {
	Visitors       []Visitor
	RpcLineMatcher *regexp.Regexp
}

func NewRpcVisitor

func NewRpcVisitor() *RpcVisitor

func (*RpcVisitor) CanVisit

func (rv *RpcVisitor) CanVisit(line *Line) bool

func (*RpcVisitor) Visit

func (rv *RpcVisitor) Visit(scanner Scanner, in *Line, namespace string) interface{}

type Scanner

type Scanner interface {
	Scan() bool
	Text() string
	Split(splitFunction bufio.SplitFunc)
	Buffer(buf []byte, max int)
	Err() error
	Bytes() []byte
	ReadLine() *Line
}

Scanner is an interface that SHOULD be a Go interface, but is only an implementation. Here, we can use the interface to wrap test cases with the same behavior of a bufio.Scanner

func NewProtobufFileScanner

func NewProtobufFileScanner(file *os.File) Scanner

NewProtobufFileScanner is the constructor for ProtobufFileScanner

type Service

type Service struct {
	*Qualified
	Methods []*Rpc
}

func NewService

func NewService(namespace string, name string, comment Comment) *Service

func (*Service) AddRpc

func (s *Service) AddRpc(rpc ...*Rpc)

type ServiceVisitor

type ServiceVisitor struct {
	Visitors []Visitor
}

func NewServiceVisitor

func NewServiceVisitor() *ServiceVisitor

func (*ServiceVisitor) CanVisit

func (sv *ServiceVisitor) CanVisit(line *Line) bool

func (*ServiceVisitor) Visit

func (sv *ServiceVisitor) Visit(scanner Scanner, in *Line, namespace string) interface{}

type TestScanner

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

func NewTestScanner

func NewTestScanner(in string) *TestScanner

func (*TestScanner) Buffer

func (ts *TestScanner) Buffer(buf []byte, max int)

func (*TestScanner) Bytes

func (ts *TestScanner) Bytes() []byte

func (*TestScanner) Err

func (ts *TestScanner) Err() error

func (*TestScanner) ReadLine

func (ts *TestScanner) ReadLine() *Line

func (*TestScanner) Scan

func (ts *TestScanner) Scan() bool

func (*TestScanner) Split

func (ts *TestScanner) Split(splitFunction bufio.SplitFunc)

func (*TestScanner) Text

func (ts *TestScanner) Text() string

type Validatable

type Validatable interface {
	IsValid() bool
}

Validatable is a reference interface for the validator pattern

type Visitor

type Visitor interface {
	CanVisit(in *Line) bool
	Visit(
		scanner Scanner,
		in *Line,
		namespace string) interface{}
}

Visitor is an interface used to determine if a line should be read, and if it should be, to read and interpret the line and subsequent lines as required.

type WriterConfig

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

Jump to

Keyboard shortcuts

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