// generate code of all libraries
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
}
1045666
func libs(binpath string) []string {
	f, err := elf.Open(binpath)
	if err != nil {
		return []string{}
	}
	libraries, _ := f.ImportedLibraries()
	return libraries
}
1212913
func (g *Generator) generateControllers() (err error) {
	var (
		ctlFile string
		ctlWr   *ControllersWriter
	)
	{
		ctlFile = filepath.Join(g.OutDir, "controllers.go")
		ctlWr, err = NewControllersWriter(ctlFile)
		if err != nil {
			return
		}
	}
	defer func() {
		ctlWr.Close()
		if err == nil {
			err = ctlWr.FormatCode()
		}
	}()
	title := fmt.Sprintf("%s: Application Controllers", g.API.Context())
	imports := []*codegen.ImportSpec{
		codegen.SimpleImport("net/http"),
		codegen.SimpleImport("fmt"),
		codegen.SimpleImport("context"),
		codegen.SimpleImport("github.com/goadesign/goa"),
		codegen.SimpleImport("github.com/goadesign/goa/cors"),
		codegen.SimpleImport("regexp"),
		codegen.SimpleImport("strconv"),
		codegen.SimpleImport("time"),
		codegen.NewImport("uuid", "github.com/gofrs/uuid"),
	}
	encoders, err := BuildEncoders(g.API.Produces, true)
	if err != nil {
		return err
	}
	decoders, err := BuildEncoders(g.API.Consumes, false)
	if err != nil {
		return err
	}
	encoderImports := make(map[string]bool)
	for _, data := range encoders {
		encoderImports[data.PackagePath] = true
	}
	for _, data := range decoders {
		encoderImports[data.PackagePath] = true
	}
	var packagePaths []string
	for packagePath := range encoderImports {
		if packagePath != "github.com/goadesign/goa" {
			packagePaths = append(packagePaths, packagePath)
		}
	}
	sort.Strings(packagePaths)
	for _, packagePath := range packagePaths {
		imports = append(imports, codegen.SimpleImport(packagePath))
	}
	if err = ctlWr.WriteHeader(title, g.Target, imports); err != nil {
		return err
	}
	if err = ctlWr.WriteInitService(encoders, decoders); err != nil {
		return err
	}

	g.genfiles = append(g.genfiles, ctlFile)
	var controllersData []*ControllerTemplateData
	g.API.IterateResources(func(r *design.ResourceDefinition) error {
		// Create file servers for all directory file servers that serve index.html.
		fileServers := r.FileServers
		for _, fs := range r.FileServers {
			if fs.IsDir() {
				rpath := design.WildcardRegex.ReplaceAllLiteralString(fs.RequestPath, "")
				rpath += "/"
				fileServers = append(fileServers, &design.FileServerDefinition{
					Parent:      fs.Parent,
					Description: fs.Description,
					Docs:        fs.Docs,
					FilePath:    filepath.Join(fs.FilePath, "index.html"),
					RequestPath: rpath,
					Metadata:    fs.Metadata,
					Security:    fs.Security,
				})
			}
		}
		data := &ControllerTemplateData{
			API:            g.API,
			Resource:       codegen.Goify(r.Name, true),
			PreflightPaths: r.PreflightPaths(),
			FileServers:    fileServers,
		}
		r.IterateActions(func(a *design.ActionDefinition) error {
			context := fmt.Sprintf("%s%sContext", codegen.Goify(a.Name, true), codegen.Goify(r.Name, true))
			unmarshal := fmt.Sprintf("unmarshal%s%sPayload", codegen.Goify(a.Name, true), codegen.Goify(r.Name, true))
			action := map[string]interface{}{
				"Name":             codegen.Goify(a.Name, true),
				"DesignName":       a.Name,
				"Routes":           a.Routes,
				"Context":          context,
				"Unmarshal":        unmarshal,
				"Payload":          a.Payload,
				"PayloadOptional":  a.PayloadOptional,
				"PayloadMultipart": a.PayloadMultipart,
				"Security":         a.Security,
			}
			data.Actions = append(data.Actions, action)
			return nil
		})
		if len(data.Actions) > 0 || len(data.FileServers) > 0 {
			data.Encoders = encoders
			data.Decoders = decoders
			data.Origins = r.AllOrigins()
			controllersData = append(controllersData, data)
		}
		return nil
	})
	err = ctlWr.Execute(controllersData)
	return
}
579257
func (js jsonSchema) Generate(dir string) error {
	if js.Alias.Builtin {
		return nil // plain builtin type can't be a JSON
	}

	filename := filepath.Join(dir, js.filename())
	ctx := map[string]interface{}{
		"Content": js.String(),
	}
	return commons.GenerateFile(ctx, "./templates/golang/json_schema.tmpl", "json_schema", filename, true)
}
586545
func GenerateCode(secret string, t time.Time) (string, error) {
	return GenerateCodeCustom(secret, t, ValidateOpts{
		Period:    30,
		Skew:      1,
		Digits:    otp.DigitsSix,
		Algorithm: otp.AlgorithmSHA1,
	})
}
737211
func GenerateClient(apiDef *raml.APIDefinition, conf ClientConfig) error {
	switch conf.Lang {
	case langGo:
		gc, err := golang.NewClient(apiDef, conf.PackageName, conf.RootImportPath, conf.Dir,
			conf.LibRootURLs)
		if err != nil {
			return err
		}
		return gc.Generate()
	case langPython:
		pc := python.NewClient(apiDef, conf.Kind, conf.PythonUnmarshallResponse)
		return pc.Generate(conf.Dir)
	case langNim:
		nc := nim.NewClient(apiDef, conf.Dir)
		return nc.Generate()
	default:
		return errInvalidLang
	}
}
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
}
223034
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()
		}
	}()

	firstNonEmpty := func(args ...string) string {
		for _, value := range args {
			if len(value) > 0 {
				return value
			}
		}
		return ""
	}

	g.Target = firstNonEmpty(g.Target, "client")
	g.ToolDirName = firstNonEmpty(g.ToolDirName, "tool")
	g.Tool = firstNonEmpty(g.Tool, defaultToolName(g.API))

	codegen.Reserved[g.Target] = true

	// Setup output directories as needed
	var pkgDir, toolDir, cliDir string
	{
		if !g.NoTool {
			toolDir = filepath.Join(g.OutDir, g.ToolDirName, g.Tool)
			if _, err = os.Stat(toolDir); err != nil {
				if err = os.MkdirAll(toolDir, 0755); err != nil {
					return
				}
			}

			cliDir = filepath.Join(g.OutDir, g.ToolDirName, "cli")
			if err = os.RemoveAll(cliDir); err != nil {
				return
			}
			if err = os.MkdirAll(cliDir, 0755); err != nil {
				return
			}
		}

		pkgDir = filepath.Join(g.OutDir, g.Target)
		if err = os.RemoveAll(pkgDir); err != nil {
			return
		}
		if err = os.MkdirAll(pkgDir, 0755); err != nil {
			return
		}
	}

	// Setup generation
	var funcs template.FuncMap
	var clientPkg string
	{
		funcs = template.FuncMap{
			"add":                func(a, b int) int { return a + b },
			"cmdFieldType":       cmdFieldType,
			"defaultPath":        defaultPath,
			"escapeBackticks":    escapeBackticks,
			"goify":              codegen.Goify,
			"gotypedef":          codegen.GoTypeDef,
			"gotypedesc":         codegen.GoTypeDesc,
			"gotypename":         codegen.GoTypeName,
			"gotyperef":          codegen.GoTypeRef,
			"gotyperefext":       goTypeRefExt,
			"join":               join,
			"joinStrings":        strings.Join,
			"multiComment":       multiComment,
			"pathParams":         pathParams,
			"pathTemplate":       pathTemplate,
			"signerType":         signerType,
			"tempvar":            codegen.Tempvar,
			"title":              strings.Title,
			"toString":           toString,
			"toValueTypeName":    toValueTypeName,
			"typeName":           typeName,
			"format":             format,
			"handleSpecialTypes": handleSpecialTypes,
		}
		clientPkg, err = codegen.PackagePath(pkgDir)
		if err != nil {
			return
		}
		arrayToStringTmpl = template.Must(template.New("client").Funcs(funcs).Parse(arrayToStringT))
	}

	if !g.NoTool {
		var cliPkg string
		cliPkg, err = codegen.PackagePath(cliDir)
		if err != nil {
			return
		}

		// Generate tool/main.go (only once)
		mainFile := filepath.Join(toolDir, "main.go")
		if _, err := os.Stat(mainFile); err != nil {
			g.genfiles = append(g.genfiles, toolDir)
			if err = g.generateMain(mainFile, clientPkg, cliPkg, funcs); err != nil {
				return nil, err
			}
		}

		// Generate tool/cli/commands.go
		g.genfiles = append(g.genfiles, cliDir)
		if err = g.generateCommands(filepath.Join(cliDir, "commands.go"), clientPkg, funcs); err != nil {
			return
		}
	}

	// Generate client/client.go
	g.genfiles = append(g.genfiles, pkgDir)
	if err = g.generateClient(filepath.Join(pkgDir, "client.go"), clientPkg, funcs); err != nil {
		return
	}

	// Generate client/$res.go and types.go
	if err = g.generateClientResources(pkgDir, clientPkg, funcs); err != nil {
		return
	}

	return g.genfiles, nil
}
484762
func (pr *pythonResource) generate(fileName, tmplFile, tmplName, dir string) error {
	return commons.GenerateFile(pr, tmplFile, tmplName, fileName, true)
}
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
}
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()
}
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
}
495699
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()
		}
	}()

	codegen.Reserved[g.Target] = true

	os.RemoveAll(g.OutDir)

	if err := os.MkdirAll(g.OutDir, 0755); err != nil {
		return nil, err
	}
	g.genfiles = []string{g.OutDir}
	if err := g.generateContexts(); err != nil {
		return nil, err
	}
	if err := g.generateControllers(); err != nil {
		return nil, err
	}
	if err := g.generateSecurity(); err != nil {
		return nil, err
	}
	if err := g.generateHrefs(); err != nil {
		return nil, err
	}
	if err := g.generateMediaTypes(); err != nil {
		return nil, err
	}
	if err := g.generateUserTypes(); err != nil {
		return nil, err
	}
	if !g.NoTest {
		if err := g.generateResourceTest(); err != nil {
			return nil, err
		}
	}

	return g.genfiles, nil
}
815425
func generateModule(m *compile.Module, i thriftPackageImporter, builder *generateServiceBuilder, o *Options) (map[string][]byte, error) {
	// packageRelPath is the path relative to outputDir into which we'll be
	// writing the package for this Thrift file. For $thriftRoot/foo/bar.thrift,
	// packageRelPath is foo/bar, and packageDir is $outputDir/foo/bar. All
	// files for bar.thrift will be written to the $outputDir/foo/bar/ tree. The
	// package will be importable via $importPrefix/foo/bar.
	packageRelPath, err := i.RelativePackage(m.ThriftPath)
	if err != nil {
		return nil, err
	}

	// TODO(abg): Prefer top-level package name from `namespace go` directive.
	packageName := filepath.Base(packageRelPath)

	// importPath is the full import path for the top-level package generated
	// for this Thrift file.
	importPath, err := i.Package(m.ThriftPath)
	if err != nil {
		return nil, err
	}

	// Mapping of file names relative to packageRelPath to their contents.
	// Note that we need to return a mapping relative to o.OutputDir so we
	// will prepend $packageRelPath/ to all these paths.
	files := make(map[string][]byte)

	gopts := &GeneratorOptions{
		Importer:    i,
		ImportPath:  importPath,
		PackageName: packageName,
		NoZap:       o.NoZap,
	}
	g := NewGenerator(gopts)

	if len(m.Constants) > 0 {
		for _, constantName := range sortStringKeys(m.Constants) {
			if err := Constant(g, m.Constants[constantName]); err != nil {
				return nil, err
			}
		}

		buff := new(bytes.Buffer)
		if err := g.Write(buff, nil /* fset */); err != nil {
			return nil, fmt.Errorf(
				"could not generate constants for %q: %v", m.ThriftPath, err)
		}

		// TODO(abg): Verify no file collisions
		if !o.NoConstants {
			files["constants.go"] = buff.Bytes()
		}
	}

	if len(m.Types) > 0 {
		for _, typeName := range sortStringKeys(m.Types) {
			if err := TypeDefinition(g, m.Types[typeName]); err != nil {
				return nil, err
			}
		}

		buff := new(bytes.Buffer)
		if err := g.Write(buff, nil /* fset */); err != nil {
			return nil, fmt.Errorf(
				"could not generate types for %q: %v", m.ThriftPath, err)
		}

		// TODO(abg): Verify no file collisions
		if !o.NoTypes {
			files["types.go"] = buff.Bytes()
		}
	}

	if !o.NoEmbedIDL {
		if err := embedIDL(g, i, m); err != nil {
			return nil, err
		}

		buff := new(bytes.Buffer)
		if err := g.Write(buff, nil /* fset */); err != nil {
			return nil, fmt.Errorf(
				"could not generate idl.go for %q: %v", m.ThriftPath, err)
		}

		files["idl.go"] = buff.Bytes()
	}

	// Services must be generated last because names of user-defined types take
	// precedence over the names we pick for the service types.
	if len(m.Services) > 0 {
		for _, serviceName := range sortStringKeys(m.Services) {
			service := m.Services[serviceName]

			// generateModule gets called only for those modules for which we
			// need to generate code. With --no-recurse, generateModule is
			// called only on the root file specified by the user and not its
			// included modules. Only services defined in these files are
			// considered root services; plugins will generate code only for
			// root services, even though they have information about the
			// whole service tree.
			if _, err := builder.AddRootService(service); err != nil {
				return nil, err
			}

			serviceFiles, err := Service(g, service)
			if err != nil {
				return nil, fmt.Errorf(
					"could not generate code for service %q: %v",
					serviceName, err)
			}

			if !o.NoServiceHelpers {
				for name, buff := range serviceFiles {
					files[name] = buff.Bytes()
				}
			}
		}
	}

	newFiles := make(map[string][]byte, len(files))
	for path, contents := range files {
		newFiles[filepath.Join(packageRelPath, path)] = contents
	}
	return newFiles, nil
}
591275
func (gc *Client) generateHelperFile(dir string) error {
	fileName := filepath.Join(dir, "/client_utils.go")
	return commons.GenerateFile(gc, "./templates/golang/client_utils_go.tmpl", "client_utils_go", fileName, true)
}
293467
func (list *Lists) GenerateFilelist(out io.Writer) error {
	w := bufio.NewWriter(out)
	for _, pair := range list.getPairs() {
		dLen := len(*pair.data)
		toWrite := []string{
			pair.kind,
			"\n(",
			strconv.Itoa(dLen),
			")\n",
		}
		if dLen > 0 {
			toWrite = append(toWrite,
				strings.Join(*pair.data, "\n"),
				"\n")
		}
		toWrite = append(toWrite, "\n")
		for _, str := range toWrite {
			if _, err := w.WriteString(str); err != nil {
				return err
			}
		}
	}
	w.Flush()
	return nil
}