github.com/cloudfoundry-community/cloudfoundry-cli@v6.44.1-0.20240130060226-cda5ed8e89a5+incompatible/api/cloudcontroller/buildpacks/upload.go (about)

     1  package buildpacks
     2  
     3  import (
     4  	"bytes"
     5  	"io"
     6  	"mime/multipart"
     7  	"path/filepath"
     8  
     9  	"code.cloudfoundry.org/cli/api/cloudcontroller"
    10  )
    11  
    12  // tested via the ccv2.buildpack_test.go file at this point
    13  
    14  func CalculateRequestSize(buildpackSize int64, bpPath string, fieldName string) (int64, error) {
    15  	body := &bytes.Buffer{}
    16  	form := multipart.NewWriter(body)
    17  
    18  	bpFileName := filepath.Base(bpPath)
    19  
    20  	_, err := form.CreateFormFile(fieldName, bpFileName)
    21  	if err != nil {
    22  		return 0, err
    23  	}
    24  
    25  	err = form.Close()
    26  	if err != nil {
    27  		return 0, err
    28  	}
    29  
    30  	return int64(body.Len()) + buildpackSize, nil
    31  }
    32  
    33  func CreateMultipartBodyAndHeader(buildpack io.Reader, bpPath string, fieldName string) (string, io.ReadSeeker, <-chan error) {
    34  	writerOutput, writerInput := cloudcontroller.NewPipeBomb()
    35  
    36  	form := multipart.NewWriter(writerInput)
    37  
    38  	writeErrors := make(chan error)
    39  
    40  	go func() {
    41  		defer close(writeErrors)
    42  		defer writerInput.Close()
    43  
    44  		bpFileName := filepath.Base(bpPath)
    45  		writer, err := form.CreateFormFile(fieldName, bpFileName)
    46  		if err != nil {
    47  			writeErrors <- err
    48  			return
    49  		}
    50  
    51  		_, err = io.Copy(writer, buildpack)
    52  		if err != nil {
    53  			writeErrors <- err
    54  			return
    55  		}
    56  
    57  		err = form.Close()
    58  		if err != nil {
    59  			writeErrors <- err
    60  		}
    61  	}()
    62  
    63  	return form.FormDataContentType(), writerOutput, writeErrors
    64  }