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