github.com/go-swagger/go-swagger@v0.31.0/generator/structs.go (about)

     1  package generator
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"fmt"
     7  	"sort"
     8  	"strconv"
     9  	"strings"
    10  
    11  	"github.com/go-openapi/analysis"
    12  	"github.com/go-openapi/spec"
    13  )
    14  
    15  // GenCommon contains common properties needed across
    16  // definitions, app and operations
    17  // TargetImportPath may be used by templates to import other (possibly
    18  // generated) packages in the generation path (e.g. relative to GOPATH).
    19  // TargetImportPath is NOT used by standard templates.
    20  type GenCommon struct {
    21  	Copyright        string
    22  	TargetImportPath string
    23  	RootedErrorPath  bool // wants array and map types to have a path corresponding to their type in reported errors
    24  }
    25  
    26  // GenDefinition contains all the properties to generate a
    27  // definition from a swagger spec
    28  type GenDefinition struct {
    29  	GenCommon
    30  	GenSchema
    31  	Package        string
    32  	Imports        map[string]string
    33  	DefaultImports map[string]string
    34  	ExtraSchemas   GenSchemaList
    35  	DependsOn      []string
    36  	External       bool
    37  }
    38  
    39  // GenDefinitions represents a list of operations to generate
    40  // this implements a sort by operation id
    41  type GenDefinitions []GenDefinition
    42  
    43  func (g GenDefinitions) Len() int           { return len(g) }
    44  func (g GenDefinitions) Less(i, j int) bool { return g[i].Name < g[j].Name }
    45  func (g GenDefinitions) Swap(i, j int)      { g[i], g[j] = g[j], g[i] }
    46  
    47  // GenSchemaList is a list of schemas for generation.
    48  //
    49  // It can be sorted by name to get a stable struct layout for
    50  // version control and such
    51  type GenSchemaList []GenSchema
    52  
    53  // GenSchema contains all the information needed to generate the code
    54  // for a schema
    55  type GenSchema struct {
    56  	resolvedType
    57  	sharedValidations
    58  	Example                    string
    59  	OriginalName               string
    60  	Name                       string
    61  	Suffix                     string
    62  	Path                       string
    63  	ValueExpression            string
    64  	IndexVar                   string
    65  	KeyVar                     string
    66  	Title                      string
    67  	Description                string
    68  	Location                   string
    69  	ReceiverName               string
    70  	Items                      *GenSchema
    71  	AllowsAdditionalItems      bool
    72  	HasAdditionalItems         bool
    73  	AdditionalItems            *GenSchema
    74  	Object                     *GenSchema
    75  	XMLName                    string
    76  	CustomTag                  string
    77  	Properties                 GenSchemaList
    78  	AllOf                      GenSchemaList
    79  	HasAdditionalProperties    bool
    80  	IsAdditionalProperties     bool
    81  	AdditionalProperties       *GenSchema
    82  	StrictAdditionalProperties bool
    83  	ReadOnly                   bool
    84  	IsVirtual                  bool
    85  	IsBaseType                 bool
    86  	HasBaseType                bool
    87  	IsSubType                  bool
    88  	IsExported                 bool
    89  	IsElem                     bool // IsElem gives some context when the schema is part of an array or a map
    90  	IsProperty                 bool // IsProperty gives some context when the schema is a property of an object
    91  	DiscriminatorField         string
    92  	DiscriminatorValue         string
    93  	Discriminates              map[string]string
    94  	Parents                    []string
    95  	IncludeValidator           bool
    96  	IncludeModel               bool
    97  	Default                    interface{}
    98  	WantsMarshalBinary         bool // do we generate MarshalBinary interface?
    99  	StructTags                 []string
   100  	ExtraImports               map[string]string // non-standard imports detected when using external types
   101  	ExternalDocs               *spec.ExternalDocumentation
   102  	WantsRootedErrorPath       bool
   103  }
   104  
   105  func (g GenSchema) renderMarshalTag() string {
   106  	if g.HasBaseType {
   107  		return "-"
   108  	}
   109  
   110  	var result strings.Builder
   111  
   112  	result.WriteString(g.OriginalName)
   113  
   114  	if !g.Required && g.IsEmptyOmitted {
   115  		result.WriteString(",omitempty")
   116  	}
   117  
   118  	if g.IsJSONString {
   119  		result.WriteString(",string")
   120  	}
   121  
   122  	return result.String()
   123  }
   124  
   125  // PrintTags takes care of rendering tags for a struct field
   126  func (g GenSchema) PrintTags() string {
   127  	tags := make(map[string]string, 3)
   128  	orderedTags := make([]string, 0, 3)
   129  
   130  	tags["json"] = g.renderMarshalTag()
   131  	orderedTags = append(orderedTags, "json")
   132  
   133  	if len(g.XMLName) > 0 {
   134  		if !g.Required && g.IsEmptyOmitted {
   135  			tags["xml"] = g.XMLName + ",omitempty"
   136  		} else {
   137  			tags["xml"] = g.XMLName
   138  		}
   139  		orderedTags = append(orderedTags, "xml")
   140  	}
   141  
   142  	// Add extra struct tags, only if the tag hasn't already been set, i.e. example.
   143  	// Extra struct tags have the same value has the `json` tag.
   144  	for _, tag := range g.StructTags {
   145  		if _, exists := tags[tag]; exists {
   146  			// dedupe
   147  			continue
   148  		}
   149  
   150  		switch {
   151  		case tag == "example" && len(g.Example) > 0:
   152  			// only add example tag if it's contained in the struct tags
   153  			tags["example"] = g.Example // json representation of the example object
   154  		case tag == "description" && len(g.Description) > 0:
   155  			tags["description"] = g.Description
   156  		default:
   157  			tags[tag] = tags["json"]
   158  		}
   159  
   160  		orderedTags = append(orderedTags, tag)
   161  	}
   162  
   163  	// Assemble the tags in key value pairs with the value properly quoted.
   164  	kvPairs := make([]string, 0, len(orderedTags)+1)
   165  	for _, key := range orderedTags {
   166  		kvPairs = append(kvPairs, fmt.Sprintf("%s:%s", key, strconv.Quote(tags[key])))
   167  	}
   168  
   169  	if len(g.CustomTag) > 0 {
   170  		kvPairs = append(kvPairs, g.CustomTag)
   171  	}
   172  
   173  	// Join the key value pairs by a space.
   174  	completeTag := strings.Join(kvPairs, " ")
   175  
   176  	// If the values contain a backtick, we cannot render the tag using backticks because Go does not support
   177  	// escaping backticks in raw string literals.
   178  	valuesHaveBacktick := false
   179  	for _, value := range tags {
   180  		if !strconv.CanBackquote(value) {
   181  			valuesHaveBacktick = true
   182  			break
   183  		}
   184  	}
   185  
   186  	if !valuesHaveBacktick {
   187  		return fmt.Sprintf("`%s`", completeTag)
   188  	}
   189  
   190  	// We have to escape the tag again to put it in a literal with double quotes as the tag format uses double quotes.
   191  	return strconv.Quote(completeTag)
   192  }
   193  
   194  // UnderlyingType tells the go type or the aliased go type
   195  func (g GenSchema) UnderlyingType() string {
   196  	if g.IsAliased {
   197  		return g.AliasedType
   198  	}
   199  	return g.GoType
   200  }
   201  
   202  // ToString returns a string conversion expression for the schema
   203  func (g GenSchema) ToString() string {
   204  	return g.resolvedType.ToString(g.ValueExpression)
   205  }
   206  
   207  func (g GenSchemaList) Len() int      { return len(g) }
   208  func (g GenSchemaList) Swap(i, j int) { g[i], g[j] = g[j], g[i] }
   209  func (g GenSchemaList) Less(i, j int) bool {
   210  	a, okA := g[i].Extensions[xOrder].(float64)
   211  	b, okB := g[j].Extensions[xOrder].(float64)
   212  
   213  	// If both properties have x-order defined, then the one with lower x-order is smaller
   214  	if okA && okB {
   215  		return a < b
   216  	}
   217  
   218  	// If only the first property has x-order defined, then it is smaller
   219  	if okA {
   220  		return true
   221  	}
   222  
   223  	// If only the second property has x-order defined, then it is smaller
   224  	if okB {
   225  		return false
   226  	}
   227  
   228  	// If neither property has x-order defined, then the one with lower lexicographic name is smaller
   229  	return g[i].Name < g[j].Name
   230  }
   231  
   232  type sharedValidations struct {
   233  	spec.SchemaValidations
   234  
   235  	HasValidations        bool
   236  	HasContextValidations bool
   237  	Required              bool
   238  	HasSliceValidations   bool
   239  	ItemsEnum             []interface{}
   240  
   241  	// NOTE: "patternProperties" and "dependencies" not supported by Swagger 2.0
   242  }
   243  
   244  // GenResponse represents a response object for code generation
   245  type GenResponse struct {
   246  	Package       string
   247  	ModelsPackage string
   248  	ReceiverName  string
   249  	Name          string
   250  	Description   string
   251  
   252  	IsSuccess bool
   253  
   254  	Code               int
   255  	Method             string
   256  	Path               string
   257  	Headers            GenHeaders
   258  	Schema             *GenSchema
   259  	AllowsForStreaming bool
   260  
   261  	Imports        map[string]string
   262  	DefaultImports map[string]string
   263  
   264  	Extensions map[string]interface{}
   265  
   266  	StrictResponders bool
   267  	OperationName    string
   268  	Examples         GenResponseExamples
   269  }
   270  
   271  // GenResponseExamples is a sortable collection []GenResponseExample
   272  type GenResponseExamples []GenResponseExample
   273  
   274  func (g GenResponseExamples) Len() int           { return len(g) }
   275  func (g GenResponseExamples) Swap(i, j int)      { g[i], g[j] = g[j], g[i] }
   276  func (g GenResponseExamples) Less(i, j int) bool { return g[i].MediaType < g[j].MediaType }
   277  
   278  // GenResponseExample captures an example provided for a response for some mime type
   279  type GenResponseExample struct {
   280  	MediaType string
   281  	Example   interface{}
   282  }
   283  
   284  // GenHeader represents a header on a response for code generation
   285  type GenHeader struct {
   286  	resolvedType
   287  	sharedValidations
   288  
   289  	Package      string
   290  	ReceiverName string
   291  	IndexVar     string
   292  
   293  	ID              string
   294  	Name            string
   295  	Path            string
   296  	ValueExpression string
   297  
   298  	Title       string
   299  	Description string
   300  	Default     interface{}
   301  	HasDefault  bool
   302  
   303  	CollectionFormat string
   304  
   305  	Child  *GenItems
   306  	Parent *GenItems
   307  
   308  	Converter string
   309  	Formatter string
   310  
   311  	ZeroValue string
   312  }
   313  
   314  // ItemsDepth returns a string "items.items..." with as many items as the level of nesting of the array.
   315  // For a header objects it always returns "".
   316  func (h *GenHeader) ItemsDepth() string {
   317  	// NOTE: this is currently used by templates to generate explicit comments in nested structures
   318  	return ""
   319  }
   320  
   321  // ToString returns a string conversion expression for the header
   322  func (h GenHeader) ToString() string {
   323  	return h.resolvedType.ToString(h.ValueExpression)
   324  }
   325  
   326  // GenHeaders is a sorted collection of headers for codegen
   327  type GenHeaders []GenHeader
   328  
   329  func (g GenHeaders) Len() int           { return len(g) }
   330  func (g GenHeaders) Swap(i, j int)      { g[i], g[j] = g[j], g[i] }
   331  func (g GenHeaders) Less(i, j int) bool { return g[i].Name < g[j].Name }
   332  
   333  // HasSomeDefaults returns true is at least one header has a default value set
   334  func (g GenHeaders) HasSomeDefaults() bool {
   335  	// NOTE: this is currently used by templates to avoid empty constructs
   336  	for _, header := range g {
   337  		if header.HasDefault {
   338  			return true
   339  		}
   340  	}
   341  	return false
   342  }
   343  
   344  // GenParameter is used to represent
   345  // a parameter or a header for code generation.
   346  type GenParameter struct {
   347  	resolvedType
   348  	sharedValidations
   349  
   350  	ID              string
   351  	Name            string
   352  	ModelsPackage   string
   353  	Path            string
   354  	ValueExpression string
   355  	IndexVar        string
   356  	KeyVar          string
   357  	ReceiverName    string
   358  	Location        string
   359  	Title           string
   360  	Description     string
   361  	Converter       string
   362  	Formatter       string
   363  
   364  	Schema *GenSchema
   365  
   366  	CollectionFormat string
   367  
   368  	CustomTag string
   369  
   370  	Child  *GenItems
   371  	Parent *GenItems
   372  
   373  	// Unused
   374  	// BodyParam *GenParameter
   375  
   376  	Default         interface{}
   377  	HasDefault      bool
   378  	ZeroValue       string
   379  	AllowEmptyValue bool
   380  
   381  	// validation strategy for Body params, which may mix model and simple constructs.
   382  	// Distinguish the following cases:
   383  	// - HasSimpleBodyParams: body is an inline simple type
   384  	// - HasModelBodyParams: body is a model objectd
   385  	// - HasSimpleBodyItems: body is an inline array of simple type
   386  	// - HasModelBodyItems: body is an array of model objects
   387  	// - HasSimpleBodyMap: body is a map of simple objects (possibly arrays)
   388  	// - HasModelBodyMap: body is a map of model objects
   389  	HasSimpleBodyParams bool
   390  	HasModelBodyParams  bool
   391  	HasSimpleBodyItems  bool
   392  	HasModelBodyItems   bool
   393  	HasSimpleBodyMap    bool
   394  	HasModelBodyMap     bool
   395  
   396  	Extensions map[string]interface{}
   397  }
   398  
   399  // IsQueryParam returns true when this parameter is a query param
   400  func (g *GenParameter) IsQueryParam() bool {
   401  	return g.Location == "query"
   402  }
   403  
   404  // IsPathParam returns true when this parameter is a path param
   405  func (g *GenParameter) IsPathParam() bool {
   406  	return g.Location == "path"
   407  }
   408  
   409  // IsFormParam returns true when this parameter is a form param
   410  func (g *GenParameter) IsFormParam() bool {
   411  	return g.Location == "formData"
   412  }
   413  
   414  // IsHeaderParam returns true when this parameter is a header param
   415  func (g *GenParameter) IsHeaderParam() bool {
   416  	return g.Location == "header"
   417  }
   418  
   419  // IsBodyParam returns true when this parameter is a body param
   420  func (g *GenParameter) IsBodyParam() bool {
   421  	return g.Location == "body"
   422  }
   423  
   424  // IsFileParam returns true when this parameter is a file param
   425  func (g *GenParameter) IsFileParam() bool {
   426  	return g.SwaggerType == "file"
   427  }
   428  
   429  // ItemsDepth returns a string "items.items..." with as many items as the level of nesting of the array.
   430  // For a parameter object, it always returns "".
   431  func (g *GenParameter) ItemsDepth() string {
   432  	// NOTE: this is currently used by templates to generate explicit comments in nested structures
   433  	return ""
   434  }
   435  
   436  // UnderlyingType tells the go type or the aliased go type
   437  func (g GenParameter) UnderlyingType() string {
   438  	return g.GoType
   439  }
   440  
   441  // ToString returns a string conversion expression for the parameter
   442  func (g GenParameter) ToString() string {
   443  	return g.resolvedType.ToString(g.ValueExpression)
   444  }
   445  
   446  // GenParameters represents a sorted parameter collection
   447  type GenParameters []GenParameter
   448  
   449  func (g GenParameters) Len() int           { return len(g) }
   450  func (g GenParameters) Less(i, j int) bool { return g[i].Name < g[j].Name }
   451  func (g GenParameters) Swap(i, j int)      { g[i], g[j] = g[j], g[i] }
   452  
   453  // HasSomeDefaults returns true is at least one parameter has a default value set
   454  func (g GenParameters) HasSomeDefaults() bool {
   455  	// NOTE: this is currently used by templates to avoid empty constructs
   456  	for _, param := range g {
   457  		if param.HasDefault {
   458  			return true
   459  		}
   460  	}
   461  	return false
   462  }
   463  
   464  // GenItems represents the collection items for a collection parameter
   465  type GenItems struct {
   466  	sharedValidations
   467  	resolvedType
   468  
   469  	Name             string
   470  	Path             string
   471  	ValueExpression  string
   472  	CollectionFormat string
   473  	Child            *GenItems
   474  	Parent           *GenItems
   475  	Converter        string
   476  	Formatter        string
   477  
   478  	Location string
   479  	IndexVar string
   480  	KeyVar   string
   481  
   482  	// instructs generator to skip the splitting and parsing from CollectionFormat
   483  	SkipParse bool
   484  	// instructs generator that some nested structure needs an higher level loop index
   485  	NeedsIndex bool
   486  }
   487  
   488  // ItemsDepth returns a string "items.items..." with as many items as the level of nesting of the array.
   489  func (g *GenItems) ItemsDepth() string {
   490  	// NOTE: this is currently used by templates to generate explicit comments in nested structures
   491  	current := g
   492  	i := 1
   493  	for current.Parent != nil {
   494  		i++
   495  		current = current.Parent
   496  	}
   497  	return strings.Repeat("items.", i)
   498  }
   499  
   500  // UnderlyingType tells the go type or the aliased go type
   501  func (g GenItems) UnderlyingType() string {
   502  	return g.GoType
   503  }
   504  
   505  // ToString returns a string conversion expression for the item
   506  func (g GenItems) ToString() string {
   507  	return g.resolvedType.ToString(g.ValueExpression)
   508  }
   509  
   510  // GenOperationGroup represents a named (tagged) group of operations
   511  type GenOperationGroup struct {
   512  	GenCommon
   513  	Name       string
   514  	Operations GenOperations
   515  
   516  	Summary        string
   517  	Description    string
   518  	Imports        map[string]string
   519  	DefaultImports map[string]string
   520  	RootPackage    string
   521  	GenOpts        *GenOpts
   522  	PackageAlias   string
   523  
   524  	ClientOptions *GenClientOptions
   525  }
   526  
   527  // GenOperationGroups is a sorted collection of operation groups
   528  type GenOperationGroups []GenOperationGroup
   529  
   530  func (g GenOperationGroups) Len() int           { return len(g) }
   531  func (g GenOperationGroups) Swap(i, j int)      { g[i], g[j] = g[j], g[i] }
   532  func (g GenOperationGroups) Less(i, j int) bool { return g[i].Name < g[j].Name }
   533  
   534  // GenStatusCodeResponses a container for status code responses
   535  type GenStatusCodeResponses []GenResponse
   536  
   537  func (g GenStatusCodeResponses) Len() int           { return len(g) }
   538  func (g GenStatusCodeResponses) Swap(i, j int)      { g[i], g[j] = g[j], g[i] }
   539  func (g GenStatusCodeResponses) Less(i, j int) bool { return g[i].Code < g[j].Code }
   540  
   541  // MarshalJSON marshals these responses to json
   542  //
   543  // This is used by DumpData.
   544  func (g GenStatusCodeResponses) MarshalJSON() ([]byte, error) {
   545  	if g == nil {
   546  		return nil, nil
   547  	}
   548  	responses := make(GenStatusCodeResponses, len(g))
   549  	copy(responses, g)
   550  	// order marshalled output
   551  	sort.Sort(responses)
   552  
   553  	var buf bytes.Buffer
   554  	buf.WriteRune('{')
   555  	for i, v := range responses {
   556  		rb, err := json.Marshal(v)
   557  		if err != nil {
   558  			return nil, err
   559  		}
   560  		if i > 0 {
   561  			buf.WriteRune(',')
   562  		}
   563  		buf.WriteString(fmt.Sprintf("%q:", strconv.Itoa(v.Code)))
   564  		buf.Write(rb)
   565  	}
   566  	buf.WriteRune('}')
   567  	return buf.Bytes(), nil
   568  }
   569  
   570  // UnmarshalJSON unmarshals this GenStatusCodeResponses from json
   571  func (g *GenStatusCodeResponses) UnmarshalJSON(data []byte) error {
   572  	var dd map[string]GenResponse
   573  	if err := json.Unmarshal(data, &dd); err != nil {
   574  		return err
   575  	}
   576  	var gg GenStatusCodeResponses
   577  	for _, v := range dd {
   578  		gg = append(gg, v)
   579  	}
   580  	sort.Sort(gg)
   581  	*g = gg
   582  	return nil
   583  }
   584  
   585  // GenOperation represents an operation for code generation
   586  type GenOperation struct {
   587  	GenCommon
   588  	Package      string
   589  	ReceiverName string
   590  	Name         string
   591  	Summary      string
   592  	Description  string
   593  	Method       string
   594  	Path         string
   595  	BasePath     string
   596  	Tags         []string
   597  	UseTags      bool
   598  	RootPackage  string
   599  
   600  	Imports        map[string]string
   601  	DefaultImports map[string]string
   602  	ExtraSchemas   GenSchemaList
   603  	PackageAlias   string
   604  
   605  	Authorized           bool
   606  	Security             []GenSecurityRequirements // resolved security requirements for the operation
   607  	SecurityDefinitions  GenSecuritySchemes
   608  	SecurityRequirements []analysis.SecurityRequirement // original security requirements as per the spec (for doc)
   609  	Principal            string
   610  	PrincipalIsNullable  bool
   611  
   612  	SuccessResponse  *GenResponse
   613  	SuccessResponses []GenResponse
   614  	Responses        GenStatusCodeResponses
   615  	DefaultResponse  *GenResponse
   616  
   617  	Params               GenParameters
   618  	QueryParams          GenParameters
   619  	PathParams           GenParameters
   620  	HeaderParams         GenParameters
   621  	FormParams           GenParameters
   622  	HasQueryParams       bool
   623  	HasPathParams        bool
   624  	HasHeaderParams      bool
   625  	HasFormParams        bool
   626  	HasFormValueParams   bool
   627  	HasFileParams        bool
   628  	HasBodyParams        bool
   629  	HasStreamingResponse bool
   630  
   631  	Schemes              []string
   632  	ExtraSchemes         []string
   633  	SchemeOverrides      []string // original scheme overrides for operation, as per spec (for doc)
   634  	ExtraSchemeOverrides []string // original extra scheme overrides for operation, as per spec (for doc)
   635  	ProducesMediaTypes   []string
   636  	ConsumesMediaTypes   []string
   637  	TimeoutName          string
   638  
   639  	Extensions map[string]interface{}
   640  
   641  	StrictResponders bool
   642  	ExternalDocs     *spec.ExternalDocumentation
   643  	Produces         []string // original produces for operation (for doc)
   644  	Consumes         []string // original consumes for operation (for doc)
   645  }
   646  
   647  // GenOperations represents a list of operations to generate
   648  // this implements a sort by operation id
   649  type GenOperations []GenOperation
   650  
   651  func (g GenOperations) Len() int           { return len(g) }
   652  func (g GenOperations) Less(i, j int) bool { return g[i].Name < g[j].Name }
   653  func (g GenOperations) Swap(i, j int)      { g[i], g[j] = g[j], g[i] }
   654  
   655  // GenApp represents all the meta data needed to generate an application
   656  // from a swagger spec
   657  type GenApp struct {
   658  	GenCommon
   659  	APIPackage                 string
   660  	ServerPackageAlias         string
   661  	ImplementationPackageAlias string
   662  	APIPackageAlias            string
   663  	Package                    string
   664  	ReceiverName               string
   665  	Name                       string
   666  	Principal                  string
   667  	PrincipalIsNullable        bool
   668  	DefaultConsumes            string
   669  	DefaultProduces            string
   670  	Host                       string
   671  	BasePath                   string
   672  	Info                       *spec.Info
   673  	ExternalDocs               *spec.ExternalDocumentation
   674  	Tags                       []spec.Tag
   675  	Imports                    map[string]string
   676  	DefaultImports             map[string]string
   677  	Schemes                    []string
   678  	ExtraSchemes               []string
   679  	Consumes                   GenSerGroups
   680  	Produces                   GenSerGroups
   681  	SecurityDefinitions        GenSecuritySchemes
   682  	SecurityRequirements       []analysis.SecurityRequirement // original security requirements as per the spec (for doc)
   683  	Models                     []GenDefinition
   684  	Operations                 GenOperations
   685  	OperationGroups            GenOperationGroups
   686  	SwaggerJSON                string
   687  	// Embedded specs: this is important for when the generated server adds routes.
   688  	// NOTE: there is a distinct advantage to having this in runtime rather than generated code.
   689  	// We are not ever going to generate the router.
   690  	// If embedding spec is an issue (e.g. memory usage), this can be excluded with the --exclude-spec
   691  	// generation option. Alternative methods to serve spec (e.g. from disk, ...) may be implemented by
   692  	// adding a middleware to the generated API.
   693  	FlatSwaggerJSON string
   694  	ExcludeSpec     bool
   695  	GenOpts         *GenOpts
   696  }
   697  
   698  // UseGoStructFlags returns true when no strategy is specified or it is set to "go-flags"
   699  func (g *GenApp) UseGoStructFlags() bool {
   700  	if g.GenOpts == nil {
   701  		return true
   702  	}
   703  	return g.GenOpts.FlagStrategy == "" || g.GenOpts.FlagStrategy == "go-flags"
   704  }
   705  
   706  // UsePFlags returns true when the flag strategy is set to pflag
   707  func (g *GenApp) UsePFlags() bool {
   708  	return g.GenOpts != nil && strings.HasPrefix(g.GenOpts.FlagStrategy, "pflag")
   709  }
   710  
   711  // UseFlags returns true when the flag strategy is set to flag
   712  func (g *GenApp) UseFlags() bool {
   713  	return g.GenOpts != nil && strings.HasPrefix(g.GenOpts.FlagStrategy, "flag")
   714  }
   715  
   716  // UseIntermediateMode for https://wiki.mozilla.org/Security/Server_Side_TLS#Intermediate_compatibility_.28default.29
   717  func (g *GenApp) UseIntermediateMode() bool {
   718  	return g.GenOpts != nil && g.GenOpts.CompatibilityMode == "intermediate"
   719  }
   720  
   721  // UseModernMode for https://wiki.mozilla.org/Security/Server_Side_TLS#Modern_compatibility
   722  func (g *GenApp) UseModernMode() bool {
   723  	return g.GenOpts == nil || g.GenOpts.CompatibilityMode == "" || g.GenOpts.CompatibilityMode == "modern"
   724  }
   725  
   726  // GenSerGroups sorted representation of serializer groups
   727  type GenSerGroups []GenSerGroup
   728  
   729  func (g GenSerGroups) Len() int           { return len(g) }
   730  func (g GenSerGroups) Swap(i, j int)      { g[i], g[j] = g[j], g[i] }
   731  func (g GenSerGroups) Less(i, j int) bool { return g[i].Name < g[j].Name }
   732  
   733  // GenSerGroup represents a group of serializers: this links a serializer to a list of
   734  // prioritized media types (mime).
   735  type GenSerGroup struct {
   736  	GenSerializer
   737  
   738  	// All media types for this serializer. The redundant representation allows for easier use in templates
   739  	AllSerializers GenSerializers
   740  }
   741  
   742  // GenSerializers sorted representation of serializers
   743  type GenSerializers []GenSerializer
   744  
   745  func (g GenSerializers) Len() int           { return len(g) }
   746  func (g GenSerializers) Swap(i, j int)      { g[i], g[j] = g[j], g[i] }
   747  func (g GenSerializers) Less(i, j int) bool { return g[i].MediaType < g[j].MediaType }
   748  
   749  // GenSerializer represents a single serializer for a particular media type
   750  type GenSerializer struct {
   751  	AppName        string // Application name
   752  	ReceiverName   string
   753  	Name           string   // Name of the Producer/Consumer (e.g. json, yaml, txt, bin)
   754  	MediaType      string   // mime
   755  	Implementation string   // func implementing the Producer/Consumer
   756  	Parameters     []string // parameters supported by this serializer
   757  }
   758  
   759  // GenSecurityScheme represents a security scheme for code generation
   760  type GenSecurityScheme struct {
   761  	AppName             string
   762  	ID                  string
   763  	Name                string
   764  	ReceiverName        string
   765  	IsBasicAuth         bool
   766  	IsAPIKeyAuth        bool
   767  	IsOAuth2            bool
   768  	Scopes              []string
   769  	Source              string
   770  	Principal           string
   771  	PrincipalIsNullable bool
   772  
   773  	// from spec.SecurityScheme
   774  	Description      string
   775  	Type             string
   776  	In               string
   777  	Flow             string
   778  	AuthorizationURL string
   779  	TokenURL         string
   780  	Extensions       map[string]interface{}
   781  	ScopesDesc       []GenSecurityScope
   782  }
   783  
   784  // GenSecuritySchemes sorted representation of serializers
   785  type GenSecuritySchemes []GenSecurityScheme
   786  
   787  func (g GenSecuritySchemes) Len() int           { return len(g) }
   788  func (g GenSecuritySchemes) Swap(i, j int)      { g[i], g[j] = g[j], g[i] }
   789  func (g GenSecuritySchemes) Less(i, j int) bool { return g[i].ID < g[j].ID }
   790  
   791  // GenSecurityRequirement represents a security requirement for an operation
   792  type GenSecurityRequirement struct {
   793  	Name   string
   794  	Scopes []string
   795  }
   796  
   797  // GenSecurityScope represents a scope descriptor for an OAuth2 security scheme
   798  type GenSecurityScope struct {
   799  	Name        string
   800  	Description string
   801  }
   802  
   803  // GenSecurityRequirements represents a compounded security requirement specification.
   804  // In a []GenSecurityRequirements complete requirements specification,
   805  // outer elements are interpreted as optional requirements (OR), and
   806  // inner elements are interpreted as jointly required (AND).
   807  type GenSecurityRequirements []GenSecurityRequirement
   808  
   809  func (g GenSecurityRequirements) Len() int           { return len(g) }
   810  func (g GenSecurityRequirements) Swap(i, j int)      { g[i], g[j] = g[j], g[i] }
   811  func (g GenSecurityRequirements) Less(i, j int) bool { return g[i].Name < g[j].Name }
   812  
   813  // GenClientOptions holds extra pieces of information
   814  // to generate a client.
   815  type GenClientOptions struct {
   816  	ProducesMediaTypes []string // filled with all producers if any method as more than 1
   817  	ConsumesMediaTypes []string // filled with all consumers if any method as more than 1
   818  }