// generate a simple report of an OpenAPI document's contents
506232
func printDocumentV2(code *printer.Code, document *openapiv2.Document) {
	code.Print("Swagger: %+v", document.Swagger)
	code.Print("Host: %+v", document.Host)
	code.Print("BasePath: %+v", document.BasePath)
	if document.Info != nil {
		code.Print("Info:")
		code.Indent()
		if document.Info.Title != "" {
			code.Print("Title: %s", document.Info.Title)
		}
		if document.Info.Description != "" {
			code.Print("Description: %s", document.Info.Description)
		}
		if document.Info.Version != "" {
			code.Print("Version: %s", document.Info.Version)
		}
		code.Outdent()
	}
	code.Print("Paths:")
	code.Indent()
	for _, pair := range document.Paths.Path {
		v := pair.Value
		if v.Get != nil {
			code.Print("GET %+v", pair.Name)
		}
		if v.Post != nil {
			code.Print("POST %+v", pair.Name)
		}
	}
	code.Outdent()
}
895294
func (p *Plugin) Generate(r *plugin_go.CodeGeneratorRequest) (*plugin_go.CodeGeneratorResponse, error) {
	options, err := ParseOptions(r)
	if err != nil {
		return nil, err
	}

	result := excludeUnwantedProtos(protokit.ParseCodeGenRequest(r), options.ExcludePatterns)
	template := NewTemplate(result)

	customTemplate := ""

	if options.TemplateFile != "" {
		data, err := ioutil.ReadFile(options.TemplateFile)
		if err != nil {
			return nil, err
		}

		customTemplate = string(data)
	}

	output, err := RenderTemplate(options.Type, template, customTemplate)
	if err != nil {
		return nil, err
	}

	resp := new(plugin_go.CodeGeneratorResponse)
	resp.File = append(resp.File, &plugin_go.CodeGeneratorResponse_File{
		Name:    proto.String(options.OutputFile),
		Content: proto.String(string(output)),
	})

	return resp, nil
}
1128216
func generateImports(ctx *context, w io.Writer) {
	fmt.Fprintf(w, "import api \"%s\"\n", govppApiImportPath)
	fmt.Fprintf(w, "import struc \"%s\"\n", "github.com/lunixbochs/struc")
	fmt.Fprintf(w, "import bytes \"%s\"\n", "bytes")
	fmt.Fprintln(w)

	fmt.Fprintf(w, "// Reference imports to suppress errors if they are not otherwise used.\n")
	fmt.Fprintf(w, "var _ = api.RegisterMessage\n")
	fmt.Fprintf(w, "var _ = struc.Pack\n")
	fmt.Fprintf(w, "var _ = bytes.NewBuffer\n")
	fmt.Fprintln(w)

	/*fmt.Fprintln(w, "// This is a compile-time assertion to ensure that this generated file")
	fmt.Fprintln(w, "// is compatible with the GoVPP api package it is being compiled against.")
	fmt.Fprintln(w, "// A compilation error at this line likely means your copy of the")
	fmt.Fprintln(w, "// GoVPP api package needs to be updated.")
	fmt.Fprintln(w, "const _ = api.GoVppAPIPackageIsVersion1 // please upgrade the GoVPP api package")
	fmt.Fprintln(w)*/
}
814491
func generateComment(ctx *context, w io.Writer, goName string, vppName string, objKind string) {
	if objKind == "service" {
		fmt.Fprintf(w, "// %s represents VPP binary API services:\n", goName)
	} else {
		fmt.Fprintf(w, "// %s represents VPP binary API %s '%s':\n", goName, objKind, vppName)
	}

	if !ctx.includeComments {
		return
	}

	var isNotSpace = func(r rune) bool {
		return !unicode.IsSpace(r)
	}

	// print out the source of the generated object
	mapType := false
	objFound := false
	objTitle := fmt.Sprintf(`"%s",`, vppName)
	switch objKind {
	case "alias", "service":
		objTitle = fmt.Sprintf(`"%s": {`, vppName)
		mapType = true
	}

	inputBuff := bytes.NewBuffer(ctx.inputData)
	inputLine := 0

	var trimIndent string
	var indent int
	for {
		line, err := inputBuff.ReadString('\n')
		if err != nil {
			break
		}
		inputLine++

		noSpaceAt := strings.IndexFunc(line, isNotSpace)
		if !objFound {
			indent = strings.Index(line, objTitle)
			if indent == -1 {
				continue
			}
			trimIndent = line[:indent]
			// If no other non-whitespace character then we are at the message header.
			if trimmed := strings.TrimSpace(line); trimmed == objTitle {
				objFound = true
				fmt.Fprintln(w, "//")
			}
		} else if noSpaceAt < indent {
			break // end of the definition in JSON for array types
		} else if objFound && mapType && noSpaceAt <= indent {
			fmt.Fprintf(w, "//\t%s", strings.TrimPrefix(line, trimIndent))
			break // end of the definition in JSON for map types (aliases, services)
		}
		fmt.Fprintf(w, "//\t%s", strings.TrimPrefix(line, trimIndent))
	}

	fmt.Fprintln(w, "//")
}
765735
func main() {
	var (
		settings         []Option
		settingsTemplate = createTemplate("templates/query_params.go.tmpl")
		filepath         = "../../search/query_params.go"
	)

	for _, opt := range options {
		if isSearch(opt.Kind) {
			settings = append(settings, opt)
		}
	}

	generateFile(settingsTemplate, settings, filepath)
}
673297
func GenerateDocs(apiDef *raml.APIDefinition, format, output string) error {
	switch format {
	case formatMarkdown:
		md := &markdownDocs{
			api:    apiDef,
			output: output,
		}
		return md.generate()
	default:
		return fmt.Errorf("unknown format '%s'", format)
	}
}
1068357
func generateRandomDocument() ([]byte, error) {
	c := &contacts{}
	c.Name = randomdata.FullName(randomdata.RandomGender)
	c.Email = randomdata.Email()
	c.Age = randomdata.Number(20, 50)
	c.Address = randomdata.Address()
	c.City = randomdata.City()
	c.State = randomdata.State(randomdata.Large)
	c.Country = randomdata.Country(randomdata.FullCountry)

	return json.Marshal(c)
}
61046
func NewDocumentStatistics(source string, document *openapi.Document) *DocumentStatistics {
	s := &DocumentStatistics{}
	s.Operations = make(map[string]int, 0)
	s.ParameterTypes = make(map[string]int, 0)
	s.ResultTypes = make(map[string]int, 0)
	s.DefinitionFieldTypes = make(map[string]int, 0)
	s.DefinitionArrayTypes = make(map[string]int, 0)
	s.DefinitionPrimitiveTypes = make(map[string]int, 0)
	s.AnonymousOperations = make([]string, 0)
	s.AnonymousObjects = make([]string, 0)
	s.analyzeDocument(source, document)
	return s
}
139792
func yaml_parser_parse_document_content(parser *yaml_parser_t, event *yaml_event_t) bool {
	token := peek_token(parser)
	if token == nil {
		return false
	}
	if token.typ == yaml_VERSION_DIRECTIVE_TOKEN ||
		token.typ == yaml_TAG_DIRECTIVE_TOKEN ||
		token.typ == yaml_DOCUMENT_START_TOKEN ||
		token.typ == yaml_DOCUMENT_END_TOKEN ||
		token.typ == yaml_STREAM_END_TOKEN {
		parser.state = parser.states[len(parser.states)-1]
		parser.states = parser.states[:len(parser.states)-1]
		return yaml_parser_process_empty_scalar(parser, event,
			token.start_mark)
	}
	return yaml_parser_parse_node(parser, event, true, false)
}
1299011
func (g *Generator) GenerateAllFiles() {
	// Initialize the plugins
	for _, p := range plugins {
		p.Init(g)
	}
	// Generate the output. The generator runs for every file, even the files
	// that we don't generate output for, so that we can collate the full list
	// of exported symbols to support public imports.
	genFileMap := make(map[*FileDescriptor]bool, len(g.genFiles))
	for _, file := range g.genFiles {
		genFileMap[file] = true
	}
	for _, file := range g.allFiles {
		g.Reset()
		g.annotations = nil
		g.writeOutput = genFileMap[file]
		g.generate(file)
		if !g.writeOutput {
			continue
		}
		fname := file.goFileName(g.pathType)
		g.Response.File = append(g.Response.File, &plugin.CodeGeneratorResponse_File{
			Name:    proto.String(fname),
			Content: proto.String(g.String()),
		})
		if g.annotateCode {
			// Store the generated code annotations in text, as the protoc plugin protocol requires that
			// strings contain valid UTF-8.
			g.Response.File = append(g.Response.File, &plugin.CodeGeneratorResponse_File{
				Name:    proto.String(file.goFileName(g.pathType) + ".meta"),
				Content: proto.String(proto.CompactTextString(&descriptor.GeneratedCodeInfo{Annotation: g.annotations})),
			})
		}
	}
}
175094
func Generate(w io.Writer, rpt *Report, obj plugin.ObjTool) error {
	o := rpt.options

	switch o.OutputFormat {
	case Dot:
		return printDOT(w, rpt)
	case Tree:
		return printTree(w, rpt)
	case Text:
		return printText(w, rpt)
	case JSON:
		return printJSON(w, rpt)
	case Raw:
		fmt.Fprint(w, rpt.prof.String())
		return nil
	case Tags:
		return printTags(w, rpt)
	case Proto:
		return rpt.prof.Write(w)
	case Dis:
		return printAssembly(w, rpt, obj)
	case List:
		return printSource(w, rpt)
	case WebList:
		return printWebSource(w, rpt, obj)
	case Callgrind:
		return printCallgrind(w, rpt)
	}
	return fmt.Errorf("unexpected output format")
}
1307748
func ConvertDoc(r io.Reader) (string, map[string]string, error) {
	f, err := NewLocalFile(r, "/tmp", "sajari-convert-")
	if err != nil {
		return "", nil, fmt.Errorf("error creating local file: %v", err)
	}
	defer f.Done()

	// Meta data
	mc := make(chan map[string]string, 1)
	go func() {
		meta := make(map[string]string)
		metaStr, err := exec.Command("wvSummary", f.Name()).Output()
		if err != nil {
			// TODO: Remove this.
			log.Println("wvSummary:", err)
		}

		// Parse meta output
		for _, line := range strings.Split(string(metaStr), "\n") {
			if parts := strings.SplitN(line, "=", 2); len(parts) > 1 {
				meta[strings.TrimSpace(parts[0])] = strings.TrimSpace(parts[1])
			}
		}

		// Convert parsed meta
		if tmp, ok := meta["Last Modified"]; ok {
			if t, err := time.Parse(time.RFC3339, tmp); err == nil {
				meta["ModifiedDate"] = fmt.Sprintf("%d", t.Unix())
			}
		}
		if tmp, ok := meta["Created"]; ok {
			if t, err := time.Parse(time.RFC3339, tmp); err == nil {
				meta["CreatedDate"] = fmt.Sprintf("%d", t.Unix())
			}
		}

		mc <- meta
	}()

	// Document body
	bc := make(chan string, 1)
	go func() {

		// Save output to a file
		outputFile, err := ioutil.TempFile("/tmp", "sajari-convert-")
		if err != nil {
			// TODO: Remove this.
			log.Println("TempFile Out:", err)
			return
		}
		defer os.Remove(outputFile.Name())

		err = exec.Command("wvText", f.Name(), outputFile.Name()).Run()
		if err != nil {
			// TODO: Remove this.
			log.Println("wvText:", err)
		}

		var buf bytes.Buffer
		_, err = buf.ReadFrom(outputFile)
		if err != nil {
			// TODO: Remove this.
			log.Println("wvText:", err)
		}

		bc <- buf.String()
	}()

	// TODO: Should errors in either of the above Goroutines stop things from progressing?
	body := <-bc
	meta := <-mc

	// TODO: Check for errors instead of len(body) == 0?
	if len(body) == 0 {
		f.Seek(0, 0)
		return ConvertDocx(f)
	}
	return body, meta, nil
}
88374
func main() {
	env, err := plugins.NewEnvironment()
	env.RespondAndExitIfError(err)
	code := &printer.Code{}
	for _, model := range env.Request.Models {
		log.Printf("model %s", model.TypeUrl)
		switch model.TypeUrl {
		case "openapi.v2.Document":
			documentv2 := &openapiv2.Document{}
			err = proto.Unmarshal(model.Value, documentv2)
			if err == nil {
				printDocumentV2(code, documentv2)
			}
		case "openapi.v3.Document":
			documentv3 := &openapiv3.Document{}
			err = proto.Unmarshal(model.Value, documentv3)
			if err == nil {
				printDocumentV3(code, documentv3)
			}
		}
	}
	file := &plugins.File{
		Name: "summary.txt",
		Data: []byte(code.String()),
	}
	env.Response.Files = append(env.Response.Files, file)
	env.RespondAndExit()
}
870604
func (parser *Parser) ParseGeneralAPIInfo(mainAPIFile string) error {
	fileSet := token.NewFileSet()
	fileTree, err := goparser.ParseFile(fileSet, mainAPIFile, nil, goparser.ParseComments)
	if err != nil {
		return errors.Wrap(err, "cannot parse soure files")
	}

	parser.swagger.Swagger = "2.0"
	securityMap := map[string]*spec.SecurityScheme{}

	// templated defaults
	parser.swagger.Info.Version = "{{.Version}}"
	parser.swagger.Info.Title = "{{.Title}}"
	parser.swagger.Info.Description = "{{.Description}}"
	parser.swagger.Host = "{{.Host}}"
	parser.swagger.BasePath = "{{.BasePath}}"

	if fileTree.Comments != nil {
		for _, comment := range fileTree.Comments {
			comments := strings.Split(comment.Text(), "\n")
			previousAttribute := ""
			for _, commentLine := range comments {
				attribute := strings.ToLower(strings.Split(commentLine, " ")[0])
				multilineBlock := false
				if previousAttribute == attribute {
					multilineBlock = true
				}
				switch attribute {
				case "@version":
					parser.swagger.Info.Version = strings.TrimSpace(commentLine[len(attribute):])
				case "@title":
					parser.swagger.Info.Title = strings.TrimSpace(commentLine[len(attribute):])
				case "@description":
					if parser.swagger.Info.Description == "{{.Description}}" {
						parser.swagger.Info.Description = strings.TrimSpace(commentLine[len(attribute):])
					} else if multilineBlock {
						parser.swagger.Info.Description += "\n" + strings.TrimSpace(commentLine[len(attribute):])
					}
				case "@termsofservice":
					parser.swagger.Info.TermsOfService = strings.TrimSpace(commentLine[len(attribute):])
				case "@contact.name":
					parser.swagger.Info.Contact.Name = strings.TrimSpace(commentLine[len(attribute):])
				case "@contact.email":
					parser.swagger.Info.Contact.Email = strings.TrimSpace(commentLine[len(attribute):])
				case "@contact.url":
					parser.swagger.Info.Contact.URL = strings.TrimSpace(commentLine[len(attribute):])
				case "@license.name":
					parser.swagger.Info.License.Name = strings.TrimSpace(commentLine[len(attribute):])
				case "@license.url":
					parser.swagger.Info.License.URL = strings.TrimSpace(commentLine[len(attribute):])
				case "@host":
					parser.swagger.Host = strings.TrimSpace(commentLine[len(attribute):])
				case "@basepath":
					parser.swagger.BasePath = strings.TrimSpace(commentLine[len(attribute):])
				case "@schemes":
					parser.swagger.Schemes = getSchemes(commentLine)
				case "@tag.name":
					commentInfo := strings.TrimSpace(commentLine[len(attribute):])
					parser.swagger.Tags = append(parser.swagger.Tags, spec.Tag{
						TagProps: spec.TagProps{
							Name: strings.TrimSpace(commentInfo),
						},
					})
				case "@tag.description":
					commentInfo := strings.TrimSpace(commentLine[len(attribute):])
					tag := parser.swagger.Tags[len(parser.swagger.Tags)-1]
					tag.TagProps.Description = commentInfo
					replaceLastTag(parser.swagger.Tags, tag)
				case "@tag.docs.url":
					commentInfo := strings.TrimSpace(commentLine[len(attribute):])
					tag := parser.swagger.Tags[len(parser.swagger.Tags)-1]
					tag.TagProps.ExternalDocs = &spec.ExternalDocumentation{
						URL: commentInfo,
					}
					replaceLastTag(parser.swagger.Tags, tag)

				case "@tag.docs.description":
					commentInfo := strings.TrimSpace(commentLine[len(attribute):])
					tag := parser.swagger.Tags[len(parser.swagger.Tags)-1]
					if tag.TagProps.ExternalDocs == nil {
						return errors.New("@tag.docs.description needs to come after a @tags.docs.url")
					}
					tag.TagProps.ExternalDocs.Description = commentInfo
					replaceLastTag(parser.swagger.Tags, tag)
				}
				previousAttribute = attribute
			}

			for i := 0; i < len(comments); i++ {
				attribute := strings.ToLower(strings.Split(comments[i], " ")[0])
				switch attribute {
				case "@securitydefinitions.basic":
					securityMap[strings.TrimSpace(comments[i][len(attribute):])] = spec.BasicAuth()
				case "@securitydefinitions.apikey":
					attrMap := map[string]string{}
					for _, v := range comments[i+1:] {
						securityAttr := strings.ToLower(strings.Split(v, " ")[0])
						if securityAttr == "@in" || securityAttr == "@name" {
							attrMap[securityAttr] = strings.TrimSpace(v[len(securityAttr):])
						}
						// next securityDefinitions
						if strings.Index(securityAttr, "@securitydefinitions.") == 0 {
							break
						}
					}
					if len(attrMap) != 2 {
						return errors.New("@securitydefinitions.apikey is @name and @in required")
					}
					securityMap[strings.TrimSpace(comments[i][len(attribute):])] = spec.APIKeyAuth(attrMap["@name"], attrMap["@in"])
				case "@securitydefinitions.oauth2.application":
					attrMap := map[string]string{}
					scopes := map[string]string{}
					for _, v := range comments[i+1:] {
						securityAttr := strings.ToLower(strings.Split(v, " ")[0])
						if securityAttr == "@tokenurl" {
							attrMap[securityAttr] = strings.TrimSpace(v[len(securityAttr):])
						} else {
							isExists, err := isExistsScope(securityAttr)
							if err != nil {
								return err
							}
							if isExists {
								scopScheme, err := getScopeScheme(securityAttr)
								if err != nil {
									return err
								}
								scopes[scopScheme] = v[len(securityAttr):]
							}
						}
						// next securityDefinitions
						if strings.Index(securityAttr, "@securitydefinitions.") == 0 {
							break
						}
					}
					if len(attrMap) != 1 {
						return errors.New("@securitydefinitions.oauth2.application is @tokenUrl required")
					}
					securityScheme := spec.OAuth2Application(attrMap["@tokenurl"])
					for scope, description := range scopes {
						securityScheme.AddScope(scope, description)
					}
					securityMap[strings.TrimSpace(comments[i][len(attribute):])] = securityScheme
				case "@securitydefinitions.oauth2.implicit":
					attrMap := map[string]string{}
					scopes := map[string]string{}
					for _, v := range comments[i+1:] {
						securityAttr := strings.ToLower(strings.Split(v, " ")[0])
						if securityAttr == "@authorizationurl" {
							attrMap[securityAttr] = strings.TrimSpace(v[len(securityAttr):])
						} else {
							isExists, err := isExistsScope(securityAttr)
							if err != nil {
								return err
							}
							if isExists {
								scopScheme, err := getScopeScheme(securityAttr)
								if err != nil {
									return err
								}
								scopes[scopScheme] = v[len(securityAttr):]
							}
						}
						// next securityDefinitions
						if strings.Index(securityAttr, "@securitydefinitions.") == 0 {
							break
						}
					}
					if len(attrMap) != 1 {
						return errors.New("@securitydefinitions.oauth2.implicit is @authorizationUrl required")
					}
					securityScheme := spec.OAuth2Implicit(attrMap["@authorizationurl"])
					for scope, description := range scopes {
						securityScheme.AddScope(scope, description)
					}
					securityMap[strings.TrimSpace(comments[i][len(attribute):])] = securityScheme
				case "@securitydefinitions.oauth2.password":
					attrMap := map[string]string{}
					scopes := map[string]string{}
					for _, v := range comments[i+1:] {
						securityAttr := strings.ToLower(strings.Split(v, " ")[0])
						if securityAttr == "@tokenurl" {
							attrMap[securityAttr] = strings.TrimSpace(v[len(securityAttr):])
						} else {
							isExists, err := isExistsScope(securityAttr)
							if err != nil {
								return err
							}
							if isExists {
								scopScheme, err := getScopeScheme(securityAttr)
								if err != nil {
									return err
								}
								scopes[scopScheme] = v[len(securityAttr):]
							}
						}
						// next securityDefinitions
						if strings.Index(securityAttr, "@securitydefinitions.") == 0 {
							break
						}
					}
					if len(attrMap) != 1 {
						return errors.New("@securitydefinitions.oauth2.password is @tokenUrl required")
					}
					securityScheme := spec.OAuth2Password(attrMap["@tokenurl"])
					for scope, description := range scopes {
						securityScheme.AddScope(scope, description)
					}
					securityMap[strings.TrimSpace(comments[i][len(attribute):])] = securityScheme
				case "@securitydefinitions.oauth2.accesscode":
					attrMap := map[string]string{}
					scopes := map[string]string{}
					for _, v := range comments[i+1:] {
						securityAttr := strings.ToLower(strings.Split(v, " ")[0])
						if securityAttr == "@tokenurl" || securityAttr == "@authorizationurl" {
							attrMap[securityAttr] = strings.TrimSpace(v[len(securityAttr):])
						} else {
							isExists, err := isExistsScope(securityAttr)
							if err != nil {
								return err
							}
							if isExists {
								scopScheme, err := getScopeScheme(securityAttr)
								if err != nil {
									return err
								}
								scopes[scopScheme] = v[len(securityAttr):]
							}
						}
						// next securityDefinitions
						if strings.Index(securityAttr, "@securitydefinitions.") == 0 {
							break
						}
					}
					if len(attrMap) != 2 {
						return errors.New("@securitydefinitions.oauth2.accessCode is @tokenUrl and @authorizationUrl required")
					}
					securityScheme := spec.OAuth2AccessToken(attrMap["@authorizationurl"], attrMap["@tokenurl"])
					for scope, description := range scopes {
						securityScheme.AddScope(scope, description)
					}
					securityMap[strings.TrimSpace(comments[i][len(attribute):])] = securityScheme
				}
			}
		}
	}
	if len(securityMap) > 0 {
		parser.swagger.SecurityDefinitions = securityMap
	}

	return nil
}
280384
func ExtractAPI(v py.Object, m map[string][]string, key string) error {
	b := v.Base()
	dir, err := b.Dir()
	if err != nil {
		return err
	}
	defer dir.Decref()
	l, ok := dir.(*py.List)
	if !ok {
		return fmt.Errorf("Unexpected type: %v", dir.Type())
	}
	sl := l.Slice()
	for _, v2 := range sl {
		if str := fmt.Sprint(v2); strings.HasPrefix(str, "__") {
			continue
		}
		if key != "" {
			m[key] = append(m[key], fmt.Sprint(v2))
			continue
		}
		item, err := b.GetAttr(v2)
		if err != nil {
			return err
		}
		ty := item.Type()
		k := fmt.Sprint(v2)
		if k == "RegionSet" {
			k = "Selection"
		}
		if ty == py.TypeType {
			k = "sublime." + k
			m[k] = make([]string, 0)
			if err := ExtractAPI(item, m, k); err != nil {
				return err
			}
		} else {
			m["sublime"] = append(m["sublime"], fmt.Sprint(v2))
		}
		item.Decref()
	}
	return nil
}
905967
func readOpenapi(handler *genericapiserver.APIServerHandler) string {
	req, err := http.NewRequest("GET", "/swagger.json", nil)
	if err != nil {
		panic(fmt.Errorf("Could not create openapi request %v", err))
	}
	resp := &BufferedResponse{}
	handler.ServeHTTP(resp, req)
	return resp.String()
}
977758
func (b *OpenAPI3Builder) build(document *openapiv3.Document) (err error) {
	// Collect service type descriptions from Components/Schemas.
	if document.Components != nil && document.Components.Schemas != nil {
		for _, pair := range document.Components.Schemas.AdditionalProperties {
			t, err := b.buildTypeFromSchemaOrReference(pair.Name, pair.Value)
			if err != nil {
				return err
			}
			if t != nil {
				b.model.addType(t)
			}
		}
	}
	// Collect service method descriptions from each PathItem.
	if document.Paths != nil {
		for _, pair := range document.Paths.Path {
			b.buildMethodFromPathItem(pair.Name, pair.Value)
		}
	}
	return err
}