_id stringlengths 2 7 | title stringlengths 1 118 | partition stringclasses 3 values | text stringlengths 52 85.5k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q18500 | TraceLoad | train | func (NoopTracer) TraceLoad(ctx context.Context, key Key) (context.Context, TraceLoadFinishFunc) {
return ctx, func(Thunk) {}
} | go | {
"resource": ""
} |
q18501 | TraceLoadMany | train | func (NoopTracer) TraceLoadMany(ctx context.Context, keys Keys) (context.Context, TraceLoadManyFinishFunc) {
return ctx, func(ThunkMany) {}
} | go | {
"resource": ""
} |
q18502 | TraceBatch | train | func (NoopTracer) TraceBatch(ctx context.Context, keys Keys) (context.Context, TraceBatchFinishFunc) {
return ctx, func(result []*Result) {}
} | go | {
"resource": ""
} |
q18503 | main | train | func main() {
env, err := plugins.NewEnvironment()
env.RespondAndExitIfError(err)
packageName, err := resolvePackageName(env.Request.OutputPath)
env.RespondAndExitIfError(err)
// Use the name used to run the plugin to decide which files to generate.
var files []string
switch {
case strings.Contains(env.Invocation, "gnostic-go-client"):
files = []string{"client.go", "types.go", "constants.go"}
case strings.Contains(env.Invocation, "gnostic-go-server"):
files = []string{"server.go", "provider.go", "types.go", "constants.go"}
default:
files = []string{"client.go", "server.go", "provider.go", "types.go", "constants.go"}
}
for _, model := range env.Request.Models {
switch model.TypeUrl {
case "surface.v1.Model":
surfaceModel := &surface.Model{}
err = proto.Unmarshal(model.Value, surfaceModel)
if err == nil {
// Customize the code surface model for Go
NewGoLanguageModel().Prepare(surfaceModel)
modelJSON, _ := json.MarshalIndent(surfaceModel, "", " ")
modelFile := &plugins.File{Name: "model.json", Data: modelJSON}
env.Response.Files = append(env.Response.Files, modelFile)
// Create the renderer.
renderer, err := NewServiceRenderer(surfaceModel)
renderer.Package = packageName
env.RespondAndExitIfError(err)
// Run the renderer to generate files and add them to the response object.
err = renderer.Render(env.Response, files)
env.RespondAndExitIfError(err)
// Return with success.
env.RespondAndExit()
}
}
}
err = errors.New("No generated code surface model is available.")
env.RespondAndExitIfError(err)
} | go | {
"resource": ""
} |
q18504 | resolvePackageName | train | func resolvePackageName(p string) (string, error) {
p, err := filepath.Abs(p)
if err == nil {
p = filepath.Base(p)
_, err = format.Source([]byte("package " + p))
}
if err != nil {
return "", errors.New("invalid package name " + p)
}
return p, nil
} | go | {
"resource": ""
} |
q18505 | Print | train | func (c *Code) Print(args ...interface{}) {
if len(args) > 0 {
for i := 0; i < c.indent; i++ {
c.text += indentation
}
c.text += fmt.Sprintf(args[0].(string), args[1:]...)
}
c.text += "\n"
} | go | {
"resource": ""
} |
q18506 | PrintIf | train | func (c *Code) PrintIf(condition bool, args ...interface{}) {
if !condition {
return
}
if len(args) > 0 {
for i := 0; i < c.indent; i++ {
c.text += indentation
}
c.text += fmt.Sprintf(args[0].(string), args[1:]...)
}
c.text += "\n"
} | go | {
"resource": ""
} |
q18507 | IsEmpty | train | func (schema *Schema) IsEmpty() bool {
return (schema.Schema == nil) &&
(schema.ID == nil) &&
(schema.MultipleOf == nil) &&
(schema.Maximum == nil) &&
(schema.ExclusiveMaximum == nil) &&
(schema.Minimum == nil) &&
(schema.ExclusiveMinimum == nil) &&
(schema.MaxLength == nil) &&
(schema.MinLength == nil) &&
(schema.Pattern == nil) &&
(schema.AdditionalItems == nil) &&
(schema.Items == nil) &&
(schema.MaxItems == nil) &&
(schema.MinItems == nil) &&
(schema.UniqueItems == nil) &&
(schema.MaxProperties == nil) &&
(schema.MinProperties == nil) &&
(schema.Required == nil) &&
(schema.AdditionalProperties == nil) &&
(schema.Properties == nil) &&
(schema.PatternProperties == nil) &&
(schema.Dependencies == nil) &&
(schema.Enumeration == nil) &&
(schema.Type == nil) &&
(schema.AllOf == nil) &&
(schema.AnyOf == nil) &&
(schema.OneOf == nil) &&
(schema.Not == nil) &&
(schema.Definitions == nil) &&
(schema.Title == nil) &&
(schema.Description == nil) &&
(schema.Default == nil) &&
(schema.Format == nil) &&
(schema.Ref == nil)
} | go | {
"resource": ""
} |
q18508 | IsEqual | train | func (schema *Schema) IsEqual(schema2 *Schema) bool {
return schema.String() == schema2.String()
} | go | {
"resource": ""
} |
q18509 | applyToSchemas | train | func (schema *Schema) applyToSchemas(operation SchemaOperation, context string) {
if schema.AdditionalItems != nil {
s := schema.AdditionalItems.Schema
if s != nil {
s.applyToSchemas(operation, "AdditionalItems")
}
}
if schema.Items != nil {
if schema.Items.SchemaArray != nil {
for _, s := range *(schema.Items.SchemaArray) {
s.applyToSchemas(operation, "Items.SchemaArray")
}
} else if schema.Items.Schema != nil {
schema.Items.Schema.applyToSchemas(operation, "Items.Schema")
}
}
if schema.AdditionalProperties != nil {
s := schema.AdditionalProperties.Schema
if s != nil {
s.applyToSchemas(operation, "AdditionalProperties")
}
}
if schema.Properties != nil {
for _, pair := range *(schema.Properties) {
s := pair.Value
s.applyToSchemas(operation, "Properties")
}
}
if schema.PatternProperties != nil {
for _, pair := range *(schema.PatternProperties) {
s := pair.Value
s.applyToSchemas(operation, "PatternProperties")
}
}
if schema.Dependencies != nil {
for _, pair := range *(schema.Dependencies) {
schemaOrStringArray := pair.Value
s := schemaOrStringArray.Schema
if s != nil {
s.applyToSchemas(operation, "Dependencies")
}
}
}
if schema.AllOf != nil {
for _, s := range *(schema.AllOf) {
s.applyToSchemas(operation, "AllOf")
}
}
if schema.AnyOf != nil {
for _, s := range *(schema.AnyOf) {
s.applyToSchemas(operation, "AnyOf")
}
}
if schema.OneOf != nil {
for _, s := range *(schema.OneOf) {
s.applyToSchemas(operation, "OneOf")
}
}
if schema.Not != nil {
schema.Not.applyToSchemas(operation, "Not")
}
if schema.Definitions != nil {
for _, pair := range *(schema.Definitions) {
s := pair.Value
s.applyToSchemas(operation, "Definitions")
}
}
operation(schema, context)
} | go | {
"resource": ""
} |
q18510 | TypeIs | train | func (schema *Schema) TypeIs(typeName string) bool {
if schema.Type != nil {
// the schema Type is either a string or an array of strings
if schema.Type.String != nil {
return (*(schema.Type.String) == typeName)
} else if schema.Type.StringArray != nil {
for _, n := range *(schema.Type.StringArray) {
if n == typeName {
return true
}
}
}
}
return false
} | go | {
"resource": ""
} |
q18511 | resolveJSONPointer | train | func (schema *Schema) resolveJSONPointer(ref string) (result *Schema, err error) {
parts := strings.Split(ref, "#")
if len(parts) == 2 {
documentName := parts[0] + "#"
if documentName == "#" && schema.ID != nil {
documentName = *(schema.ID)
}
path := parts[1]
document := schemas[documentName]
pathParts := strings.Split(path, "/")
// we currently do a very limited (hard-coded) resolution of certain paths and log errors for missed cases
if len(pathParts) == 1 {
return document, nil
} else if len(pathParts) == 3 {
switch pathParts[1] {
case "definitions":
dictionary := document.Definitions
for _, pair := range *dictionary {
if pair.Name == pathParts[2] {
result = pair.Value
}
}
case "properties":
dictionary := document.Properties
for _, pair := range *dictionary {
if pair.Name == pathParts[2] {
result = pair.Value
}
}
default:
break
}
}
}
if result == nil {
return nil, fmt.Errorf("unresolved pointer: %+v", ref)
}
return result, nil
} | go | {
"resource": ""
} |
q18512 | ResolveAllOfs | train | func (schema *Schema) ResolveAllOfs() {
schema.applyToSchemas(
func(schema *Schema, context string) {
if schema.AllOf != nil {
for _, allOf := range *(schema.AllOf) {
schema.CopyProperties(allOf)
}
schema.AllOf = nil
}
}, "resolveAllOfs")
} | go | {
"resource": ""
} |
q18513 | ResolveAnyOfs | train | func (schema *Schema) ResolveAnyOfs() {
schema.applyToSchemas(
func(schema *Schema, context string) {
if schema.AnyOf != nil {
schema.OneOf = schema.AnyOf
schema.AnyOf = nil
}
}, "resolveAnyOfs")
} | go | {
"resource": ""
} |
q18514 | CopyOfficialSchemaProperty | train | func (schema *Schema) CopyOfficialSchemaProperty(name string) {
*schema.Properties = append(*schema.Properties,
NewNamedSchema(name,
&Schema{Ref: stringptr("http://json-schema.org/draft-04/schema#/properties/" + name)}))
} | go | {
"resource": ""
} |
q18515 | CopyOfficialSchemaProperties | train | func (schema *Schema) CopyOfficialSchemaProperties(names []string) {
for _, name := range names {
schema.CopyOfficialSchemaProperty(name)
}
} | go | {
"resource": ""
} |
q18516 | escape | train | func escape(s string) string {
s = strings.Replace(s, "\n", "\\n", -1)
s = strings.Replace(s, "\"", "\\\"", -1)
return s
} | go | {
"resource": ""
} |
q18517 | Marshal | train | func Marshal(in interface{}) (out []byte, err error) {
var w writer
m, ok := in.(yaml.MapSlice)
if !ok {
return nil, errors.New("invalid type passed to Marshal")
}
w.writeMap(m, "")
w.writeString("\n")
return w.bytes(), err
} | go | {
"resource": ""
} |
q18518 | NewContextWithExtensions | train | func NewContextWithExtensions(name string, parent *Context, extensionHandlers *[]ExtensionHandler) *Context {
return &Context{Name: name, Parent: parent, ExtensionHandlers: extensionHandlers}
} | go | {
"resource": ""
} |
q18519 | NewContext | train | func NewContext(name string, parent *Context) *Context {
if parent != nil {
return &Context{Name: name, Parent: parent, ExtensionHandlers: parent.ExtensionHandlers}
}
return &Context{Name: name, Parent: parent, ExtensionHandlers: nil}
} | go | {
"resource": ""
} |
q18520 | Description | train | func (context *Context) Description() string {
if context.Parent != nil {
return context.Parent.Description() + "." + context.Name
}
return context.Name
} | go | {
"resource": ""
} |
q18521 | analyzeDocument | train | func (s *DocumentLinterV2) analyzeDocument(document *openapi.Document) []*plugins.Message {
messages := make([]*plugins.Message, 0, 0)
for _, pair := range document.Paths.Path {
path := pair.Value
if path.Get != nil {
messages = append(messages, s.analyzeOperation([]string{"paths", pair.Name, "get"}, path.Get)...)
}
if path.Post != nil {
messages = append(messages, s.analyzeOperation([]string{"paths", pair.Name, "post"}, path.Post)...)
}
if path.Put != nil {
messages = append(messages, s.analyzeOperation([]string{"paths", pair.Name, "put"}, path.Put)...)
}
if path.Delete != nil {
messages = append(messages, s.analyzeOperation([]string{"paths", pair.Name, "delete"}, path.Delete)...)
}
}
if document.Definitions != nil {
for _, pair := range document.Definitions.AdditionalProperties {
definition := pair.Value
messages = append(messages, s.analyzeDefinition([]string{"definitions", pair.Name}, definition)...)
}
}
return messages
} | go | {
"resource": ""
} |
q18522 | analyzeDefinition | train | func (s *DocumentLinterV2) analyzeDefinition(keys []string, definition *openapi.Schema) []*plugins.Message {
messages := make([]*plugins.Message, 0)
if definition.Description == "" {
messages = append(messages,
&plugins.Message{
Level: plugins.Message_WARNING,
Code: "NODESCRIPTION",
Text: "Definition has no description.",
Keys: keys})
}
if definition.Properties != nil {
for _, pair := range definition.Properties.AdditionalProperties {
propertySchema := pair.Value
if propertySchema.Description == "" {
messages = append(messages,
&plugins.Message{
Level: plugins.Message_WARNING,
Code: "NODESCRIPTION",
Text: "Property has no description.",
Keys: append(keys, []string{"properties", pair.Name}...)})
}
}
}
return messages
} | go | {
"resource": ""
} |
q18523 | NewSchemaFromFile | train | func NewSchemaFromFile(filename string) (schema *Schema, err error) {
file, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
var info yaml.MapSlice
err = yaml.Unmarshal(file, &info)
if err != nil {
return nil, err
}
return NewSchemaFromObject(info), nil
} | go | {
"resource": ""
} |
q18524 | NewDomain | train | func NewDomain(schema *jsonschema.Schema, version string) *Domain {
cc := &Domain{}
cc.TypeModels = make(map[string]*TypeModel, 0)
cc.TypeNameOverrides = make(map[string]string, 0)
cc.PropertyNameOverrides = make(map[string]string, 0)
cc.ObjectTypeRequests = make(map[string]*TypeRequest, 0)
cc.MapTypeRequests = make(map[string]string, 0)
cc.Schema = schema
cc.Version = version
return cc
} | go | {
"resource": ""
} |
q18525 | TypeNameForStub | train | func (domain *Domain) TypeNameForStub(stub string) string {
return domain.Prefix + strings.ToUpper(stub[0:1]) + stub[1:len(stub)]
} | go | {
"resource": ""
} |
q18526 | typeNameForReference | train | func (domain *Domain) typeNameForReference(reference string) string {
parts := strings.Split(reference, "/")
first := parts[0]
last := parts[len(parts)-1]
if first == "#" {
return domain.TypeNameForStub(last)
}
return "Schema"
} | go | {
"resource": ""
} |
q18527 | propertyNameForReference | train | func (domain *Domain) propertyNameForReference(reference string) *string {
parts := strings.Split(reference, "/")
first := parts[0]
last := parts[len(parts)-1]
if first == "#" {
return &last
}
return nil
} | go | {
"resource": ""
} |
q18528 | arrayItemTypeForSchema | train | func (domain *Domain) arrayItemTypeForSchema(propertyName string, schema *jsonschema.Schema) string {
// default
itemTypeName := "Any"
if schema.Items != nil {
if schema.Items.SchemaArray != nil {
if len(*(schema.Items.SchemaArray)) > 0 {
ref := (*schema.Items.SchemaArray)[0].Ref
if ref != nil {
itemTypeName = domain.typeNameForReference(*ref)
} else {
types := (*schema.Items.SchemaArray)[0].Type
if types == nil {
// do nothing
} else if (types.StringArray != nil) && len(*(types.StringArray)) == 1 {
itemTypeName = (*types.StringArray)[0]
} else if (types.StringArray != nil) && len(*(types.StringArray)) > 1 {
itemTypeName = fmt.Sprintf("%+v", types.StringArray)
} else if types.String != nil {
itemTypeName = *(types.String)
} else {
itemTypeName = "UNKNOWN"
}
}
}
} else if schema.Items.Schema != nil {
types := schema.Items.Schema.Type
if schema.Items.Schema.Ref != nil {
itemTypeName = domain.typeNameForReference(*schema.Items.Schema.Ref)
} else if schema.Items.Schema.OneOf != nil {
// this type is implied by the "oneOf"
itemTypeName = domain.TypeNameForStub(propertyName + "Item")
domain.ObjectTypeRequests[itemTypeName] =
NewTypeRequest(itemTypeName, propertyName, schema.Items.Schema)
} else if types == nil {
// do nothing
} else if (types.StringArray != nil) && len(*(types.StringArray)) == 1 {
itemTypeName = (*types.StringArray)[0]
} else if (types.StringArray != nil) && len(*(types.StringArray)) > 1 {
itemTypeName = fmt.Sprintf("%+v", types.StringArray)
} else if types.String != nil {
itemTypeName = *(types.String)
} else {
itemTypeName = "UNKNOWN"
}
}
}
return itemTypeName
} | go | {
"resource": ""
} |
q18529 | BuildTypeForDefinition | train | func (domain *Domain) BuildTypeForDefinition(
typeName string,
propertyName string,
schema *jsonschema.Schema) *TypeModel {
if (schema.Type == nil) || (*schema.Type.String == "object") {
return domain.buildTypeForDefinitionObject(typeName, propertyName, schema)
}
return nil
} | go | {
"resource": ""
} |
q18530 | Description | train | func (domain *Domain) Description() string {
typeNames := domain.sortedTypeNames()
result := ""
for _, typeName := range typeNames {
result += domain.TypeModels[typeName].description()
}
return result
} | go | {
"resource": ""
} |
q18531 | UnpackMap | train | func UnpackMap(in interface{}) (yaml.MapSlice, bool) {
m, ok := in.(yaml.MapSlice)
if ok {
return m, true
}
// do we have an empty array?
a, ok := in.([]interface{})
if ok && len(a) == 0 {
// if so, return an empty map
return yaml.MapSlice{}, true
}
return nil, false
} | go | {
"resource": ""
} |
q18532 | SortedKeysForMap | train | func SortedKeysForMap(m yaml.MapSlice) []string {
keys := make([]string, 0)
for _, item := range m {
keys = append(keys, item.Key.(string))
}
sort.Strings(keys)
return keys
} | go | {
"resource": ""
} |
q18533 | MapHasKey | train | func MapHasKey(m yaml.MapSlice, key string) bool {
for _, item := range m {
itemKey, ok := item.Key.(string)
if ok && key == itemKey {
return true
}
}
return false
} | go | {
"resource": ""
} |
q18534 | MapValueForKey | train | func MapValueForKey(m yaml.MapSlice, key string) interface{} {
for _, item := range m {
itemKey, ok := item.Key.(string)
if ok && key == itemKey {
return item.Value
}
}
return nil
} | go | {
"resource": ""
} |
q18535 | ConvertInterfaceArrayToStringArray | train | func ConvertInterfaceArrayToStringArray(interfaceArray []interface{}) []string {
stringArray := make([]string, 0)
for _, item := range interfaceArray {
v, ok := item.(string)
if ok {
stringArray = append(stringArray, v)
}
}
return stringArray
} | go | {
"resource": ""
} |
q18536 | MissingKeysInMap | train | func MissingKeysInMap(m yaml.MapSlice, requiredKeys []string) []string {
missingKeys := make([]string, 0)
for _, k := range requiredKeys {
if !MapHasKey(m, k) {
missingKeys = append(missingKeys, k)
}
}
return missingKeys
} | go | {
"resource": ""
} |
q18537 | InvalidKeysInMap | train | func InvalidKeysInMap(m yaml.MapSlice, allowedKeys []string, allowedPatterns []*regexp.Regexp) []string {
invalidKeys := make([]string, 0)
for _, item := range m {
itemKey, ok := item.Key.(string)
if ok {
key := itemKey
found := false
// does the key match an allowed key?
for _, allowedKey := range allowedKeys {
if key == allowedKey {
found = true
break
}
}
if !found {
// does the key match an allowed pattern?
for _, allowedPattern := range allowedPatterns {
if allowedPattern.MatchString(key) {
found = true
break
}
}
if !found {
invalidKeys = append(invalidKeys, key)
}
}
}
}
return invalidKeys
} | go | {
"resource": ""
} |
q18538 | StringArrayContainsValue | train | func StringArrayContainsValue(array []string, value string) bool {
for _, item := range array {
if item == value {
return true
}
}
return false
} | go | {
"resource": ""
} |
q18539 | StringArrayContainsValues | train | func StringArrayContainsValues(array []string, values []string) bool {
for _, value := range values {
if !StringArrayContainsValue(array, value) {
return false
}
}
return true
} | go | {
"resource": ""
} |
q18540 | StringValue | train | func StringValue(item interface{}) (value string, ok bool) {
value, ok = item.(string)
if ok {
return value, ok
}
intValue, ok := item.(int)
if ok {
return strconv.Itoa(intValue), true
}
return "", false
} | go | {
"resource": ""
} |
q18541 | NewTypeRequest | train | func NewTypeRequest(name string, propertyName string, schema *jsonschema.Schema) *TypeRequest {
return &TypeRequest{Name: name, PropertyName: propertyName, Schema: schema}
} | go | {
"resource": ""
} |
q18542 | NewTypePropertyWithNameAndType | train | func NewTypePropertyWithNameAndType(name string, typeName string) *TypeProperty {
return &TypeProperty{Name: name, Type: typeName}
} | go | {
"resource": ""
} |
q18543 | NewTypePropertyWithNameTypeAndPattern | train | func NewTypePropertyWithNameTypeAndPattern(name string, typeName string, pattern string) *TypeProperty {
return &TypeProperty{Name: name, Type: typeName, Pattern: pattern}
} | go | {
"resource": ""
} |
q18544 | FieldName | train | func (typeProperty *TypeProperty) FieldName() string {
propertyName := typeProperty.Name
if propertyName == "$ref" {
return "XRef"
}
return strings.Title(snakeCaseToCamelCase(propertyName))
} | go | {
"resource": ""
} |
q18545 | walker | train | func walker(p string, info os.FileInfo, err error) error {
basename := path.Base(p)
if basename != "summary.json" {
return nil
}
data, err := ioutil.ReadFile(p)
if err != nil {
return err
}
var s statistics.DocumentStatistics
err = json.Unmarshal(data, &s)
if err != nil {
return err
}
stats = append(stats, s)
return nil
} | go | {
"resource": ""
} |
q18546 | sendAndExitIfError | train | func sendAndExitIfError(err error, response *plugins.Response) {
if err != nil {
response.Errors = append(response.Errors, err.Error())
sendAndExit(response)
}
} | go | {
"resource": ""
} |
q18547 | sendAndExit | train | func sendAndExit(response *plugins.Response) {
responseBytes, _ := proto.Marshal(response)
os.Stdout.Write(responseBytes)
os.Exit(0)
} | go | {
"resource": ""
} |
q18548 | NewSchemaNumberWithInteger | train | func NewSchemaNumberWithInteger(i int64) *SchemaNumber {
result := &SchemaNumber{}
result.Integer = &i
return result
} | go | {
"resource": ""
} |
q18549 | NewSchemaNumberWithFloat | train | func NewSchemaNumberWithFloat(f float64) *SchemaNumber {
result := &SchemaNumber{}
result.Float = &f
return result
} | go | {
"resource": ""
} |
q18550 | NewSchemaOrBooleanWithSchema | train | func NewSchemaOrBooleanWithSchema(s *Schema) *SchemaOrBoolean {
result := &SchemaOrBoolean{}
result.Schema = s
return result
} | go | {
"resource": ""
} |
q18551 | NewSchemaOrBooleanWithBoolean | train | func NewSchemaOrBooleanWithBoolean(b bool) *SchemaOrBoolean {
result := &SchemaOrBoolean{}
result.Boolean = &b
return result
} | go | {
"resource": ""
} |
q18552 | NewStringOrStringArrayWithString | train | func NewStringOrStringArrayWithString(s string) *StringOrStringArray {
result := &StringOrStringArray{}
result.String = &s
return result
} | go | {
"resource": ""
} |
q18553 | NewStringOrStringArrayWithStringArray | train | func NewStringOrStringArrayWithStringArray(a []string) *StringOrStringArray {
result := &StringOrStringArray{}
result.StringArray = &a
return result
} | go | {
"resource": ""
} |
q18554 | NewSchemaOrSchemaArrayWithSchema | train | func NewSchemaOrSchemaArrayWithSchema(s *Schema) *SchemaOrSchemaArray {
result := &SchemaOrSchemaArray{}
result.Schema = s
return result
} | go | {
"resource": ""
} |
q18555 | NewSchemaOrSchemaArrayWithSchemaArray | train | func NewSchemaOrSchemaArrayWithSchemaArray(a []*Schema) *SchemaOrSchemaArray {
result := &SchemaOrSchemaArray{}
result.SchemaArray = &a
return result
} | go | {
"resource": ""
} |
q18556 | NewNamedSchema | train | func NewNamedSchema(name string, value *Schema) *NamedSchema {
return &NamedSchema{Name: name, Value: value}
} | go | {
"resource": ""
} |
q18557 | namedSchemaArrayElementWithName | train | func namedSchemaArrayElementWithName(array *[]*NamedSchema, name string) *Schema {
if array == nil {
return nil
}
for _, pair := range *array {
if pair.Name == name {
return pair.Value
}
}
return nil
} | go | {
"resource": ""
} |
q18558 | PropertyWithName | train | func (s *Schema) PropertyWithName(name string) *Schema {
return namedSchemaArrayElementWithName(s.Properties, name)
} | go | {
"resource": ""
} |
q18559 | PatternPropertyWithName | train | func (s *Schema) PatternPropertyWithName(name string) *Schema {
return namedSchemaArrayElementWithName(s.PatternProperties, name)
} | go | {
"resource": ""
} |
q18560 | DefinitionWithName | train | func (s *Schema) DefinitionWithName(name string) *Schema {
return namedSchemaArrayElementWithName(s.Definitions, name)
} | go | {
"resource": ""
} |
q18561 | AddProperty | train | func (s *Schema) AddProperty(name string, property *Schema) {
*s.Properties = append(*s.Properties, NewNamedSchema(name, property))
} | go | {
"resource": ""
} |
q18562 | lowerFirst | train | func lowerFirst(s string) string {
if s == "" {
return ""
}
r, n := utf8.DecodeRuneInString(s)
return string(unicode.ToLower(r)) + s[n:]
} | go | {
"resource": ""
} |
q18563 | ReadSection | train | func ReadSection(text string, level int) (section *Section) {
titlePattern := regexp.MustCompile("^" + strings.Repeat("#", level) + " .*$")
subtitlePattern := regexp.MustCompile("^" + strings.Repeat("#", level+1) + " .*$")
section = &Section{Level: level, Text: text}
lines := strings.Split(string(text), "\n")
subsection := ""
for i, line := range lines {
if i == 0 && titlePattern.Match([]byte(line)) {
section.Title = line
} else if subtitlePattern.Match([]byte(line)) {
// we've found a subsection title.
// if there's a subsection that we've already been reading, save it
if len(subsection) != 0 {
child := ReadSection(subsection, level+1)
section.Children = append(section.Children, child)
}
// start a new subsection
subsection = line + "\n"
} else {
// add to the subsection we've been reading
subsection += line + "\n"
}
}
// if this section has subsections, save the last one
if len(section.Children) > 0 {
child := ReadSection(subsection, level+1)
section.Children = append(section.Children, child)
}
return
} | go | {
"resource": ""
} |
q18564 | Display | train | func (s *Section) Display(section string) {
if len(s.Children) == 0 {
//fmt.Printf("%s\n", s.Text)
} else {
for i, child := range s.Children {
var subsection string
if section == "" {
subsection = fmt.Sprintf("%d", i)
} else {
subsection = fmt.Sprintf("%s.%d", section, i)
}
fmt.Printf("%-12s %s\n", subsection, child.NiceTitle())
child.Display(subsection)
}
}
} | go | {
"resource": ""
} |
q18565 | stripLink | train | func stripLink(input string) (output string) {
stringPattern := regexp.MustCompile("^(.*)$")
stringWithLinkPattern := regexp.MustCompile("^<a .*</a>(.*)$")
if matches := stringWithLinkPattern.FindSubmatch([]byte(input)); matches != nil {
return string(matches[1])
} else if matches := stringPattern.FindSubmatch([]byte(input)); matches != nil {
return string(matches[1])
} else {
return input
}
} | go | {
"resource": ""
} |
q18566 | parseFixedFields | train | func parseFixedFields(input string, schemaObject *SchemaObject) {
lines := strings.Split(input, "\n")
for _, line := range lines {
// replace escaped bars with "OR", assuming these are used to describe union types
line = strings.Replace(line, " \\| ", " OR ", -1)
// split the table on the remaining bars
parts := strings.Split(line, "|")
if len(parts) > 1 {
fieldName := strings.Trim(stripLink(parts[0]), " ")
if fieldName != "Field Name" && fieldName != "---" {
if len(parts) == 3 || len(parts) == 4 {
// this is what we expect
} else {
log.Printf("ERROR: %+v", parts)
}
typeName := parts[1]
typeName = strings.Replace(typeName, "{expression}", "Expression", -1)
typeName = strings.Trim(typeName, " ")
typeName = strings.Replace(typeName, "`", "", -1)
typeName = removeMarkdownLinks(typeName)
typeName = strings.Replace(typeName, " ", "", -1)
typeName = strings.Replace(typeName, "Object", "", -1)
isArray := false
if typeName[0] == '[' && typeName[len(typeName)-1] == ']' {
typeName = typeName[1 : len(typeName)-1]
isArray = true
}
isMap := false
mapPattern := regexp.MustCompile("^Mapstring,\\[(.*)\\]$")
if matches := mapPattern.FindSubmatch([]byte(typeName)); matches != nil {
typeName = string(matches[1])
isMap = true
} else {
// match map[string,<typename>]
mapPattern2 := regexp.MustCompile("^Map\\[string,(.+)\\]$")
if matches := mapPattern2.FindSubmatch([]byte(typeName)); matches != nil {
typeName = string(matches[1])
isMap = true
}
}
description := strings.Trim(parts[len(parts)-1], " ")
description = removeMarkdownLinks(description)
description = strings.Replace(description, "\n", " ", -1)
requiredLabel1 := "**Required.** "
requiredLabel2 := "**REQUIRED**."
if strings.Contains(description, requiredLabel1) ||
strings.Contains(description, requiredLabel2) {
// only include required values if their "Validity" is "Any" or if no validity is specified
valid := true
if len(parts) == 4 {
validity := parts[2]
if strings.Contains(validity, "Any") {
valid = true
} else {
valid = false
}
}
if valid {
schemaObject.RequiredFields = append(schemaObject.RequiredFields, fieldName)
}
description = strings.Replace(description, requiredLabel1, "", -1)
description = strings.Replace(description, requiredLabel2, "", -1)
}
schemaField := SchemaObjectField{
Name: fieldName,
Type: typeName,
IsArray: isArray,
IsMap: isMap,
Description: description,
}
schemaObject.FixedFields = append(schemaObject.FixedFields, schemaField)
}
}
}
} | go | {
"resource": ""
} |
q18567 | parsePatternedFields | train | func parsePatternedFields(input string, schemaObject *SchemaObject) {
lines := strings.Split(input, "\n")
for _, line := range lines {
line = strings.Replace(line, " \\| ", " OR ", -1)
parts := strings.Split(line, "|")
if len(parts) > 1 {
fieldName := strings.Trim(stripLink(parts[0]), " ")
fieldName = removeMarkdownLinks(fieldName)
if fieldName == "HTTP Status Code" {
fieldName = "^([0-9X]{3})$"
}
if fieldName != "Field Pattern" && fieldName != "---" {
typeName := parts[1]
typeName = strings.Trim(typeName, " ")
typeName = strings.Replace(typeName, "`", "", -1)
typeName = removeMarkdownLinks(typeName)
typeName = strings.Replace(typeName, " ", "", -1)
typeName = strings.Replace(typeName, "Object", "", -1)
typeName = strings.Replace(typeName, "{expression}", "Expression", -1)
isArray := false
if typeName[0] == '[' && typeName[len(typeName)-1] == ']' {
typeName = typeName[1 : len(typeName)-1]
isArray = true
}
isMap := false
mapPattern := regexp.MustCompile("^Mapstring,\\[(.*)\\]$")
if matches := mapPattern.FindSubmatch([]byte(typeName)); matches != nil {
typeName = string(matches[1])
isMap = true
}
description := strings.Trim(parts[len(parts)-1], " ")
description = removeMarkdownLinks(description)
description = strings.Replace(description, "\n", " ", -1)
schemaField := SchemaObjectField{
Name: fieldName,
Type: typeName,
IsArray: isArray,
IsMap: isMap,
Description: description,
}
schemaObject.PatternedFields = append(schemaObject.PatternedFields, schemaField)
}
}
}
} | go | {
"resource": ""
} |
q18568 | NewSchemaModel | train | func NewSchemaModel(filename string) (schemaModel *SchemaModel, err error) {
b, err := ioutil.ReadFile("3.0.1.md")
if err != nil {
return nil, err
}
// divide the specification into sections
document := ReadSection(string(b), 1)
document.Display("")
// read object names and their details
specification := document.Children[4] // fragile! the section title is "Specification"
schema := specification.Children[7] // fragile! the section title is "Schema"
anchor := regexp.MustCompile("^#### <a name=\"(.*)Object\"")
schemaObjects := make([]SchemaObject, 0)
for _, section := range schema.Children {
if matches := anchor.FindSubmatch([]byte(section.Title)); matches != nil {
id := string(matches[1])
schemaObject := SchemaObject{
Name: section.NiceTitle(),
ID: id,
RequiredFields: nil,
}
if len(section.Children) > 0 {
description := section.Children[0].Text
description = removeMarkdownLinks(description)
description = strings.Trim(description, " \t\n")
description = strings.Replace(description, "\n", " ", -1)
schemaObject.Description = description
}
// is the object extendable?
if strings.Contains(section.Text, "Specification Extensions") {
schemaObject.Extendable = true
}
// look for fixed fields
for _, child := range section.Children {
if child.NiceTitle() == "Fixed Fields" {
parseFixedFields(child.Text, &schemaObject)
}
}
// look for patterned fields
for _, child := range section.Children {
if child.NiceTitle() == "Patterned Fields" {
parsePatternedFields(child.Text, &schemaObject)
}
}
schemaObjects = append(schemaObjects, schemaObject)
}
}
return &SchemaModel{Objects: schemaObjects}, nil
} | go | {
"resource": ""
} |
q18569 | NewError | train | func NewError(context *Context, message string) *Error {
return &Error{Context: context, Message: message}
} | go | {
"resource": ""
} |
q18570 | Error | train | func (err *Error) Error() string {
if err.Context == nil {
return "ERROR " + err.Message
}
return "ERROR " + err.Context.Description() + " " + err.Message
} | go | {
"resource": ""
} |
q18571 | NewErrorGroupOrNil | train | func NewErrorGroupOrNil(errors []error) error {
if len(errors) == 0 {
return nil
} else if len(errors) == 1 {
return errors[0]
} else {
return &ErrorGroup{Errors: errors}
}
} | go | {
"resource": ""
} |
q18572 | getOpenAPIVersionFromInfo | train | func getOpenAPIVersionFromInfo(info interface{}) int {
m, ok := compiler.UnpackMap(info)
if !ok {
return SourceFormatUnknown
}
swagger, ok := compiler.MapValueForKey(m, "swagger").(string)
if ok && strings.HasPrefix(swagger, "2.0") {
return SourceFormatOpenAPI2
}
openapi, ok := compiler.MapValueForKey(m, "openapi").(string)
if ok && strings.HasPrefix(openapi, "3.0") {
return SourceFormatOpenAPI3
}
kind, ok := compiler.MapValueForKey(m, "kind").(string)
if ok && kind == "discovery#restDescription" {
return SourceFormatDiscovery
}
return SourceFormatUnknown
} | go | {
"resource": ""
} |
q18573 | newGnostic | train | func newGnostic() *Gnostic {
g := &Gnostic{}
// Option fields initialize to their default values.
g.usage = `
Usage: gnostic SOURCE [OPTIONS]
SOURCE is the filename or URL of an API description.
Options:
--pb-out=PATH Write a binary proto to the specified location.
--text-out=PATH Write a text proto to the specified location.
--json-out=PATH Write a json API description to the specified location.
--yaml-out=PATH Write a yaml API description to the specified location.
--errors-out=PATH Write compilation errors to the specified location.
--messages-out=PATH Write messages generated by plugins to the specified
location. Messages from all plugin invocations are
written to a single common file.
--PLUGIN-out=PATH Run the plugin named gnostic-PLUGIN and write results
to the specified location.
--PLUGIN Run the plugin named gnostic-PLUGIN but don't write any
results. Used for plugins that return messages only.
PLUGIN must not match any other gnostic option.
--x-EXTENSION Use the extension named gnostic-x-EXTENSION
to process OpenAPI specification extensions.
--resolve-refs Explicitly resolve $ref references.
This could have problems with recursive definitions.
--time-plugins Report plugin runtimes.
`
// Initialize internal structures.
g.pluginCalls = make([]*pluginCall, 0)
g.extensionHandlers = make([]compiler.ExtensionHandler, 0)
return g
} | go | {
"resource": ""
} |
q18574 | readOptions | train | func (g *Gnostic) readOptions() {
// plugin processing matches patterns of the form "--PLUGIN-out=PATH" and "--PLUGIN_out=PATH"
pluginRegex := regexp.MustCompile("--(.+)[-_]out=(.+)")
// extension processing matches patterns of the form "--x-EXTENSION"
extensionRegex := regexp.MustCompile("--x-(.+)")
for i, arg := range os.Args {
if i == 0 {
continue // skip the tool name
}
var m [][]byte
if m = pluginRegex.FindSubmatch([]byte(arg)); m != nil {
pluginName := string(m[1])
invocation := string(m[2])
switch pluginName {
case "pb":
g.binaryOutputPath = invocation
case "text":
g.textOutputPath = invocation
case "json":
g.jsonOutputPath = invocation
case "yaml":
g.yamlOutputPath = invocation
case "errors":
g.errorOutputPath = invocation
case "messages":
g.messageOutputPath = invocation
default:
p := &pluginCall{Name: pluginName, Invocation: invocation}
g.pluginCalls = append(g.pluginCalls, p)
}
} else if m = extensionRegex.FindSubmatch([]byte(arg)); m != nil {
extensionName := string(m[1])
extensionHandler := compiler.ExtensionHandler{Name: extensionPrefix + extensionName}
g.extensionHandlers = append(g.extensionHandlers, extensionHandler)
} else if arg == "--resolve-refs" {
g.resolveReferences = true
} else if arg == "--time-plugins" {
g.timePlugins = true
} else if arg[0] == '-' && arg[1] == '-' {
// try letting the option specify a plugin with no output files (or unwanted output files)
// this is useful for calling plugins like linters that only return messages
p := &pluginCall{Name: arg[2:len(arg)], Invocation: "!"}
g.pluginCalls = append(g.pluginCalls, p)
} else if arg[0] == '-' {
fmt.Fprintf(os.Stderr, "Unknown option: %s.\n%s\n", arg, g.usage)
os.Exit(-1)
} else {
g.sourceName = arg
}
}
} | go | {
"resource": ""
} |
q18575 | validateOptions | train | func (g *Gnostic) validateOptions() {
if g.binaryOutputPath == "" &&
g.textOutputPath == "" &&
g.yamlOutputPath == "" &&
g.jsonOutputPath == "" &&
g.errorOutputPath == "" &&
len(g.pluginCalls) == 0 {
fmt.Fprintf(os.Stderr, "Missing output directives.\n%s\n", g.usage)
os.Exit(-1)
}
if g.sourceName == "" {
fmt.Fprintf(os.Stderr, "No input specified.\n%s\n", g.usage)
os.Exit(-1)
}
// If we get here and the error output is unspecified, write errors to stderr.
if g.errorOutputPath == "" {
g.errorOutputPath = "="
}
} | go | {
"resource": ""
} |
q18576 | errorBytes | train | func (g *Gnostic) errorBytes(err error) []byte {
return []byte("Errors reading " + g.sourceName + "\n" + err.Error())
} | go | {
"resource": ""
} |
q18577 | readOpenAPIText | train | func (g *Gnostic) readOpenAPIText(bytes []byte) (message proto.Message, err error) {
info, err := compiler.ReadInfoFromBytes(g.sourceName, bytes)
if err != nil {
return nil, err
}
// Determine the OpenAPI version.
g.sourceFormat = getOpenAPIVersionFromInfo(info)
if g.sourceFormat == SourceFormatUnknown {
return nil, errors.New("unable to identify OpenAPI version")
}
// Compile to the proto model.
if g.sourceFormat == SourceFormatOpenAPI2 {
document, err := openapi_v2.NewDocument(info, compiler.NewContextWithExtensions("$root", nil, &g.extensionHandlers))
if err != nil {
return nil, err
}
message = document
} else if g.sourceFormat == SourceFormatOpenAPI3 {
document, err := openapi_v3.NewDocument(info, compiler.NewContextWithExtensions("$root", nil, &g.extensionHandlers))
if err != nil {
return nil, err
}
message = document
} else {
document, err := discovery_v1.NewDocument(info, compiler.NewContextWithExtensions("$root", nil, &g.extensionHandlers))
if err != nil {
return nil, err
}
message = document
}
return message, err
} | go | {
"resource": ""
} |
q18578 | readOpenAPIBinary | train | func (g *Gnostic) readOpenAPIBinary(data []byte) (message proto.Message, err error) {
// try to read an OpenAPI v3 document
documentV3 := &openapi_v3.Document{}
err = proto.Unmarshal(data, documentV3)
if err == nil && strings.HasPrefix(documentV3.Openapi, "3.0") {
g.sourceFormat = SourceFormatOpenAPI3
return documentV3, nil
}
// if that failed, try to read an OpenAPI v2 document
documentV2 := &openapi_v2.Document{}
err = proto.Unmarshal(data, documentV2)
if err == nil && strings.HasPrefix(documentV2.Swagger, "2.0") {
g.sourceFormat = SourceFormatOpenAPI2
return documentV2, nil
}
// if that failed, try to read a Discovery Format document
discoveryDocument := &discovery_v1.Document{}
err = proto.Unmarshal(data, discoveryDocument)
if err == nil { // && strings.HasPrefix(documentV2.Swagger, "2.0") {
g.sourceFormat = SourceFormatDiscovery
return discoveryDocument, nil
}
return nil, err
} | go | {
"resource": ""
} |
q18579 | writeBinaryOutput | train | func (g *Gnostic) writeBinaryOutput(message proto.Message) {
protoBytes, err := proto.Marshal(message)
if err != nil {
writeFile(g.errorOutputPath, g.errorBytes(err), g.sourceName, "errors")
defer os.Exit(-1)
} else {
writeFile(g.binaryOutputPath, protoBytes, g.sourceName, "pb")
}
} | go | {
"resource": ""
} |
q18580 | writeTextOutput | train | func (g *Gnostic) writeTextOutput(message proto.Message) {
bytes := []byte(proto.MarshalTextString(message))
writeFile(g.textOutputPath, bytes, g.sourceName, "text")
} | go | {
"resource": ""
} |
q18581 | writeMessagesOutput | train | func (g *Gnostic) writeMessagesOutput(message proto.Message) {
protoBytes, err := proto.Marshal(message)
if err != nil {
writeFile(g.messageOutputPath, g.errorBytes(err), g.sourceName, "errors")
defer os.Exit(-1)
} else {
writeFile(g.messageOutputPath, protoBytes, g.sourceName, "messages.pb")
}
} | go | {
"resource": ""
} |
q18582 | performActions | train | func (g *Gnostic) performActions(message proto.Message) (err error) {
// Optionally resolve internal references.
if g.resolveReferences {
if g.sourceFormat == SourceFormatOpenAPI2 {
document := message.(*openapi_v2.Document)
_, err = document.ResolveReferences(g.sourceName)
} else if g.sourceFormat == SourceFormatOpenAPI3 {
document := message.(*openapi_v3.Document)
_, err = document.ResolveReferences(g.sourceName)
}
if err != nil {
return err
}
}
// Optionally write proto in binary format.
if g.binaryOutputPath != "" {
g.writeBinaryOutput(message)
}
// Optionally write proto in text format.
if g.textOutputPath != "" {
g.writeTextOutput(message)
}
// Optionally write document in yaml and/or json formats.
if g.yamlOutputPath != "" || g.jsonOutputPath != "" {
g.writeJSONYAMLOutput(message)
}
// Call all specified plugins.
messages := make([]*plugins.Message, 0)
for _, p := range g.pluginCalls {
pluginMessages, err := p.perform(message, g.sourceFormat, g.sourceName, g.timePlugins)
if err != nil {
writeFile(g.errorOutputPath, g.errorBytes(err), g.sourceName, "errors")
defer os.Exit(-1) // run all plugins, even when some have errors
}
messages = append(messages, pluginMessages...)
}
if g.messageOutputPath != "" {
g.writeMessagesOutput(&plugins.Messages{Messages: messages})
} else {
// Print any messages from the plugins
if len(messages) > 0 {
for _, message := range messages {
fmt.Printf("%+v\n", message)
}
}
}
return nil
} | go | {
"resource": ""
} |
q18583 | ProcessExtension | train | func ProcessExtension(handleExtension extensionHandler) {
response := &ExtensionHandlerResponse{}
forInputYamlFromOpenapic(
func(version string, extensionName string, yamlInput string) {
var newObject proto.Message
var err error
handled, newObject, err := handleExtension(extensionName, yamlInput)
if !handled {
responseBytes, _ := proto.Marshal(response)
os.Stdout.Write(responseBytes)
os.Exit(0)
}
// If we reach here, then the extension is handled
response.Handled = true
if err != nil {
response.Error = append(response.Error, err.Error())
responseBytes, _ := proto.Marshal(response)
os.Stdout.Write(responseBytes)
os.Exit(0)
}
response.Value, err = ptypes.MarshalAny(newObject)
if err != nil {
response.Error = append(response.Error, err.Error())
responseBytes, _ := proto.Marshal(response)
os.Stdout.Write(responseBytes)
os.Exit(0)
}
})
responseBytes, _ := proto.Marshal(response)
os.Stdout.Write(responseBytes)
} | go | {
"resource": ""
} |
q18584 | NewAnnotations | train | func NewAnnotations(in interface{}, context *compiler.Context) (*Annotations, error) {
errors := make([]error, 0)
x := &Annotations{}
m, ok := compiler.UnpackMap(in)
if !ok {
message := fmt.Sprintf("has unexpected value: %+v (%T)", in, in)
errors = append(errors, compiler.NewError(context, message))
} else {
allowedKeys := []string{"required"}
var allowedPatterns []*regexp.Regexp
invalidKeys := compiler.InvalidKeysInMap(m, allowedKeys, allowedPatterns)
if len(invalidKeys) > 0 {
message := fmt.Sprintf("has invalid %s: %+v", compiler.PluralProperties(len(invalidKeys)), strings.Join(invalidKeys, ", "))
errors = append(errors, compiler.NewError(context, message))
}
// repeated string required = 1;
v1 := compiler.MapValueForKey(m, "required")
if v1 != nil {
v, ok := v1.([]interface{})
if ok {
x.Required = compiler.ConvertInterfaceArrayToStringArray(v)
} else {
message := fmt.Sprintf("has unexpected value for required: %+v (%T)", v1, v1)
errors = append(errors, compiler.NewError(context, message))
}
}
}
return x, compiler.NewErrorGroupOrNil(errors)
} | go | {
"resource": ""
} |
q18585 | NewAny | train | func NewAny(in interface{}, context *compiler.Context) (*Any, error) {
errors := make([]error, 0)
x := &Any{}
bytes, _ := yaml.Marshal(in)
x.Yaml = string(bytes)
return x, compiler.NewErrorGroupOrNil(errors)
} | go | {
"resource": ""
} |
q18586 | NewAuth | train | func NewAuth(in interface{}, context *compiler.Context) (*Auth, error) {
errors := make([]error, 0)
x := &Auth{}
m, ok := compiler.UnpackMap(in)
if !ok {
message := fmt.Sprintf("has unexpected value: %+v (%T)", in, in)
errors = append(errors, compiler.NewError(context, message))
} else {
allowedKeys := []string{"oauth2"}
var allowedPatterns []*regexp.Regexp
invalidKeys := compiler.InvalidKeysInMap(m, allowedKeys, allowedPatterns)
if len(invalidKeys) > 0 {
message := fmt.Sprintf("has invalid %s: %+v", compiler.PluralProperties(len(invalidKeys)), strings.Join(invalidKeys, ", "))
errors = append(errors, compiler.NewError(context, message))
}
// Oauth2 oauth2 = 1;
v1 := compiler.MapValueForKey(m, "oauth2")
if v1 != nil {
var err error
x.Oauth2, err = NewOauth2(v1, compiler.NewContext("oauth2", context))
if err != nil {
errors = append(errors, err)
}
}
}
return x, compiler.NewErrorGroupOrNil(errors)
} | go | {
"resource": ""
} |
q18587 | NewMediaUpload | train | func NewMediaUpload(in interface{}, context *compiler.Context) (*MediaUpload, error) {
errors := make([]error, 0)
x := &MediaUpload{}
m, ok := compiler.UnpackMap(in)
if !ok {
message := fmt.Sprintf("has unexpected value: %+v (%T)", in, in)
errors = append(errors, compiler.NewError(context, message))
} else {
allowedKeys := []string{"accept", "maxSize", "protocols", "supportsSubscription"}
var allowedPatterns []*regexp.Regexp
invalidKeys := compiler.InvalidKeysInMap(m, allowedKeys, allowedPatterns)
if len(invalidKeys) > 0 {
message := fmt.Sprintf("has invalid %s: %+v", compiler.PluralProperties(len(invalidKeys)), strings.Join(invalidKeys, ", "))
errors = append(errors, compiler.NewError(context, message))
}
// repeated string accept = 1;
v1 := compiler.MapValueForKey(m, "accept")
if v1 != nil {
v, ok := v1.([]interface{})
if ok {
x.Accept = compiler.ConvertInterfaceArrayToStringArray(v)
} else {
message := fmt.Sprintf("has unexpected value for accept: %+v (%T)", v1, v1)
errors = append(errors, compiler.NewError(context, message))
}
}
// string max_size = 2;
v2 := compiler.MapValueForKey(m, "maxSize")
if v2 != nil {
x.MaxSize, ok = v2.(string)
if !ok {
message := fmt.Sprintf("has unexpected value for maxSize: %+v (%T)", v2, v2)
errors = append(errors, compiler.NewError(context, message))
}
}
// Protocols protocols = 3;
v3 := compiler.MapValueForKey(m, "protocols")
if v3 != nil {
var err error
x.Protocols, err = NewProtocols(v3, compiler.NewContext("protocols", context))
if err != nil {
errors = append(errors, err)
}
}
// bool supports_subscription = 4;
v4 := compiler.MapValueForKey(m, "supportsSubscription")
if v4 != nil {
x.SupportsSubscription, ok = v4.(bool)
if !ok {
message := fmt.Sprintf("has unexpected value for supportsSubscription: %+v (%T)", v4, v4)
errors = append(errors, compiler.NewError(context, message))
}
}
}
return x, compiler.NewErrorGroupOrNil(errors)
} | go | {
"resource": ""
} |
q18588 | NewMethods | train | func NewMethods(in interface{}, context *compiler.Context) (*Methods, error) {
errors := make([]error, 0)
x := &Methods{}
m, ok := compiler.UnpackMap(in)
if !ok {
message := fmt.Sprintf("has unexpected value: %+v (%T)", in, in)
errors = append(errors, compiler.NewError(context, message))
} else {
// repeated NamedMethod additional_properties = 1;
// MAP: Method
x.AdditionalProperties = make([]*NamedMethod, 0)
for _, item := range m {
k, ok := compiler.StringValue(item.Key)
if ok {
v := item.Value
pair := &NamedMethod{}
pair.Name = k
var err error
pair.Value, err = NewMethod(v, compiler.NewContext(k, context))
if err != nil {
errors = append(errors, err)
}
x.AdditionalProperties = append(x.AdditionalProperties, pair)
}
}
}
return x, compiler.NewErrorGroupOrNil(errors)
} | go | {
"resource": ""
} |
q18589 | NewProtocols | train | func NewProtocols(in interface{}, context *compiler.Context) (*Protocols, error) {
errors := make([]error, 0)
x := &Protocols{}
m, ok := compiler.UnpackMap(in)
if !ok {
message := fmt.Sprintf("has unexpected value: %+v (%T)", in, in)
errors = append(errors, compiler.NewError(context, message))
} else {
allowedKeys := []string{"resumable", "simple"}
var allowedPatterns []*regexp.Regexp
invalidKeys := compiler.InvalidKeysInMap(m, allowedKeys, allowedPatterns)
if len(invalidKeys) > 0 {
message := fmt.Sprintf("has invalid %s: %+v", compiler.PluralProperties(len(invalidKeys)), strings.Join(invalidKeys, ", "))
errors = append(errors, compiler.NewError(context, message))
}
// Simple simple = 1;
v1 := compiler.MapValueForKey(m, "simple")
if v1 != nil {
var err error
x.Simple, err = NewSimple(v1, compiler.NewContext("simple", context))
if err != nil {
errors = append(errors, err)
}
}
// Resumable resumable = 2;
v2 := compiler.MapValueForKey(m, "resumable")
if v2 != nil {
var err error
x.Resumable, err = NewResumable(v2, compiler.NewContext("resumable", context))
if err != nil {
errors = append(errors, err)
}
}
}
return x, compiler.NewErrorGroupOrNil(errors)
} | go | {
"resource": ""
} |
q18590 | NewResource | train | func NewResource(in interface{}, context *compiler.Context) (*Resource, error) {
errors := make([]error, 0)
x := &Resource{}
m, ok := compiler.UnpackMap(in)
if !ok {
message := fmt.Sprintf("has unexpected value: %+v (%T)", in, in)
errors = append(errors, compiler.NewError(context, message))
} else {
allowedKeys := []string{"methods", "resources"}
var allowedPatterns []*regexp.Regexp
invalidKeys := compiler.InvalidKeysInMap(m, allowedKeys, allowedPatterns)
if len(invalidKeys) > 0 {
message := fmt.Sprintf("has invalid %s: %+v", compiler.PluralProperties(len(invalidKeys)), strings.Join(invalidKeys, ", "))
errors = append(errors, compiler.NewError(context, message))
}
// Methods methods = 1;
v1 := compiler.MapValueForKey(m, "methods")
if v1 != nil {
var err error
x.Methods, err = NewMethods(v1, compiler.NewContext("methods", context))
if err != nil {
errors = append(errors, err)
}
}
// Resources resources = 2;
v2 := compiler.MapValueForKey(m, "resources")
if v2 != nil {
var err error
x.Resources, err = NewResources(v2, compiler.NewContext("resources", context))
if err != nil {
errors = append(errors, err)
}
}
}
return x, compiler.NewErrorGroupOrNil(errors)
} | go | {
"resource": ""
} |
q18591 | NewResources | train | func NewResources(in interface{}, context *compiler.Context) (*Resources, error) {
errors := make([]error, 0)
x := &Resources{}
m, ok := compiler.UnpackMap(in)
if !ok {
message := fmt.Sprintf("has unexpected value: %+v (%T)", in, in)
errors = append(errors, compiler.NewError(context, message))
} else {
// repeated NamedResource additional_properties = 1;
// MAP: Resource
x.AdditionalProperties = make([]*NamedResource, 0)
for _, item := range m {
k, ok := compiler.StringValue(item.Key)
if ok {
v := item.Value
pair := &NamedResource{}
pair.Name = k
var err error
pair.Value, err = NewResource(v, compiler.NewContext(k, context))
if err != nil {
errors = append(errors, err)
}
x.AdditionalProperties = append(x.AdditionalProperties, pair)
}
}
}
return x, compiler.NewErrorGroupOrNil(errors)
} | go | {
"resource": ""
} |
q18592 | NewScopes | train | func NewScopes(in interface{}, context *compiler.Context) (*Scopes, error) {
errors := make([]error, 0)
x := &Scopes{}
m, ok := compiler.UnpackMap(in)
if !ok {
message := fmt.Sprintf("has unexpected value: %+v (%T)", in, in)
errors = append(errors, compiler.NewError(context, message))
} else {
// repeated NamedScope additional_properties = 1;
// MAP: Scope
x.AdditionalProperties = make([]*NamedScope, 0)
for _, item := range m {
k, ok := compiler.StringValue(item.Key)
if ok {
v := item.Value
pair := &NamedScope{}
pair.Name = k
var err error
pair.Value, err = NewScope(v, compiler.NewContext(k, context))
if err != nil {
errors = append(errors, err)
}
x.AdditionalProperties = append(x.AdditionalProperties, pair)
}
}
}
return x, compiler.NewErrorGroupOrNil(errors)
} | go | {
"resource": ""
} |
q18593 | NewSimple | train | func NewSimple(in interface{}, context *compiler.Context) (*Simple, error) {
errors := make([]error, 0)
x := &Simple{}
m, ok := compiler.UnpackMap(in)
if !ok {
message := fmt.Sprintf("has unexpected value: %+v (%T)", in, in)
errors = append(errors, compiler.NewError(context, message))
} else {
allowedKeys := []string{"multipart", "path"}
var allowedPatterns []*regexp.Regexp
invalidKeys := compiler.InvalidKeysInMap(m, allowedKeys, allowedPatterns)
if len(invalidKeys) > 0 {
message := fmt.Sprintf("has invalid %s: %+v", compiler.PluralProperties(len(invalidKeys)), strings.Join(invalidKeys, ", "))
errors = append(errors, compiler.NewError(context, message))
}
// bool multipart = 1;
v1 := compiler.MapValueForKey(m, "multipart")
if v1 != nil {
x.Multipart, ok = v1.(bool)
if !ok {
message := fmt.Sprintf("has unexpected value for multipart: %+v (%T)", v1, v1)
errors = append(errors, compiler.NewError(context, message))
}
}
// string path = 2;
v2 := compiler.MapValueForKey(m, "path")
if v2 != nil {
x.Path, ok = v2.(string)
if !ok {
message := fmt.Sprintf("has unexpected value for path: %+v (%T)", v2, v2)
errors = append(errors, compiler.NewError(context, message))
}
}
}
return x, compiler.NewErrorGroupOrNil(errors)
} | go | {
"resource": ""
} |
q18594 | NewStringArray | train | func NewStringArray(in interface{}, context *compiler.Context) (*StringArray, error) {
errors := make([]error, 0)
x := &StringArray{}
a, ok := in.([]interface{})
if !ok {
message := fmt.Sprintf("has unexpected value for StringArray: %+v (%T)", in, in)
errors = append(errors, compiler.NewError(context, message))
} else {
x.Value = make([]string, 0)
for _, s := range a {
x.Value = append(x.Value, s.(string))
}
}
return x, compiler.NewErrorGroupOrNil(errors)
} | go | {
"resource": ""
} |
q18595 | ResolveReferences | train | func (m *MediaUpload) ResolveReferences(root string) (interface{}, error) {
errors := make([]error, 0)
if m.Protocols != nil {
_, err := m.Protocols.ResolveReferences(root)
if err != nil {
errors = append(errors, err)
}
}
return nil, compiler.NewErrorGroupOrNil(errors)
} | go | {
"resource": ""
} |
q18596 | ResolveReferences | train | func (m *Method) ResolveReferences(root string) (interface{}, error) {
errors := make([]error, 0)
if m.Parameters != nil {
_, err := m.Parameters.ResolveReferences(root)
if err != nil {
errors = append(errors, err)
}
}
if m.Request != nil {
_, err := m.Request.ResolveReferences(root)
if err != nil {
errors = append(errors, err)
}
}
if m.Response != nil {
_, err := m.Response.ResolveReferences(root)
if err != nil {
errors = append(errors, err)
}
}
if m.MediaUpload != nil {
_, err := m.MediaUpload.ResolveReferences(root)
if err != nil {
errors = append(errors, err)
}
}
return nil, compiler.NewErrorGroupOrNil(errors)
} | go | {
"resource": ""
} |
q18597 | ResolveReferences | train | func (m *Methods) ResolveReferences(root string) (interface{}, error) {
errors := make([]error, 0)
for _, item := range m.AdditionalProperties {
if item != nil {
_, err := item.ResolveReferences(root)
if err != nil {
errors = append(errors, err)
}
}
}
return nil, compiler.NewErrorGroupOrNil(errors)
} | go | {
"resource": ""
} |
q18598 | ResolveReferences | train | func (m *NamedMethod) ResolveReferences(root string) (interface{}, error) {
errors := make([]error, 0)
if m.Value != nil {
_, err := m.Value.ResolveReferences(root)
if err != nil {
errors = append(errors, err)
}
}
return nil, compiler.NewErrorGroupOrNil(errors)
} | go | {
"resource": ""
} |
q18599 | ResolveReferences | train | func (m *Protocols) ResolveReferences(root string) (interface{}, error) {
errors := make([]error, 0)
if m.Simple != nil {
_, err := m.Simple.ResolveReferences(root)
if err != nil {
errors = append(errors, err)
}
}
if m.Resumable != nil {
_, err := m.Resumable.ResolveReferences(root)
if err != nil {
errors = append(errors, err)
}
}
return nil, compiler.NewErrorGroupOrNil(errors)
} | go | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.