// Generate recursively iterates over all tasks, including pre and post tasks for
// each of them, and adds all of them into a task chain.
340301
func (taskChain *TaskChain) generate(dtasks Dogtasks, task string) error {

	t, found := dtasks.Tasks[task]
	if !found {
		return fmt.Errorf("Task %q does not exist", task)
	}

	// Cycle detection
	for i := 0; i < len(taskChain.Tasks); i++ {
		if taskChain.Tasks[i].Name == task {
			if len(taskChain.Tasks[i].Pre) > 0 || len(taskChain.Tasks[i].Post) > 0 {
				return ErrCycleInTaskChain
			}
		}
	}

	// Iterate over pre-tasks
	if err := addToChain(taskChain, dtasks, t.Pre); err != nil {
		return err
	}

	// Add current task to chain
	taskChain.Tasks = append(taskChain.Tasks, *t)

	// Iterate over post-tasks
	if err := addToChain(taskChain, dtasks, t.Post); err != nil {
		return err
	}
	return nil
}
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
}
911841
func (src *Source) Generate(w io.Writer) error {
	const (
		pkgStd         = iota // any package in std library
		pkgXSysWindows        // x/sys/windows package
		pkgOther
	)
	isStdRepo, err := src.IsStdRepo()
	if err != nil {
		return err
	}
	var pkgtype int
	switch {
	case isStdRepo:
		pkgtype = pkgStd
	case packageName == "windows":
		// TODO: this needs better logic than just using package name
		pkgtype = pkgXSysWindows
	default:
		pkgtype = pkgOther
	}
	if *systemDLL {
		switch pkgtype {
		case pkgStd:
			src.Import("internal/syscall/windows/sysdll")
		case pkgXSysWindows:
		default:
			src.ExternalImport("golang.org/x/sys/windows")
		}
	}
	if *winio {
		src.ExternalImport("github.com/Microsoft/go-winio")
	}
	if packageName != "syscall" {
		src.Import("syscall")
	}
	funcMap := template.FuncMap{
		"packagename": packagename,
		"syscalldot":  syscalldot,
		"newlazydll": func(dll string) string {
			arg := "\"" + dll + ".dll\""
			if !*systemDLL {
				return syscalldot() + "NewLazyDLL(" + arg + ")"
			}
			if strings.HasPrefix(dll, "api_") || strings.HasPrefix(dll, "ext_") {
				arg = strings.Replace(arg, "_", "-", -1)
			}
			switch pkgtype {
			case pkgStd:
				return syscalldot() + "NewLazyDLL(sysdll.Add(" + arg + "))"
			case pkgXSysWindows:
				return "NewLazySystemDLL(" + arg + ")"
			default:
				return "windows.NewLazySystemDLL(" + arg + ")"
			}
		},
	}
	t := template.Must(template.New("main").Funcs(funcMap).Parse(srcTemplate))
	err = t.Execute(w, src)
	if err != nil {
		return errors.New("Failed to execute template: " + err.Error())
	}
	return nil
}
985708
func (s *Server) Generate() error {
	s.Resources = getAllResources(s.APIDef, true)

	if err := generateAllObjects(s.APIDef, s.Dir); err != nil {
		return err
	}

	// main file
	if err := s.generateMain(); err != nil {
		return err
	}

	// API implementation
	if err := generateResourceAPIs(s.Resources, s.Dir); err != nil {
		return err
	}

	// security related files
	if err := s.generateSecurity(); err != nil {
		return err
	}

	// HTML front page
	if err := commons.GenerateFile(s, "./templates/index.html.tmpl", "index.html", filepath.Join(s.Dir, "index.html"), false); err != nil {
		return err
	}

	return nil
}
855262
func (r *resource) generate(dir string) error {
	filename := filepath.Join(dir, r.apiName()+".nim")
	return commons.GenerateFile(r, "./templates/nim/server_resources_api_nim.tmpl", "server_resources_api_nim", filename, true)
}
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
}
779465
func (sr *Strrand) Generate(pattern string) (string, error) {
	result := ""
	g, err := sr.CreateGenerator(pattern)
	if err != nil {
		return result, err
	}
	return g.Generate(), nil
}
1299881
func (s *CassandraSource) Generate(f *flow.Flow) *flow.Dataset {
	return s.genShardInfos(f).RoundRobin(s.prefix, s.Concurrency).Map(s.prefix+".Read", MapperReadShard)
}
1275320
func (ps *pythonSecurity) generate(dir string) error {
	filename := filepath.Join(dir, ps.FileName)
	return commons.GenerateFile(ps, ps.template, ps.templateName, filename, true)
}
816497
func (c *cache) generate(dir string, limit int, test bool) {
	c.once.Do(func() {
		size := cacheSize(c.epoch*epochLength + 1)
		seed := seedHash(c.epoch*epochLength + 1)
		if test {
			size = 1024
		}
		// If we don't store anything on disk, generate and return.
		if dir == "" {
			c.cache = make([]uint32, size/4)
			generateCache(c.cache, c.epoch, seed)
			return
		}
		// Disk storage is needed, this will get fancy
		var endian string
		if !isLittleEndian() {
			endian = ".be"
		}
		path := filepath.Join(dir, fmt.Sprintf("cache-R%d-%x%s", algorithmRevision, seed[:8], endian))
		logger := log.New("epoch", c.epoch)

		// We're about to mmap the file, ensure that the mapping is cleaned up when the
		// cache becomes unused.
		runtime.SetFinalizer(c, (*cache).finalizer)

		// Try to load the file from disk and memory map it
		var err error
		c.dump, c.mmap, c.cache, err = memoryMap(path)
		if err == nil {
			logger.Debug("Loaded old ethash cache from disk")
			return
		}
		logger.Debug("Failed to load old ethash cache", "err", err)

		// No previous cache available, create a new cache file to fill
		c.dump, c.mmap, c.cache, err = memoryMapAndGenerate(path, size, func(buffer []uint32) { generateCache(buffer, c.epoch, seed) })
		if err != nil {
			logger.Error("Failed to generate mapped ethash cache", "err", err)

			c.cache = make([]uint32, size/4)
			generateCache(c.cache, c.epoch, seed)
		}
		// Iterate over all previous instances and delete old ones
		for ep := int(c.epoch) - limit; ep >= 0; ep-- {
			seed := seedHash(uint64(ep)*epochLength + 1)
			path := filepath.Join(dir, fmt.Sprintf("cache-R%d-%x%s", algorithmRevision, seed[:8], endian))
			os.Remove(path)
		}
	})
}
272933
func (t *Token) Generate() (bool, error) {
	if t.AuthKey == nil {
		return false, ErrAuthKeyNil
	}
	issuedAt := time.Now().Unix()
	jwtToken := &jwt.Token{
		Header: map[string]interface{}{
			"alg": "ES256",
			"kid": t.KeyID,
		},
		Claims: jwt.MapClaims{
			"iss": t.TeamID,
			"iat": issuedAt,
		},
		Method: jwt.SigningMethodES256,
	}
	bearer, err := jwtToken.SignedString(t.AuthKey)
	if err != nil {
		return false, err
	}
	t.IssuedAt = issuedAt
	t.Bearer = bearer
	return true, 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)
}
611259
func Generate(length, numDigits, numSymbols int, noUpper, allowRepeat bool) (string, error) {
	gen, err := NewGenerator(nil)
	if err != nil {
		return "", err
	}

	return gen.Generate(length, numDigits, numSymbols, noUpper, allowRepeat)
}
636521
func (s *FileSource) Generate(f *flow.Flow) *flow.Dataset {
	return s.genShardInfos(f).RoundRobin(s.prefix, s.PartitionCount).Map(s.prefix+".Read", registeredMapperReadShard)
}
778982
func (gs *Server) Generate() error {
	if err := commons.CheckDuplicatedTitleTypes(gs.apiDef); err != nil {
		return err
	}
	if gs.RootImportPath == "" {
		return fmt.Errorf("invalid import path = empty. please set --import-path or set target dir under gopath")
	}
	// helper package
	gh := goramlHelper{
		rootImportPath: gs.RootImportPath,
		packageName:    "goraml",
		packageDir:     "goraml",
	}
	if err := gh.generate(gs.TargetDir); err != nil {
		return err
	}

	if err := generateAllStructs(gs.apiDef, gs.TargetDir); err != nil {
		return err
	}

	// security scheme
	if err := generateSecurity(gs.apiDef.SecuritySchemes, gs.TargetDir, gs.PackageName); err != nil {
		log.Errorf("failed to generate security scheme:%v", err)
		return err
	}

	// genereate resources
	rds, err := gs.generateServerResources(gs.TargetDir)
	if err != nil {
		return err
	}
	gs.ResourcesDef = rds

	// libraries
	if err := generateLibraries(gs.apiDef.Libraries, gs.TargetDir, gs.libsRootURLs); err != nil {
		return err
	}

	// routes
	if err := commons.GenerateFile(gs, "./templates/golang/server_routes.tmpl", "server_routes", filepath.Join(gs.TargetDir, "routes.go"), true); err != nil {
		return err
	}

	// generate main
	if gs.withMain {
		// HTML front page
		if err := commons.GenerateFile(gs, "./templates/index.html.tmpl", "index.html", filepath.Join(gs.TargetDir, "index.html"), false); err != nil {
			return err
		}
		// main file
		return commons.GenerateFile(gs, "./templates/golang/server_main_go.tmpl", "server_main_go", filepath.Join(gs.TargetDir, "main.go"), true)
	}

	return nil
}
614264
func (w *Wrapper) Generate() error {
	if !w.initCalled {
		return errors.New("Init() must be called before Generate()")
	}
	if w.Parallelism < 1 {
		return fmt.Errorf("parallelism cannot be < 1; got %d", w.Parallelism)
	}
	parallelism := len(w.packages)
	if w.Parallelism < parallelism {
		parallelism = w.Parallelism
	}

	pkgChan := make(chan *PackageInfo)

	errChan := make(chan error, parallelism)
	var wg sync.WaitGroup
	wg.Add(parallelism)
	for i := 0; i < parallelism; i++ {
		go func() {
			for pkg := range pkgChan {
				fmt.Printf("Generating package %s\n", pkg.ComputedPackage)
				if err := Generate(pkg, w.ImportDirs, w.ProtocCommand, w.ProtocFlags, w.PrintOnly); err != nil {
					errChan <- fmt.Errorf("error generating package %s: %v\n", pkg.ComputedPackage, err)
				}
			}
			wg.Done()
		}()
	}

	var err error
OUTER:
	for _, pkg := range w.packagesInOrder() {
		select {
		case pkgChan <- pkg:
		case err = <-errChan:
			break OUTER
		}
	}
	close(pkgChan)
	wg.Wait()
	select {
	case err = <-errChan:
	default:
	}
	return err
}
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
}