// tested via the ccv2.buildpack_test.go file at this point
967361
func CalculateRequestSize(buildpackSize int64, bpPath string, fieldName string) (int64, error) {
	body := &bytes.Buffer{}
	form := multipart.NewWriter(body)

	bpFileName := filepath.Base(bpPath)

	_, err := form.CreateFormFile(fieldName, bpFileName)
	if err != nil {
		return 0, err
	}

	err = form.Close()
	if err != nil {
		return 0, err
	}

	return int64(body.Len()) + buildpackSize, nil
}
1119726
func (b *Builder) typeCheckPackage(pkgPath importPathString) (*tc.Package, error) {
	klog.V(5).Infof("typeCheckPackage %s", pkgPath)
	if pkg, ok := b.typeCheckedPackages[pkgPath]; ok {
		if pkg != nil {
			klog.V(6).Infof("typeCheckPackage %s already done", pkgPath)
			return pkg, nil
		}
		// We store a nil right before starting work on a package. So
		// if we get here and it's present and nil, that means there's
		// another invocation of this function on the call stack
		// already processing this package.
		return nil, fmt.Errorf("circular dependency for %q", pkgPath)
	}
	parsedFiles, ok := b.parsed[pkgPath]
	if !ok {
		return nil, fmt.Errorf("No files for pkg %q", pkgPath)
	}
	files := make([]*ast.File, len(parsedFiles))
	for i := range parsedFiles {
		files[i] = parsedFiles[i].file
	}
	b.typeCheckedPackages[pkgPath] = nil
	c := tc.Config{
		IgnoreFuncBodies: true,
		// Note that importAdapter can call b.importPackage which calls this
		// method. So there can't be cycles in the import graph.
		Importer: importAdapter{b},
		Error: func(err error) {
			klog.V(2).Infof("type checker: %v\n", err)
		},
	}
	pkg, err := c.Check(string(pkgPath), b.fset, files, nil)
	b.typeCheckedPackages[pkgPath] = pkg // record the result whether or not there was an error
	return pkg, err
}
303825
func (g *GopathTest) In(pkg string) {
	g.pkg = pkg
	p := g.Path(pkg)
	err := os.Chdir(p)
	if err != nil {
		g.Fatal(err)
	}
	g.current = p
}
1028645
func computeDoc(bpkg *build.Package) (*doc.Package, error) {
	fset := token.NewFileSet()
	files := make(map[string]*ast.File)
	for _, file := range append(bpkg.GoFiles, bpkg.CgoFiles...) {
		f, err := parser.ParseFile(fset, filepath.Join(bpkg.Dir, file), nil, parser.ParseComments)
		if err != nil {
			return nil, err
		}
		files[file] = f
	}
	apkg := &ast.Package{
		Name:  bpkg.Name,
		Files: files,
	}
	return doc.New(apkg, bpkg.ImportPath, 0), nil
}
729136
func (actor Actor) GetBuildpackByNameAndStack(buildpackName string, buildpackStack string) (Buildpack, Warnings, error) {
	var (
		ccv3Buildpacks []ccv3.Buildpack
		warnings       ccv3.Warnings
		err            error
	)

	if buildpackStack == "" {
		ccv3Buildpacks, warnings, err = actor.CloudControllerClient.GetBuildpacks(ccv3.Query{
			Key:    ccv3.NameFilter,
			Values: []string{buildpackName},
		})
	} else {
		ccv3Buildpacks, warnings, err = actor.CloudControllerClient.GetBuildpacks(
			ccv3.Query{
				Key:    ccv3.NameFilter,
				Values: []string{buildpackName},
			},
			ccv3.Query{
				Key:    ccv3.StackFilter,
				Values: []string{buildpackStack},
			},
		)
	}

	if err != nil {
		return Buildpack{}, Warnings(warnings), err
	}

	if len(ccv3Buildpacks) == 0 {
		return Buildpack{}, Warnings(warnings), actionerror.BuildpackNotFoundError{BuildpackName: buildpackName, StackName: buildpackStack}
	}

	if len(ccv3Buildpacks) > 1 {
		for _, buildpack := range ccv3Buildpacks {
			if buildpack.Stack == "" {
				return Buildpack(buildpack), Warnings(warnings), nil
			}
		}
		return Buildpack{}, Warnings(warnings), actionerror.MultipleBuildpacksFoundError{BuildpackName: buildpackName}
	}

	return Buildpack(ccv3Buildpacks[0]), Warnings(warnings), err
}
944620
func GetChaincodePackageFromPath(ccname string, ccversion string, ccInstallPath string) ([]byte, error) {
	path := fmt.Sprintf("%s/%s.%s", ccInstallPath, ccname, ccversion)
	var ccbytes []byte
	var err error
	if ccbytes, err = ioutil.ReadFile(path); err != nil {
		return nil, err
	}
	return ccbytes, 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)
}
840873
func chaincodePackage(cmd *cobra.Command, args []string, cdsFact ccDepSpecFactory, cf *ChaincodeCmdFactory) error {
	if cdsFact == nil {
		return fmt.Errorf("Error chaincode deployment spec factory not specified")
	}
	// Parsing of the command line is done so silence cmd usage
	cmd.SilenceUsage = true

	var err error
	if cf == nil {
		cf, err = InitCmdFactory(cmd.Name(), false, false)
		if err != nil {
			return err
		}
	}
	spec, err := getChaincodeSpec(cmd)
	if err != nil {
		return err
	}

	cds, err := cdsFact(spec)
	if err != nil {
		return fmt.Errorf("error getting chaincode code %s: %s", chaincodeName, err)
	}

	var bytesToWrite []byte
	if createSignedCCDepSpec {
		bytesToWrite, err = getChaincodeInstallPackage(cds, cf)
		if err != nil {
			return err
		}
	} else {
		bytesToWrite = utils.MarshalOrPanic(cds)
	}

	logger.Debugf("Packaged chaincode into deployment spec of size <%d>, with args = %v", len(bytesToWrite), args)
	fileToWrite := args[0]
	err = ioutil.WriteFile(fileToWrite, bytesToWrite, 0700)
	if err != nil {
		logger.Errorf("failed writing deployment spec to file [%s]: [%s]", fileToWrite, err)
		return err
	}

	return err
}
572977
func (l *Loader) Build(baseDir vfs.Path) (map[string]fi.Task, error) {
	// First pass: load options
	tw := &loader.TreeWalker{
		DefaultHandler: ignoreHandler,
		Contexts: map[string]loader.Handler{
			"files":    ignoreHandler,
			"disks":    ignoreHandler,
			"packages": ignoreHandler,
			"services": ignoreHandler,
			"users":    ignoreHandler,
		},
		Tags: l.tags,
	}

	err := tw.Walk(baseDir)
	if err != nil {
		return nil, err
	}

	// Second pass: load everything else
	tw = &loader.TreeWalker{
		DefaultHandler: l.handleFile,
		Contexts: map[string]loader.Handler{
			"files":    l.handleFile,
			"disks":    l.newTaskHandler("disk/", nodetasks.NewMountDiskTask),
			"packages": l.newTaskHandler("package/", nodetasks.NewPackage),
			"services": l.newTaskHandler("service/", nodetasks.NewService),
			"users":    l.newTaskHandler("user/", nodetasks.NewUserTask),
		},
		Tags: l.tags,
	}

	err = tw.Walk(baseDir)
	if err != nil {
		return nil, err
	}

	for _, builder := range l.Builders {
		context := &fi.ModelBuilderContext{
			Tasks: l.tasks,
		}
		err := builder.Build(context)
		if err != nil {
			return nil, err
		}
		l.tasks = context.Tasks
	}

	// If there is a package task, we need an update packages task
	for _, t := range l.tasks {
		if _, ok := t.(*nodetasks.Package); ok {
			glog.Infof("Package task found; adding UpdatePackages task")
			l.tasks["UpdatePackages"] = nodetasks.NewUpdatePackages()
			break
		}
	}
	if l.tasks["UpdatePackages"] == nil {
		glog.Infof("No package task found; won't update packages")
	}

	return l.tasks, nil
}
536170
func CurrentPackage() string {
	for _, root := range gobuild.Default.SrcDirs() {
		if pkg, ok := hasSubdir(root, "."); ok {
			return pkg
		}
	}
	return ""
}
583016
func main() {
	var (
		lintArgs       string
		lintBin        string
		packageList    string
		output         string
		packages       []string
		results        []*result
		hasFailingTest bool

		gopath = os.Getenv("GOPATH")
	)

	flag.StringVar(&lintArgs, "lintArgs", "", "args to pass to gometalinter")
	flag.StringVar(&lintBin, "lintBin", filepath.Join(gopath, "bin", "gometalinter"), "path to go metalinter")
	flag.StringVar(&packageList, "packages", "", "list of space separated packages")
	flag.StringVar(&output, "output", "", "output file for to write results.")
	flag.Parse()

	packages = strings.Split(strings.Replace(packageList, "-", "/", -1), " ")
	dirname, _ := os.Getwd()
	cwd := filepath.Base(dirname)
	gopath, _ = filepath.Abs(gopath)
	lintArgs += fmt.Sprintf(" --concurrency=%d", runtime.NumCPU()/2)

	for _, pkg := range packages {
		args := []string{lintBin, lintArgs}
		if cwd == pkg {
			args = append(args, ".")
		} else {
			args = append(args, "./"+pkg)
		}

		startAt := time.Now()
		cmd := strings.Join(args, " ")
		out, err := exec.Command("sh", "-c", cmd).CombinedOutput()

		r := &result{
			cmd:      strings.Join(args, " "),
			name:     "lint-" + strings.Replace(pkg, "/", "-", -1),
			passed:   err == nil,
			duration: time.Since(startAt),
			output:   strings.Split(string(out), "\n"),
		}
		r.fixup(dirname)

		if !r.passed {
			hasFailingTest = true
		}

		results = append(results, r)
		fmt.Println(r)
	}

	if output != "" {
		f, err := os.Create(output)
		if err != nil {
			os.Exit(1)
		}
		defer func() {
			if err != f.Close() {
				panic(err)
			}
		}()

		for _, r := range results {
			f.WriteString(r.String() + "\n")
		}
	}

	if hasFailingTest {
		os.Exit(1)
	}
}
463743
func GetCCPackage(buf []byte) (CCPackage, error) {
	// try raw CDS
	cds := &CDSPackage{}
	if ccdata, err := cds.InitFromBuffer(buf); err != nil {
		cds = nil
	} else {
		err = cds.ValidateCC(ccdata)
		if err != nil {
			cds = nil
		}
	}

	// try signed CDS
	scds := &SignedCDSPackage{}
	if ccdata, err := scds.InitFromBuffer(buf); err != nil {
		scds = nil
	} else {
		err = scds.ValidateCC(ccdata)
		if err != nil {
			scds = nil
		}
	}

	if cds != nil && scds != nil {
		// Both were unmarshaled successfully, this is exactly why the approach of
		// hoping proto fails for bad inputs is fatally flawed.
		ccproviderLogger.Errorf("Could not determine chaincode package type, guessing SignedCDS")
		return scds, nil
	}

	if cds != nil {
		return cds, nil
	}

	if scds != nil {
		return scds, nil
	}

	return nil, errors.New("could not unmarshal chaincode package to CDS or SignedCDS")
}
975127
func (m *MockDebugInfo) EnableDatapathPacketTracing(contextID string, direction packettracing.TracingDirection, interval time.Duration, putype common.PUType) error {
	ret := m.ctrl.Call(m, "EnableDatapathPacketTracing", contextID, direction, interval, putype)
	ret0, _ := ret[0].(error)
	return ret0
}
620051
func (_m *APIClient) BuildCachePrune(ctx context.Context, opts types.BuildCachePruneOptions) (*types.BuildCachePruneReport, error) {
	ret := _m.Called(ctx, opts)

	var r0 *types.BuildCachePruneReport
	if rf, ok := ret.Get(0).(func(context.Context, types.BuildCachePruneOptions) *types.BuildCachePruneReport); ok {
		r0 = rf(ctx, opts)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(*types.BuildCachePruneReport)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(context.Context, types.BuildCachePruneOptions) error); ok {
		r1 = rf(ctx, opts)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}
618678
func (ccpack *CDSPackage) GetDepSpec() *pb.ChaincodeDeploymentSpec {
	//this has to be after creating a package and initializing it
	//If those steps fail, GetDepSpec() should never be called
	if ccpack.depSpec == nil {
		panic("GetDepSpec called on uninitialized package")
	}
	return ccpack.depSpec
}
783199
func build_package(p *build.Package) error {
	if *g_debug {
		log.Printf("-------------------")
		log.Printf("rebuilding package %s", p.Name)
		log.Printf("package import: %s", p.ImportPath)
		log.Printf("package object: %s", p.PkgObj)
		log.Printf("package source dir: %s", p.Dir)
		log.Printf("package source files: %v", p.GoFiles)
		log.Printf("GOPATH: %v", g_daemon.context.GOPATH)
		log.Printf("GOROOT: %v", g_daemon.context.GOROOT)
	}
	env := os.Environ()
	for i, v := range env {
		if strings.HasPrefix(v, "GOPATH=") {
			env[i] = "GOPATH=" + g_daemon.context.GOPATH
		} else if strings.HasPrefix(v, "GOROOT=") {
			env[i] = "GOROOT=" + g_daemon.context.GOROOT
		}
	}

	cmd := exec.Command("go", "install", p.ImportPath)
	cmd.Env = env

	// TODO: Should read STDERR rather than STDOUT.
	out, err := cmd.CombinedOutput()
	if err != nil {
		return err
	}
	if *g_debug {
		log.Printf("build out: %s\n", string(out))
	}
	return nil
}
607923
func (application Application) CalculatedBuildpack() string {
	if application.Buildpack.IsSet {
		return application.Buildpack.Value
	}

	return application.DetectedBuildpack.Value
}