// generate Go client lib file
518121
func (gc *Client) generateClientFile(dir string) error {
	fileName := filepath.Join(dir, "/client_"+strings.ToLower(gc.Name)+".go")
	return commons.GenerateFile(gc, "./templates/golang/client_go.tmpl", "client_go", fileName, true)
}
72674
func (gr *goResource) generateAPIImplementations(dir string) error {
	// generate the main API impl file, which only contains struct
	mainCtx := map[string]interface{}{
		"PackageName": gr.PackageName,
		"Name":        gr.Name,
		"Endpoint":    gr.Endpoint,
	}

	mainFile := filepath.Join(dir, strings.ToLower(gr.Name)+"_api")
	if err := commons.GenerateFile(mainCtx, "./templates/golang/server_resource_api_main_go.tmpl",
		"server_resource_api_main_go", mainFile+".go", false); err != nil {
		return err
	}

	// generate per methods file
	for _, sm := range gr.Methods {
		ctx := map[string]interface{}{
			"Method":      sm,
			"APIName":     gr.Name,
			"PackageName": gr.PackageName,
		}
		filename := mainFile + "_" + sm.MethodName + ".go"
		if err := commons.GenerateFile(ctx, "./templates/golang/server_resource_api_impl_go.tmpl",
			"server_resource_api_impl_go", filename, false); err != nil {
			return err
		}
	}
	return nil
}
79666
func (g *Generator) generateImports() {
	imports := make(map[GoImportPath]GoPackageName)
	for i, s := range g.file.Dependency {
		fd := g.fileByName(s)
		importPath := fd.importPath
		// Do not import our own package.
		if importPath == g.file.importPath {
			continue
		}
		// Do not import weak imports.
		if g.weak(int32(i)) {
			continue
		}
		// Do not import a package twice.
		if _, ok := imports[importPath]; ok {
			continue
		}
		// We need to import all the dependencies, even if we don't reference them,
		// because other code and tools depend on having the full transitive closure
		// of protocol buffer types in the binary.
		packageName := g.GoPackageName(importPath)
		if _, ok := g.usedPackages[importPath]; !ok {
			packageName = "_"
		}
		imports[importPath] = packageName
	}
	for importPath := range g.addedImports {
		imports[importPath] = g.GoPackageName(importPath)
	}
	// We almost always need a proto import.  Rather than computing when we
	// do, which is tricky when there's a plugin, just import it and
	// reference it later. The same argument applies to the fmt and math packages.
	g.P("import (")
	g.P(g.Pkg["fmt"] + ` "fmt"`)
	g.P(g.Pkg["math"] + ` "math"`)
	g.P(g.Pkg["proto"]+" ", GoImportPath(g.ImportPrefix)+"github.com/golang/protobuf/proto")
	for importPath, packageName := range imports {
		g.P(packageName, " ", GoImportPath(g.ImportPrefix)+importPath)
	}
	g.P(")")
	g.P()
	// TODO: may need to worry about uniqueness across plugins
	for _, p := range plugins {
		p.GenerateImports(g.file)
		g.P()
	}
	g.P("// Reference imports to suppress errors if they are not otherwise used.")
	g.P("var _ = ", g.Pkg["proto"], ".Marshal")
	g.P("var _ = ", g.Pkg["fmt"], ".Errorf")
	g.P("var _ = ", g.Pkg["math"], ".Inf")
	g.P()
}
89179
func (g *grpc) generateService(file *generator.FileDescriptor, service *pb.ServiceDescriptorProto, index int) {
	path := fmt.Sprintf("6,%d", index) // 6 means service.

	origServName := service.GetName()
	fullServName := origServName
	if pkg := file.GetPackage(); pkg != "" {
		fullServName = pkg + "." + fullServName
	}
	servName := generator.CamelCase(origServName)
	deprecated := service.GetOptions().GetDeprecated()

	g.P()
	g.P(fmt.Sprintf(`// %sClient is the client API for %s service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.`, servName, servName))

	// Client interface.
	if deprecated {
		g.P("//")
		g.P(deprecationComment)
	}
	g.P("type ", servName, "Client interface {")
	for i, method := range service.Method {
		g.gen.PrintComments(fmt.Sprintf("%s,2,%d", path, i)) // 2 means method in a service.
		g.P(g.generateClientSignature(servName, method))
	}
	g.P("}")
	g.P()

	// Client structure.
	g.P("type ", unexport(servName), "Client struct {")
	g.P("cc *", grpcPkg, ".ClientConn")
	g.P("}")
	g.P()

	// NewClient factory.
	if deprecated {
		g.P(deprecationComment)
	}
	g.P("func New", servName, "Client (cc *", grpcPkg, ".ClientConn) ", servName, "Client {")
	g.P("return &", unexport(servName), "Client{cc}")
	g.P("}")
	g.P()

	var methodIndex, streamIndex int
	serviceDescVar := "_" + servName + "_serviceDesc"
	// Client method implementations.
	for _, method := range service.Method {
		var descExpr string
		if !method.GetServerStreaming() && !method.GetClientStreaming() {
			// Unary RPC method
			descExpr = fmt.Sprintf("&%s.Methods[%d]", serviceDescVar, methodIndex)
			methodIndex++
		} else {
			// Streaming RPC method
			descExpr = fmt.Sprintf("&%s.Streams[%d]", serviceDescVar, streamIndex)
			streamIndex++
		}
		g.generateClientMethod(servName, fullServName, serviceDescVar, method, descExpr)
	}

	// Server interface.
	serverType := servName + "Server"
	g.P("// ", serverType, " is the server API for ", servName, " service.")
	if deprecated {
		g.P("//")
		g.P(deprecationComment)
	}
	g.P("type ", serverType, " interface {")
	for i, method := range service.Method {
		g.gen.PrintComments(fmt.Sprintf("%s,2,%d", path, i)) // 2 means method in a service.
		g.P(g.generateServerSignature(servName, method))
	}
	g.P("}")
	g.P()

	// Server Unimplemented struct for forward compatability.
	if deprecated {
		g.P(deprecationComment)
	}
	g.generateUnimplementedServer(servName, service)

	// Server registration.
	if deprecated {
		g.P(deprecationComment)
	}
	g.P("func Register", servName, "Server(s *", grpcPkg, ".Server, srv ", serverType, ") {")
	g.P("s.RegisterService(&", serviceDescVar, `, srv)`)
	g.P("}")
	g.P()

	// Server handler implementations.
	var handlerNames []string
	for _, method := range service.Method {
		hname := g.generateServerMethod(servName, fullServName, method)
		handlerNames = append(handlerNames, hname)
	}

	// Service descriptor.
	g.P("var ", serviceDescVar, " = ", grpcPkg, ".ServiceDesc {")
	g.P("ServiceName: ", strconv.Quote(fullServName), ",")
	g.P("HandlerType: (*", serverType, ")(nil),")
	g.P("Methods: []", grpcPkg, ".MethodDesc{")
	for i, method := range service.Method {
		if method.GetServerStreaming() || method.GetClientStreaming() {
			continue
		}
		g.P("{")
		g.P("MethodName: ", strconv.Quote(method.GetName()), ",")
		g.P("Handler: ", handlerNames[i], ",")
		g.P("},")
	}
	g.P("},")
	g.P("Streams: []", grpcPkg, ".StreamDesc{")
	for i, method := range service.Method {
		if !method.GetServerStreaming() && !method.GetClientStreaming() {
			continue
		}
		g.P("{")
		g.P("StreamName: ", strconv.Quote(method.GetName()), ",")
		g.P("Handler: ", handlerNames[i], ",")
		if method.GetServerStreaming() {
			g.P("ServerStreams: true,")
		}
		if method.GetClientStreaming() {
			g.P("ClientStreams: true,")
		}
		g.P("},")
	}
	g.P("},")
	g.P("Metadata: \"", file.GetName(), "\",")
	g.P("}")
	g.P()
}
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)
}
378670
func (gc *Client) generateSecurity(dir string) error {
	for name, ss := range gc.apiDef.SecuritySchemes {
		if v, ok := ss.Settings["accessTokenUri"]; ok {
			ctx := map[string]string{
				"ClientName":     gc.Name,
				"AccessTokenURI": fmt.Sprintf("%v", v),
				"PackageName":    gc.PackageName,
			}
			filename := filepath.Join(dir, "oauth2_client_"+name+".go")
			if err := commons.GenerateFile(ctx, "./templates/golang/oauth2_client_go.tmpl", "oauth2_client_go", filename, true); err != nil {
				return err
			}
		}
	}
	return nil
}
321248
func generateLibraries(libraries map[string]*raml.Library, baseDir string) error {
	for _, ramlLib := range libraries {
		pl := newLibrary(ramlLib, baseDir)

		if err := pl.generate(); err != nil {
			return err
		}
	}
	return nil
}
1075922
func (s *Server) Generate() error {
	apiDef := new(raml.APIDefinition)
	// parse the raml file
	dir, fileName := filepath.Split(s.RAMLFile)
	ramlBytes, err := raml.ParseReadFile(dir, fileName, apiDef)
	if err != nil {
		return err
	}

	var generator generator.Server

	switch s.Lang {
	case langGo:
		generator = golang.NewServer(apiDef, s.PackageName, s.APIDocsDir, s.RootImportPath, s.WithMain,
			s.Dir, s.LibRootURLs)
	case langPython:
		generator = python.NewServer(s.Kind, apiDef, s.APIDocsDir, s.Dir, s.WithMain, s.LibRootURLs)
	case langNim:
		generator = nim.NewServer(apiDef, s.APIDocsDir, s.Dir)
	case langTarantool:
		generator = tarantool.NewServer(apiDef, s.APIDocsDir, s.Dir)
	default:
		return errInvalidLang
	}
	err = generator.Generate()
	if err != nil {
		return err
	}

	if s.APIDocsDir == "" {
		return nil
	}

	if s.Lang == langNim {
		s.APIDocsDir = "public/" + s.APIDocsDir
	}

	log.Infof("Generating API Docs to %v", s.APIDocsDir)

	return apidocs.Generate(apiDef, s.RAMLFile, ramlBytes, filepath.Join(s.Dir, s.APIDocsDir), s.LibRootURLs)
}
591019
func _go_glib_sourcefunc(sfi *C.sourcefunc_info) {
	id := int(sfi.func_no)
	value, found := sourcefunc_contexts.Get(id)
	if !found {
		return
	}
	context := value.(*SourcefuncContext)
	t := context.f.Type()
	fargs := make([]reflect.Value, t.NumIn())
	if len(fargs) > 0 {
		fargs[0] = reflect.ValueOf(context.data)
	}
	ret := context.f.Call(fargs)
	if len(ret) > 0 {
		bret, _ := ret[0].Interface().(bool)
		sfi.ret = gbool(bret)
	}
}
839965
func GenerateController(force, regen bool, appPkg, outDir, pkg, name string, r *design.ResourceDefinition) (filename string, err error) {
	filename = filepath.Join(outDir, codegen.SnakeCase(name)+".go")
	var (
		actionImpls      map[string]string
		extractedImports []*ast.ImportSpec
	)
	if regen {
		actionImpls, extractedImports, err = extractControllerBody(filename)
		if err != nil {
			return "", err
		}
		os.Remove(filename)
	}
	if force {
		os.Remove(filename)
	}
	if _, e := os.Stat(filename); e == nil {
		return "", nil
	}
	if err = os.MkdirAll(outDir, 0755); err != nil {
		return "", err
	}

	var file *codegen.SourceFile
	file, err = codegen.SourceFileFor(filename)
	if err != nil {
		return "", err
	}
	defer func() {
		file.Close()
		if err == nil {
			err = file.FormatCode()
		}
	}()

	elems := strings.Split(appPkg, "/")
	pkgName := elems[len(elems)-1]
	var imp string
	if _, err := codegen.PackageSourcePath(appPkg); err == nil {
		imp = appPkg
	} else {
		imp, err = codegen.PackagePath(outDir)
		if err != nil {
			return "", err
		}
		imp = path.Join(filepath.ToSlash(imp), appPkg)
	}

	imports := []*codegen.ImportSpec{
		codegen.SimpleImport("io"),
		codegen.SimpleImport("github.com/goadesign/goa"),
		codegen.SimpleImport(imp),
		codegen.SimpleImport("golang.org/x/net/websocket"),
	}
	for _, imp := range extractedImports {
		// This may introduce duplicate imports of the defaults, but
		// that'll get worked out by Format later.
		var cgimp *codegen.ImportSpec
		path := strings.Trim(imp.Path.Value, `"`)
		if imp.Name != nil {
			cgimp = codegen.NewImport(imp.Name.Name, path)
		} else {
			cgimp = codegen.SimpleImport(path)
		}
		imports = append(imports, cgimp)
	}

	funcs := funcMap(pkgName, actionImpls)
	if err = file.WriteHeader("", pkg, imports); err != nil {
		return "", err
	}
	if err = file.ExecuteTemplate("controller", ctrlT, funcs, r); err != nil {
		return "", err
	}
	err = r.IterateActions(func(a *design.ActionDefinition) error {
		if a.WebSocket() {
			return file.ExecuteTemplate("actionWS", actionWST, funcs, a)
		}
		return file.ExecuteTemplate("action", actionT, funcs, a)
	})
	if err != nil {
		return "", err
	}
	return
}
258954
func Generate(pkg *PackageInfo, importDirs []string, protocCommand string, protocFlags []string, printOnly bool) (err error) {
	args := protocFlags[0:len(protocFlags):len(protocFlags)]

	files := make([]string, 0, len(pkg.Files))
	for _, f := range pkg.Files {
		files = append(files, f.FullPath)
	}
	sort.Strings(files)
	args = append(args, files...)

	if printOnly {
		fmt.Printf("%s %s\n", protocCommand, strings.Join(args, " "))
		return nil
	}
	cmd := exec.Command(protocCommand, args...)
	out, err := cmd.CombinedOutput()
	if err != nil {
		cmdline := fmt.Sprintf("%s %s\n", protocCommand, strings.Join(args, " "))
		return fmt.Errorf("error running %v\n%v\nOutput:\n======\n%s======\n", cmdline, err, out)
	}
	return nil
}
326959
func (g *Generator) Generate() (_ []string, err error) {
	if g.API == nil {
		return nil, fmt.Errorf("missing API definition, make sure design is properly initialized")
	}

	go utils.Catch(nil, func() { g.Cleanup() })

	defer func() {
		if err != nil {
			g.Cleanup()
		}
	}()

	if g.Timeout == 0 {
		g.Timeout = 20 * time.Second
	}
	if g.Scheme == "" && len(g.API.Schemes) > 0 {
		g.Scheme = g.API.Schemes[0]
	}
	if g.Scheme == "" {
		g.Scheme = "http"
	}
	if g.Host == "" {
		g.Host = g.API.Host
	}
	if g.Host == "" {
		return nil, fmt.Errorf("missing host value, set it with --host")
	}

	g.OutDir = filepath.Join(g.OutDir, "js")
	if err := os.RemoveAll(g.OutDir); err != nil {
		return nil, err
	}
	if err := os.MkdirAll(g.OutDir, 0755); err != nil {
		return nil, err
	}
	g.genfiles = append(g.genfiles, g.OutDir)

	// Generate client.js
	exampleAction, err := g.generateJS(filepath.Join(g.OutDir, "client.js"))
	if err != nil {
		return
	}

	// Generate axios.html
	if err = g.generateAxiosJS(); err != nil {
		return
	}

	if exampleAction != nil && !g.NoExample {
		// Generate index.html
		if err = g.generateIndexHTML(filepath.Join(g.OutDir, "index.html"), exampleAction); err != nil {
			return
		}

		// Generate example
		if err = g.generateExample(); err != nil {
			return
		}
	}

	return g.genfiles, nil
}
241
func Generate(pidfile string, chDel <-chan struct{}) error {
	f, err := os.OpenFile(pidfile, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644)
	if err != nil {
		return err
	}
	defer f.Close()
	fmt.Fprintln(f, os.Getpid())
	if chDel != nil {
		go func() {
			select {
			case <-chDel:
				os.Remove(pidfile)
			}
		}()
	}
	return nil
}
1212336
func NewClient(
	ctx context.Context,
	gcKeyFile string,
	projectID string,
	options ...interface{},
) (*Client, error) {
	queueSize := OptionUploaderQueueSizeDefault
	errorHandler := OptionUploaderErrorHandlerDefault
	ensureDataset := OptionEnsureDatasetWhenFirstUploadDefault
	ensureTable := OptionEnsureTableWhenFirstUploadDefault
	for _, option := range options {
		switch opt := option.(type) {
		case OptionUploaderQueueSize:
			queueSize = opt
		case OptionUploaderErrorHandler:
			errorHandler = opt
		case OptionEnsureDatasetWhenFirstUpload:
			ensureDataset = opt
		case OptionEnsureTableWhenFirstUpload:
			ensureTable = opt
		default:
			return nil, ErrUnknownOption2.New(nil, option, opt)
		}
	}

	client, err := bigquery.NewClient(
		ctx,
		projectID,
		option.WithServiceAccountFile(gcKeyFile),
	)
	if err != nil {
		return nil, err
	}

	msgQueue := make(chan uploadMessage, queueSize)
	go startUploaderLoop(ctx, msgQueue, errorHandler)

	return &Client{
		ctx:           ctx,
		client:        client,
		msgQueue:      msgQueue,
		ensureDataset: ensureDataset,
		ensureTable:   ensureTable,
	}, nil
}
897984
func GenerateConfig(cfgFile string, data map[string]interface{}) error {
	oncer.Deprecate(0, "generate.GenerateConfig", "Use github.com/gobuffalo/pop/genny/config instead.")
	return Config(cfgFile, data)
}
1255030
func Generate(m *compile.Module, o *Options) error {
	if !filepath.IsAbs(o.ThriftRoot) {
		return fmt.Errorf(
			"ThriftRoot must be an absolute path: %q is not absolute",
			o.ThriftRoot)
	}

	if !filepath.IsAbs(o.OutputDir) {
		return fmt.Errorf(
			"OutputDir must be an absolute path: %q is not absolute",
			o.OutputDir)
	}

	importer := thriftPackageImporter{
		ImportPrefix: o.PackagePrefix,
		ThriftRoot:   o.ThriftRoot,
	}

	// Mapping of filenames relative to OutputDir to their contents.
	files := make(map[string][]byte)
	genBuilder := newGenerateServiceBuilder(importer)

	generate := func(m *compile.Module) error {
		moduleFiles, err := generateModule(m, importer, genBuilder, o)
		if err != nil {
			return generateError{Name: m.ThriftPath, Reason: err}
		}
		if err := mergeFiles(files, moduleFiles); err != nil {
			return generateError{Name: m.ThriftPath, Reason: err}
		}
		return nil
	}

	// Note that we call generate directly on only those modules that we need
	// to generate code for. If the user used --no-recurse, we're not going to
	// generate code for included modules.
	if o.NoRecurse {
		if err := generate(m); err != nil {
			return err
		}
	} else {
		if err := m.Walk(generate); err != nil {
			return err
		}
	}

	plug := o.Plugin
	if plug == nil {
		plug = plugin.EmptyHandle
	}

	if sgen := plug.ServiceGenerator(); sgen != nil {
		res, err := sgen.Generate(genBuilder.Build())
		if err != nil {
			return err
		}

		if err := mergeFiles(files, res.Files); err != nil {
			return err
		}
	}

	for relPath, contents := range files {
		fullPath := filepath.Join(o.OutputDir, relPath)
		directory := filepath.Dir(fullPath)

		if err := os.MkdirAll(directory, 0755); err != nil {
			return fmt.Errorf("could not create directory %q: %v", directory, err)
		}

		if err := ioutil.WriteFile(fullPath, contents, 0644); err != nil {
			return fmt.Errorf("failed to write %q: %v", fullPath, err)
		}
	}

	return nil
}
291466
func writeAPIFile(g *generateInfo) error {
	return writeGoFile(filepath.Join(g.PackageDir, "api.go"),
		codeLayout,
		"",
		g.API.PackageName(),
		g.API.APIGoCode(),
	)
}