// generate flask representation of an RAML resource
// It has one file : an API route and implementation
484762
func (pr *pythonResource) generate(fileName, tmplFile, tmplName, dir string) error {
	return commons.GenerateFile(pr, tmplFile, tmplName, fileName, true)
}
14627
func GenerateHandler(h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		Generate(w, r)
		h.ServeHTTP(w, r)
	})
}
1206511
func Generate(targetDir, targetSrc string, pool int, dynamic bool) error {
	filterPath := filepath.Join(targetDir, IgnoreFile)
	filter := filter.LoadFilter(filterPath)
	var hashes HashSet
	var err error
	if pool < 2 {
		hashes, err = HashDirectory(targetDir)
	} else {
		if dynamic {
			pool *= runtime.NumCPU()
		}
		hashes, err = HashDirectoryAsync(targetDir, pool)
	}
	if err != nil {
		log.Critical("failed to hash directory:", err)
		return err
	}
	filtered := FilterHashes(hashes, filter)
	return Write(targetDir, targetSrc, filtered)
}
399391
func Generate() (files []string, err error) {
	var (
		outDir, designPkg, appPkg, ver, res, pkg string
		force, regen                             bool
	)

	set := flag.NewFlagSet("controller", flag.PanicOnError)
	set.StringVar(&outDir, "out", "", "")
	set.StringVar(&designPkg, "design", "", "")
	set.StringVar(&appPkg, "app-pkg", "app", "")
	set.StringVar(&pkg, "pkg", "main", "")
	set.StringVar(&res, "res", "", "")
	set.StringVar(&ver, "version", "", "")
	set.BoolVar(&force, "force", false, "")
	set.BoolVar(&regen, "regen", false, "")
	set.Bool("notest", false, "")
	set.Parse(os.Args[1:])

	if err := codegen.CheckVersion(ver); err != nil {
		return nil, err
	}

	g := &Generator{OutDir: outDir, DesignPkg: designPkg, AppPkg: appPkg, Force: force, Regen: regen, API: design.Design, Pkg: pkg, Resource: res}

	return g.Generate()
}
1225505
func (RouteGenerator) Generate(genericParams map[string]interface{}) (runtime.Object, error) {
	var (
		labels map[string]string
		err    error
	)

	params := map[string]string{}
	for key, value := range genericParams {
		strVal, isString := value.(string)
		if !isString {
			return nil, fmt.Errorf("expected string, saw %v for '%s'", value, key)
		}
		params[key] = strVal
	}

	labelString, found := params["labels"]
	if found && len(labelString) > 0 {
		labels, err = generate.ParseLabels(labelString)
		if err != nil {
			return nil, err
		}
	}

	name, found := params["name"]
	if !found || len(name) == 0 {
		name, found = params["default-name"]
		if !found || len(name) == 0 {
			return nil, fmt.Errorf("'name' is a required parameter.")
		}
	}

	route := &routev1.Route{
		ObjectMeta: metav1.ObjectMeta{
			Name:   name,
			Labels: labels,
		},
		Spec: routev1.RouteSpec{
			Host:           params["hostname"],
			WildcardPolicy: routev1.WildcardPolicyType(params["wildcard-policy"]),
			Path:           params["path"],
			To: routev1.RouteTargetReference{
				Name: params["default-name"],
			},
		},
	}

	portString := params["port"]
	if len(portString) > 0 {
		var targetPort intstr.IntOrString
		if port, err := strconv.Atoi(portString); err == nil {
			targetPort = intstr.FromInt(port)
		} else {
			targetPort = intstr.FromString(portString)
		}
		route.Spec.Port = &routev1.RoutePort{
			TargetPort: targetPort,
		}
	}

	return route, nil
}
506509
func generateListMultipartUploadsResponse(bucket string, multipartsInfo ListMultipartsInfo, encodingType string) ListMultipartUploadsResponse {
	listMultipartUploadsResponse := ListMultipartUploadsResponse{}
	listMultipartUploadsResponse.Bucket = bucket
	listMultipartUploadsResponse.Delimiter = s3EncodeName(multipartsInfo.Delimiter, encodingType)
	listMultipartUploadsResponse.IsTruncated = multipartsInfo.IsTruncated
	listMultipartUploadsResponse.EncodingType = encodingType
	listMultipartUploadsResponse.Prefix = s3EncodeName(multipartsInfo.Prefix, encodingType)
	listMultipartUploadsResponse.KeyMarker = s3EncodeName(multipartsInfo.KeyMarker, encodingType)
	listMultipartUploadsResponse.NextKeyMarker = s3EncodeName(multipartsInfo.NextKeyMarker, encodingType)
	listMultipartUploadsResponse.MaxUploads = multipartsInfo.MaxUploads
	listMultipartUploadsResponse.NextUploadIDMarker = multipartsInfo.NextUploadIDMarker
	listMultipartUploadsResponse.UploadIDMarker = multipartsInfo.UploadIDMarker
	listMultipartUploadsResponse.CommonPrefixes = make([]CommonPrefix, len(multipartsInfo.CommonPrefixes))
	for index, commonPrefix := range multipartsInfo.CommonPrefixes {
		listMultipartUploadsResponse.CommonPrefixes[index] = CommonPrefix{
			Prefix: s3EncodeName(commonPrefix, encodingType),
		}
	}
	listMultipartUploadsResponse.Uploads = make([]Upload, len(multipartsInfo.Uploads))
	for index, upload := range multipartsInfo.Uploads {
		newUpload := Upload{}
		newUpload.UploadID = upload.UploadID
		newUpload.Key = s3EncodeName(upload.Object, encodingType)
		newUpload.Initiated = upload.Initiated.UTC().Format(timeFormatAMZLong)
		listMultipartUploadsResponse.Uploads[index] = newUpload
	}
	return listMultipartUploadsResponse
}
636521
func (s *FileSource) Generate(f *flow.Flow) *flow.Dataset {
	return s.genShardInfos(f).RoundRobin(s.prefix, s.PartitionCount).Map(s.prefix+".Read", registeredMapperReadShard)
}
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)
	}
}
621202
func (s *mustRunAs) Generate(_ *api.Pod, _ *api.Container) (*api.SELinuxOptions, error) {
	return s.opts.SELinuxOptions, nil
}
1198452
func generateFile(scripts []script, tmplFile string, dest string) error {
	destFile, err := os.Create(dest)
	if err != nil {
		return err
	}
	tmpl, err := template.ParseFiles(tmplFile)
	if err != nil {
		return err
	}
	return tmpl.Execute(destFile, scripts)
}
1079736
func (g *goFileGenerator) Generate(filename, tmpl string, data interface{}) ([]byte, error) {
	funcs := template.FuncMap{
		"import":     g.Import,
		"formatType": g.FormatType,
	}
	for k, v := range g.templateFuncs {
		funcs[k] = v
	}

	t, err := template.New(filename).Delims("<", ">").Funcs(funcs).Parse(tmpl)
	if err != nil {
		return nil, fmt.Errorf("failed to parse template %q: %v", filename, err)
	}

	var buff bytes.Buffer
	if err := t.Execute(&buff, data); err != nil {
		return nil, err
	}

	fset := token.NewFileSet()
	f, err := parser.ParseFile(fset, filename, buff.Bytes(), parser.ParseComments)
	if err != nil {
		return nil, fmt.Errorf("failed to parse generated code: %v:\n%s", err, buff.String())
	}

	if len(f.Imports) > 0 {
		return nil, fmt.Errorf(
			"plain imports are not allowed with GoFileFromTemplate: use the import function")
	}

	importPaths := make([]string, 0, len(g.imports))
	for path := range g.imports {
		importPaths = append(importPaths, path)
	}
	sort.Strings(importPaths)
	for _, path := range importPaths {
		astutil.AddNamedImport(fset, f, g.imports[path], path)
	}

	buff = bytes.Buffer{}
	if err := format.Node(&buff, fset, f); err != nil {
		return nil, err // TODO wrap error
	}

	return buff.Bytes(), nil
}
127548
func (s *Struct) Generate(dir string) error {
	if s.Enum != nil {
		return s.Enum.generate(dir)
	}

	if err := s.generateEnums(dir); err != nil {
		return err
	}
	filename := filepath.Join(dir, s.Name+".capnp")
	return commons.GenerateFile(s, "./templates/capnp/struct_capnp.tmpl", "struct_capnp", filename, true)
}
1336180
func GenerateTemplate(filename, templateSource string, args map[string]interface{}) (err error) {
	tmpl := template.Must(template.New("").Parse(templateSource))

	var b bytes.Buffer
	if err = tmpl.Execute(&b, args); err != nil {
		return NewBuildIfError(err, "ExecuteTemplate: Execute failed")
	}
	sourceCode := b.String()
	filePath := filepath.Dir(filename)
	if !DirExists(filePath) {
		err = os.MkdirAll(filePath, 0777)
		if err != nil && !os.IsExist(err) {
			return NewBuildIfError(err, "Failed to make directory", "dir", filePath)
		}
	}

	// Create the file
	file, err := os.Create(filename)
	if err != nil {
		Logger.Fatal("Failed to create file", "error", err)
		return
	}
	defer func() {
		_ = file.Close()
	}()

	if _, err = file.WriteString(sourceCode); err != nil {
		Logger.Fatal("Failed to write to file: ", "error", err)
	}

	return
}
1210991
func Process(file string) (*raml.APIDefinition, error) {
	routes, err := raml.ParseFile(file)
	if err != nil {
		return nil, fmt.Errorf("Failed parsing RAML file: %s\n", err.Error())
	}
	return routes, 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)
}
391192
func (rootRouter *Router) ServeHTTP(rw http.ResponseWriter, r *http.Request) {

	// Manually create a closure. These variables are needed in middlewareStack.
	// The reason we put these here instead of in the middleware stack, is Go (as of 1.2)
	// creates a heap variable for each varaiable in the closure. To minimize that, we'll
	// just have one (closure *middlewareClosure).
	var closure middlewareClosure
	closure.Request.Request = r
	closure.appResponseWriter.ResponseWriter = rw
	closure.Routers = make([]*Router, 1, rootRouter.maxChildrenDepth)
	closure.Routers[0] = rootRouter
	closure.Contexts = make([]reflect.Value, 1, rootRouter.maxChildrenDepth)
	closure.Contexts[0] = reflect.New(rootRouter.contextType)
	closure.currentMiddlewareLen = len(rootRouter.middleware)
	closure.RootRouter = rootRouter
	closure.Request.rootContext = closure.Contexts[0]

	// Handle errors
	defer func() {
		if recovered := recover(); recovered != nil {
			rootRouter.handlePanic(&closure.appResponseWriter, &closure.Request, recovered)
		}
	}()

	next := middlewareStack(&closure)
	next(&closure.appResponseWriter, &closure.Request)
}
421748
func BuildURLFromMap(baseUrl string, queryParams map[string]string) string {
	if len(queryParams) < 1 {
		return baseUrl
	}
	queryValues := url.Values{}
	for key, val := range queryParams {
		queryValues.Set(key, val)
	}
	return BuildURL(baseUrl, queryValues)
}