// BuildDirect is a helper that looks like the regular zk create function
199824
func (b *Builder) BuildDirect() (*ZkPlus, <-chan zk.Event, error) {
	z, err := b.Build()
	if err != nil {
		return nil, nil, errors.Annotate(err, "cannot build zk connection")
	}
	return z, z.EventChan(), nil
}
958596
func AutoBuild(files []string, isgenerate bool) {
	state.Lock()
	defer state.Unlock()

	os.Chdir(currpath)

	cmdName := "go"

	var (
		err    error
		stderr bytes.Buffer
	)
	// For applications use full import path like "github.com/.../.."
	// are able to use "go install" to reduce build time.
	if config.Conf.GoInstall {
		icmd := exec.Command(cmdName, "install", "-v")
		icmd.Stdout = os.Stdout
		icmd.Stderr = os.Stderr
		icmd.Env = append(os.Environ(), "GOGC=off")
		icmd.Run()
	}

	if isgenerate {
		beeLogger.Log.Info("Generating the docs...")
		icmd := exec.Command("bee", "generate", "docs")
		icmd.Env = append(os.Environ(), "GOGC=off")
		err = icmd.Run()
		if err != nil {
			utils.Notify("", "Failed to generate the docs.")
			beeLogger.Log.Errorf("Failed to generate the docs.")
			return
		}
		beeLogger.Log.Success("Docs generated!")
	}
	appName := appname
	if err == nil {

		if runtime.GOOS == "windows" {
			appName += ".exe"
		}

		args := []string{"build"}
		args = append(args, "-o", appName)
		if buildTags != "" {
			args = append(args, "-tags", buildTags)
		}
		args = append(args, files...)

		bcmd := exec.Command(cmdName, args...)
		bcmd.Env = append(os.Environ(), "GOGC=off")
		bcmd.Stderr = &stderr
		err = bcmd.Run()
		if err != nil {
			utils.Notify(stderr.String(), "Build Failed")
			beeLogger.Log.Errorf("Failed to build the application: %s", stderr.String())
			return
		}
	}

	beeLogger.Log.Success("Built Successfully!")
	Restart(appName)
}
1071694
func Build(path, IP, hostname, domainname string, extraContent []Record) error {
	defer pathLock(path)()

	content := bytes.NewBuffer(nil)
	if IP != "" {
		//set main record
		var mainRec Record
		mainRec.IP = IP
		// User might have provided a FQDN in hostname or split it across hostname
		// and domainname.  We want the FQDN and the bare hostname.
		fqdn := hostname
		if domainname != "" {
			fqdn = fmt.Sprintf("%s.%s", fqdn, domainname)
		}
		parts := strings.SplitN(fqdn, ".", 2)
		if len(parts) == 2 {
			mainRec.Hosts = fmt.Sprintf("%s %s", fqdn, parts[0])
		} else {
			mainRec.Hosts = fqdn
		}
		if _, err := mainRec.WriteTo(content); err != nil {
			return err
		}
	}
	// Write defaultContent slice to buffer
	for _, r := range defaultContent {
		if _, err := r.WriteTo(content); err != nil {
			return err
		}
	}
	// Write extra content from function arguments
	for _, r := range extraContent {
		if _, err := r.WriteTo(content); err != nil {
			return err
		}
	}

	return ioutil.WriteFile(path, content.Bytes(), 0644)
}
382700
func (db *Database) buildCreate() string {
	var query bytes.Buffer
	query.WriteString(db.buildCTE())
	query.WriteString("INSERT INTO ")

	// Model only
	if len(db.tables) != 1 {
		db.panicLog(fmt.Sprintf("Unable to infer table name for Create. Number of tables: %d", len(db.tables)))
	}
	// Table (
	query.WriteString(db.tables[0])
	query.WriteString("(")

	// field1,file2,...
	createSize := len(db.updateCreateFields)
	if createSize == 0 {
		db.panicLog("Unable to detect fields for Create")
	}

	query.WriteString(strings.Join(db.updateCreateFields, ","))
	// values($1,..$n) place holders
	query.WriteString(") VALUES (")
	for i := 0; i < createSize; i++ {
		query.WriteString("$")
		query.WriteString(strconv.Itoa(db.varCount))
		db.varCount++
		if i != createSize-1 {
			query.WriteString(",")
		}
	}

	query.WriteString(") ")
	query.WriteString(db.buildReturning())
	query.WriteString(";")

	qs := query.String()
	db.printLog(qs)
	return qs
}
1065472
func createEnvoyRedirect(r *Redirect, stateDir string, xdsServer *envoy.XDSServer, wg *completion.WaitGroup) (RedirectImplementation, error) {
	envoyOnce.Do(func() {
		// Start Envoy on first invocation
		envoyProxy = envoy.StartEnvoy(stateDir, option.Config.EnvoyLogPath, 0)
	})

	l := r.listener
	if envoyProxy != nil {
		redir := &envoyRedirect{
			listenerName: fmt.Sprintf("%s:%d", l.name, l.proxyPort),
			xdsServer:    xdsServer,
		}

		xdsServer.AddListener(redir.listenerName, l.parserType, l.proxyPort, l.ingress, wg)

		return redir, nil
	}

	return nil, fmt.Errorf("%s: Envoy proxy process failed to start, cannot add redirect", l.name)
}
397877
func createGenerateStruct(apiDef *raml.APIDefinition, tip, dir, pkgName string) (string, error) {
	rt := raml.Type{
		Type: tip,
	}
	if parents, isMultiple := rt.MultipleInheritance(); isMultiple {
		sd := newStructDef(apiDef, multipleInheritanceNewName(parents), pkgName, "", map[string]interface{}{})
		sd.addMultipleInheritance(apiDef, parents)
		return sd.Name, sd.generate(dir)
	}

	if rt.IsUnion() {
		t := raml.Type{
			Type: tip,
		}
		sd := newStructDef(apiDef, unionNewName(tip), pkgName, "", map[string]interface{}{})
		sd.T = t
		sd.buildUnion()
		sd.generate(dir)
	}
	return "", nil
}
1235991
func (s *Service) BuildCreate(ctx context.Context, appIdentity string, o BuildCreateOpts) (*Build, error) {
	var build Build
	return &build, s.Post(ctx, &build, fmt.Sprintf("/apps/%v/builds", appIdentity), o)
}
671384
func (b *Builder) Build(images []*Image) error {
	builds := make(map[string]*Build, len(images))
	for _, image := range images {
		builds[image.ID] = NewBuild(image)
	}

	addDependency := func(build *Build, dependsOn string) error {
		dep, ok := builds[dependsOn]
		if !ok {
			return fmt.Errorf("unknown image dependency: %s -> %s", build.Image.ID, dependsOn)
		}
		build.AddDependency(dep)
		dep.AddDependent(build)
		return nil
	}

	for _, build := range builds {
		image := build.Image

		// determine build dependencies
		// TODO: check for circular dependencies
		if image.Base != "" {
			addDependency(build, image.Base)
		}
		for _, l := range image.Layers {
			// build Go binaries using the Go image
			if l.BuildWith == "" && (len(l.GoBuild) > 0 || len(l.CGoBuild) > 0) {
				l.BuildWith = "go"
			}
			if l.BuildWith != "" {
				addDependency(build, l.BuildWith)
			}
		}
	}

	// build images until there are no pending builds left
	done := make(chan *Build, len(builds))
	failures := make(map[string]error)
	for len(builds) > 0 {
		for _, build := range builds {
			// if the build has no more pending dependencies, build it
			if len(build.Dependencies) == 0 {
				build.Once.Do(func() {
					// if the build is aborted due to a dependency
					// failure, just send it to the done channel
					if build.Abort {
						b.log.Debug(fmt.Sprintf("%s build abort", build.Image.ID))
						done <- build
						return
					}

					b.log.Debug(fmt.Sprintf("%s build start", build.Image.ID))
					go func(build *Build) {
						build.StartedAt = time.Now()
						build.Err = b.BuildImage(build.Image)
						done <- build
					}(build)
				})
			}
		}

		// wait for a build to finish
		build := <-done
		b.bar.Increment()
		if build.Err == nil {
			b.log.Debug(fmt.Sprintf("%s build done", build.Image.ID), "duration", time.Since(build.StartedAt))
		} else {
			b.log.Error(fmt.Sprintf("%s build error", build.Image.ID), "duration", time.Since(build.StartedAt), "err", build.Err)
		}

		// remove from the pending list
		delete(builds, build.Image.ID)

		// remove the build as a pending dependency from all
		// dependents
		for dependent := range build.Dependents {
			// if the build failed or was aborted, abort the
			// dependent builds
			if build.Err != nil || build.Abort {
				dependent.Abort = true
			}
			dependent.RemoveDependency(build)
		}

		if build.Err != nil {
			failures[build.Image.ID] = build.Err
		}
	}

	if len(failures) > 0 {
		b.log.Error("the following builds failed:")
		for id, err := range failures {
			b.log.Error("* "+id, "err", err)
		}
		return fmt.Errorf("%d builds failed", len(failures))
	}

	return nil
}
609631
func (collector *clientInterceptorBuilder) Build() []grpc.DialOption {
	switch len(collector.unaryInterceptors) + len(collector.streamInterceptors) {
	case 0:
		return []grpc.DialOption{}
	default:
		return []grpc.DialOption{
			grpc.WithUnaryInterceptor(grpc_middleware.ChainUnaryClient(collector.unaryInterceptors...)),
			grpc.WithStreamInterceptor(grpc_middleware.ChainStreamClient(collector.streamInterceptors...)),
		}
	}
}
521190
func (f FileManager) MakeDirectory(ctx context.Context, name string, dc *Datacenter, createParentDirectories bool) error {
	req := types.MakeDirectory{
		This:                    f.Reference(),
		Name:                    name,
		CreateParentDirectories: types.NewBool(createParentDirectories),
	}

	if dc != nil {
		ref := dc.Reference()
		req.Datacenter = &ref
	}

	_, err := methods.MakeDirectory(ctx, f.c, &req)
	return err
}
506068
func makeBuild(params httprouter.Params, build *ui.MiloBuildLegacy) *buildbucketpb.Build {
	return &buildbucketpb.Build{
		Builder: &buildbucketpb.BuilderID{
			Project: build.Trigger.Project,           // equivalent params.ByName("project")
			Bucket:  params.ByName("bucket"),         // way to get from ui.MiloBuildLegacy so don't need params here?
			Builder: build.Summary.ParentLabel.Label, // params.ByName("builder")
		},
	}
}
63510
func (b *Builder) BuildZip(folder string) error {
	w := zip.NewWriter(b.Content)
	defer w.Close()

	if err := b.generateKeyIfNeeded(); err != nil {
		return err
	}

	keyFile, err := w.Create(keyFilename)
	if err != nil {
		return err
	}

	size, err := b.saveKeyFile(keyFile)
	if err != nil {
		return err
	}

	fmt.Printf("Included %q %s\n", keyFilename, humanize.Bytes(uint64(size)))

	return filepath.Walk(folder, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}

		filename, _ := filepath.Rel(folder, path)
		if info.IsDir() {
			return nil
		}

		header, err := zip.FileInfoHeader(info)
		if err != nil {
			return err
		}

		header.Name = filename
		dst, err := w.CreateHeader(header)
		if err != nil {
			return err
		}

		src, err := os.Open(path)
		if err != nil {
			return err
		}

		bytes, err := io.Copy(dst, src)
		if err != nil {
			return err
		}

		fmt.Printf("Included %q %s\n", filename, humanize.Bytes(uint64(bytes)))
		return nil
	})
}
134683
func (s *scheduler) build(ctx context.Context, edge Edge) (CachedResult, error) {
	s.mu.Lock()
	e := s.ef.getEdge(edge)
	if e == nil {
		s.mu.Unlock()
		return nil, errors.Errorf("invalid request %v for build", edge)
	}

	wait := make(chan struct{})

	var p *pipe.Pipe
	p = s.newPipe(e, nil, pipe.Request{Payload: &edgeRequest{desiredState: edgeStatusComplete}})
	p.OnSendCompletion = func() {
		p.Receiver.Receive()
		if p.Receiver.Status().Completed {
			close(wait)
		}
	}
	s.mu.Unlock()

	ctx, cancel := context.WithCancel(ctx)
	defer cancel()

	go func() {
		<-ctx.Done()
		p.Receiver.Cancel()
	}()

	<-wait

	if err := p.Receiver.Status().Err; err != nil {
		return nil, err
	}
	return p.Receiver.Status().Value.(*edgeState).result.Clone(), nil
}
964256
func BuildsCreate(appID, image, procfile string) error {
	c, appID, err := load(appID)

	if err != nil {
		return err
	}

	procfileMap := make(map[string]string)

	if procfile != "" {
		if procfileMap, err = parseProcfile([]byte(procfile)); err != nil {
			return err
		}
	} else if _, err := os.Stat("Procfile"); err == nil {
		contents, err := ioutil.ReadFile("Procfile")
		if err != nil {
			return err
		}

		if procfileMap, err = parseProcfile(contents); err != nil {
			return err
		}
	}

	fmt.Print("Creating build... ")
	quit := progress()
	_, err = builds.New(c, appID, image, procfileMap)
	quit <- true
	<-quit

	if err != nil {
		return err
	}

	fmt.Println("done")

	return nil
}
966060
func (b *Builder) Build() (*FileSorter, error) {
	// Sanity checks
	if b.sc == nil {
		return nil, errors.New("StatementContext is nil")
	}
	if b.keySize != len(b.byDesc) {
		return nil, errors.New("mismatch in key size and byDesc slice")
	}
	if b.keySize <= 0 {
		return nil, errors.New("key size is not positive")
	}
	if b.valSize <= 0 {
		return nil, errors.New("value size is not positive")
	}
	if b.bufSize <= 0 {
		return nil, errors.New("buffer size is not positive")
	}
	_, err := os.Stat(b.tmpDir)
	if err != nil {
		if os.IsNotExist(err) {
			return nil, errors.New("tmpDir does not exist")
		}
		return nil, errors.Trace(err)
	}

	rh := &rowHeap{sc: b.sc,
		ims:    make([]*item, 0),
		byDesc: b.byDesc,
	}

	return &FileSorter{sc: b.sc,
		keySize: b.keySize,
		valSize: b.valSize,
		bufSize: b.bufSize,
		buf:     make([]*comparableRow, 0, b.bufSize),
		files:   make([]string, 0),
		byDesc:  b.byDesc,
		rowHeap: rh,
		tmpDir:  b.tmpDir,
		fds:     make([]*os.File, 0),
	}, nil
}
750352
func MakeBuildKey(c context.Context, host, buildAddress string) *datastore.Key {
	return datastore.MakeKey(c,
		"buildbucket.Build", fmt.Sprintf("%s:%s", host, buildAddress))
}
635160
func (mount *MountInfo) MakeDir(path string, mode uint32) error {
	cPath := C.CString(path)
	defer C.free(unsafe.Pointer(cPath))

	ret := C.ceph_mkdir(mount.mount, cPath, C.mode_t(mode))
	if ret != 0 {
		log.Errorf("MakeDir: Failed to make directory %s", path)
		return cephError(ret)
	}
	return nil
}