// Generate generates Go structs and a JSON Schema from the AWS CloudFormation
// Resource Specifications provided to NewResourceGenerator
772607
func (rg *ResourceGenerator) Generate() error {

	// Process the primary template first, since the primary template resources
	// are added to the JSON schema for fragment transform specs
	fmt.Printf("Downloading cloudformation specification from %s\n", rg.primaryUrl)
	primaryData, err := rg.downloadSpec(rg.primaryUrl)
	if err != nil {
		return err
	}
	primarySpec, err := rg.processSpec("cloudformation", primaryData)
	if err != nil {
		return err
	}
	if err := rg.generateJSONSchema("cloudformation", primarySpec); err != nil {
		return err
	}

	for name, url := range rg.fragmentUrls {
		fmt.Printf("Downloading %s specification from %s\n", name, url)
		data, err := rg.downloadSpec(url)
		if err != nil {
			return err
		}
		spec, err := rg.processSpec(name, data)
		if err != nil {
			return err
		}
		// Append main CloudFormation schema resource types and property types to this fragment
		for k, v := range primarySpec.Resources {
			spec.Resources[k] = v
		}
		for k, v := range primarySpec.Properties {
			spec.Properties[k] = v
		}
		if err := rg.generateJSONSchema(name, spec); err != nil {
			return err
		}
	}

	if err := rg.generateAllResourcesMap(rg.Results.AllResources); err != nil {
		return err
	}

	return nil
}
1333048
func (g *Generator) Generate(api *design.APIDefinition) (_ []string, err error) {
	if api == nil {
		return nil, fmt.Errorf("missing API definition, make sure design.Design is properly initialized")
	}
	go utils.Catch(nil, func() { g.Cleanup() })
	defer func() {
		if err != nil {
			g.Cleanup()
		}
	}()
	if err := os.MkdirAll(g.outDir, 0755); err != nil {
		return nil, err
	}

	if err := g.generateUserTypes(g.outDir, api); err != nil {
		return g.genfiles, err
	}
	if err := g.generateUserHelpers(g.outDir, api); err != nil {
		return g.genfiles, err
	}

	return g.genfiles, nil
}
771974
func (m *Generator) Generate() ([]string, error) {
	// Sanity checks
	if m.OutDir == "" {
		return nil, fmt.Errorf("missing output directory flag")
	}
	if m.DesignPkgPath == "" {
		return nil, fmt.Errorf("missing design package flag")
	}

	// Create output directory
	if err := os.MkdirAll(m.OutDir, 0755); err != nil {
		return nil, err
	}

	// Create temporary workspace used for generation
	wd, err := os.Getwd()
	if err != nil {
		return nil, err
	}
	tmpDir, err := ioutil.TempDir(wd, "goagen")
	if err != nil {
		if _, ok := err.(*os.PathError); ok {
			err = fmt.Errorf(`invalid output directory path "%s"`, m.OutDir)
		}
		return nil, err
	}
	defer func() {
		if !m.debug {
			os.RemoveAll(tmpDir)
		}
	}()
	if m.debug {
		fmt.Printf("** Code generator source dir: %s\n", tmpDir)
	}

	pkgSourcePath, err := codegen.PackageSourcePath(m.DesignPkgPath)
	if err != nil {
		return nil, fmt.Errorf("invalid design package import path: %s", err)
	}
	pkgName, err := codegen.PackageName(pkgSourcePath)
	if err != nil {
		return nil, err
	}

	// Generate tool source code.
	pkgPath := filepath.Join(tmpDir, pkgName)
	p, err := codegen.PackageFor(pkgPath)
	if err != nil {
		return nil, err
	}
	m.generateToolSourceCode(p)

	// Compile and run generated tool.
	if m.debug {
		fmt.Printf("** Compiling with:\n%s", strings.Join(os.Environ(), "\n"))
	}
	genbin, err := p.Compile("goagen")
	if err != nil {
		return nil, err
	}
	return m.spawn(genbin)
}
450465
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.Target == "" {
		g.Target = "app"
	}

	codegen.Reserved[g.Target] = true

	mainFile := filepath.Join(g.OutDir, "main.go")
	if g.Force {
		os.Remove(mainFile)
	}
	_, err = os.Stat(mainFile)
	if err != nil {
		// ensure that the output directory exists before creating a new main
		if err = os.MkdirAll(g.OutDir, 0755); err != nil {
			return nil, err
		}
		if err = g.createMainFile(mainFile, funcMap(g.Target, nil)); err != nil {
			return nil, err
		}
	}

	err = g.API.IterateResources(func(r *design.ResourceDefinition) error {
		filename, err := GenerateController(g.Force, g.Regen, g.Target, g.OutDir, "main", r.Name, r)
		if err != nil {
			return err
		}

		g.genfiles = append(g.genfiles, filename)
		return nil
	})
	if err != nil {
		return
	}

	return g.genfiles, nil
}
1353465
func (g *Plugin) Generate(file *generator.FileDescriptor) {
	if len(file.FileDescriptorProto.Service) == 0 {
		return
	}

	g.P("// Reference imports to suppress errors if they are not otherwise used.")
	g.P("var _ ", contextPkg, ".Context")
	g.P("var _ ", yarpcPkg, ".ClientConn")
	g.P()

	// Assert version compatibility.
	g.P("// This is a compile-time assertion to ensure that this generated file")
	g.P("// is compatible with the yarpc package it is being compiled against.")
	g.P("const _ = ", yarpcPkg, ".SupportPackageIsVersion", generatedCodeVersion)
	g.P()

	for i, service := range file.FileDescriptorProto.Service {
		g.generateService(file, service, i)
	}
}
800506
func (k *Key) Generate() error {
	_, err := io.ReadFull(rand.Reader, k[:])
	return err
}
61639
func (codegen *CodeGenerator) Generate() (string, error) {
	for index, rawSchema := range codegen.rawSchemas {
		parsedSchema, err := ParseSchema(rawSchema)
		if err != nil {
			return "", err
		}

		schema, ok := parsedSchema.(*RecordSchema)
		if !ok {
			return "", errors.New("Not a Record schema.")
		}
		schemaInfo, err := newRecordSchemaInfo(schema)
		if err != nil {
			return "", err
		}

		buffer := &bytes.Buffer{}
		codegen.codeSnippets = append(codegen.codeSnippets, buffer)

		// write package and import only once
		if index == 0 {
			err = codegen.writePackageName(schemaInfo)
			if err != nil {
				return "", err
			}

			err = codegen.writeImportStatement()
			if err != nil {
				return "", err
			}
		}

		err = codegen.writeStruct(schemaInfo)
		if err != nil {
			return "", err
		}
	}

	formatted, err := format.Source([]byte(codegen.collectResult()))
	if err != nil {
		return "", err
	}

	return string(formatted), nil
}
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
}
150657
func (s SecretForDockerRegistryGeneratorV1) Generate(genericParams map[string]interface{}) (runtime.Object, error) {
	err := ValidateParams(s.ParamNames(), genericParams)
	if err != nil {
		return nil, err
	}
	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
	}
	delegate := &SecretForDockerRegistryGeneratorV1{
		Name:     params["name"],
		Username: params["docker-username"],
		Email:    params["docker-email"],
		Password: params["docker-password"],
		Server:   params["docker-server"],
	}
	return delegate.StructuredGenerate()
}
1250609
func (s *SetupService) Generate(ctx context.Context, or *platform.OnboardingRequest) (*platform.OnboardingResults, error) {
	u, err := newURL(s.Addr, setupPath)
	if err != nil {
		return nil, err
	}
	octets, err := json.Marshal(or)
	if err != nil {
		return nil, err
	}
	req, err := http.NewRequest("POST", u.String(), bytes.NewReader(octets))
	if err != nil {
		return nil, err
	}

	req.Header.Set("Content-Type", "application/json")
	hc := newClient(u.Scheme, s.InsecureSkipVerify)

	resp, err := hc.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	// TODO(jsternberg): Should this check for a 201 explicitly?
	if err := CheckError(resp, true); err != nil {
		return nil, err
	}

	var oResp onboardingResponse
	if err := json.NewDecoder(resp.Body).Decode(&oResp); err != nil {
		return nil, err
	}

	bkt, err := oResp.Bucket.toPlatform()
	if err != nil {
		return nil, err
	}
	return &platform.OnboardingResults{
		Org:    &oResp.Organization.Organization,
		User:   &oResp.User.User,
		Auth:   oResp.Auth.toPlatform(),
		Bucket: bkt,
	}, nil
}
1248839
func (g *grpc) Generate(file *generator.FileDescriptor) {
	if len(file.FileDescriptorProto.Service) == 0 {
		return
	}

	contextPkg = string(g.gen.AddImport(contextPkgPath))
	grpcPkg = string(g.gen.AddImport(grpcPkgPath))

	g.P("// Reference imports to suppress errors if they are not otherwise used.")
	g.P("var _ ", contextPkg, ".Context")
	g.P("var _ ", grpcPkg, ".ClientConn")
	g.P()

	// Assert version compatibility.
	g.P("// This is a compile-time assertion to ensure that this generated file")
	g.P("// is compatible with the grpc package it is being compiled against.")
	g.P("const _ = ", grpcPkg, ".SupportPackageIsVersion", generatedCodeVersion)
	g.P()

	for i, service := range file.FileDescriptorProto.Service {
		g.generateService(file, service, i)
	}
}
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
}
150129
func (p *Params) Generate(id string) string {
	buf := make([]byte, dataSize, dataSize+macSize)
	binary.BigEndian.PutUint32(buf, uint32(p.timer().Unix()))
	token := append(buf, hmacSHA256(p.key, buf, id)...)
	return base64.URLEncoding.EncodeToString(token)
}
1155095
func (g *Generator) Generate() error {
	g.populateImports()
	if g.iface == nil {
		return ErrNotSetup
	}

	g.printf(
		"// %s is an autogenerated mock type for the %s type\n", g.mockName(),
		g.iface.Name,
	)

	g.printf(
		"type %s struct {\n\tmock.Mock\n}\n\n", g.mockName(),
	)

	for i := 0; i < g.iface.Type.NumMethods(); i++ {
		fn := g.iface.Type.Method(i)

		ftype := fn.Type().(*types.Signature)
		fname := fn.Name()

		params := g.genList(ftype.Params(), ftype.Variadic())
		returns := g.genList(ftype.Results(), false)

		if len(params.Names) == 0 {
			g.printf("// %s provides a mock function with given fields:\n", fname)
		} else {
			g.printf(
				"// %s provides a mock function with given fields: %s\n", fname,
				strings.Join(params.Names, ", "),
			)
		}
		g.printf(
			"func (_m *%s) %s(%s) ", g.mockName(), fname,
			strings.Join(params.Params, ", "),
		)

		switch len(returns.Types) {
		case 0:
			g.printf("{\n")
		case 1:
			g.printf("%s {\n", returns.Types[0])
		default:
			g.printf("(%s) {\n", strings.Join(returns.Types, ", "))
		}

		var formattedParamNames string
		for i, name := range params.Names {
			if i > 0 {
				formattedParamNames += ", "
			}

			paramType := params.Types[i]
			// for variable args, move the ... to the end.
			if strings.Index(paramType, "...") == 0 {
				name += "..."
			}
			formattedParamNames += name
		}

		called := g.generateCalled(params, formattedParamNames) // _m.Called invocation string

		if len(returns.Types) > 0 {
			g.printf("\tret := %s\n\n", called)

			var (
				ret []string
			)

			for idx, typ := range returns.Types {
				g.printf("\tvar r%d %s\n", idx, typ)
				g.printf("\tif rf, ok := ret.Get(%d).(func(%s) %s); ok {\n",
					idx, strings.Join(params.Types, ", "), typ)
				g.printf("\t\tr%d = rf(%s)\n", idx, formattedParamNames)
				g.printf("\t} else {\n")
				if typ == "error" {
					g.printf("\t\tr%d = ret.Error(%d)\n", idx, idx)
				} else if returns.Nilable[idx] {
					g.printf("\t\tif ret.Get(%d) != nil {\n", idx)
					g.printf("\t\t\tr%d = ret.Get(%d).(%s)\n", idx, idx, typ)
					g.printf("\t\t}\n")
				} else {
					g.printf("\t\tr%d = ret.Get(%d).(%s)\n", idx, idx, typ)
				}
				g.printf("\t}\n\n")

				ret = append(ret, fmt.Sprintf("r%d", idx))
			}

			g.printf("\treturn %s\n", strings.Join(ret, ", "))
		} else {
			g.printf("\t%s\n", called)
		}

		g.printf("}\n")
	}

	return nil
}
726979
func (g *Generator) Generate() error {
	// first we read the code from which we should find the types
	if err := g.readPackageCode(g.options.Source); err != nil {
		return err
	}

	// then we generate code for the types given
	for _, rootType := range g.options.Types {
		if err := g.generateStructCode(rootType); err != nil {
			return err
		}
	}

	//
	g.Imports = strings.Join(toolbox.MapKeysToStringSlice(g.imports), "\n")
	return g.writeCode()
}
281679
func Generate() (files []string, err error) {
	var outDir, ver string
	set := flag.NewFlagSet("app", flag.PanicOnError)
	set.StringVar(&outDir, "out", "", "")
	set.StringVar(&ver, "version", "", "")
	set.String("design", "", "")
	set.Parse(os.Args[1:])

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

	g := &Generator{OutDir: outDir, API: design.Design}

	return g.Generate()
}
132161
func (g *Generator) Generate(limit int) string {
	return g.generate(&state{limit: limit}, g.re)
}