github.com/discordapp/buildkite-agent@v2.6.6+incompatible/api/pipelines.go (about) 1 package api 2 3 import ( 4 "bytes" 5 "fmt" 6 "mime/multipart" 7 "path/filepath" 8 9 "github.com/buildkite/agent/mime" 10 ) 11 12 // PipelinesService handles communication with the pipeline related methods of the 13 // Buildkite Agent API. 14 type PipelinesService struct { 15 client *Client 16 } 17 18 // Pipeline represents a Buildkite Agent API Pipeline 19 type Pipeline struct { 20 UUID string 21 Data []byte 22 FileName string 23 Replace bool 24 } 25 26 // Uploads the pipeline to the Buildkite Agent API. This request doesn't use JSON, 27 // but a multi-part HTTP form upload 28 func (cs *PipelinesService) Upload(jobId string, pipeline *Pipeline) (*Response, error) { 29 body := &bytes.Buffer{} 30 writer := multipart.NewWriter(body) 31 32 // Default the filename 33 fileName := pipeline.FileName 34 if fileName == "" { 35 fileName = "pipeline" 36 } 37 38 // Calculate the mime type based on the filename 39 extension := filepath.Ext(fileName) 40 contentType := mime.TypeByExtension(extension) 41 if contentType == "" { 42 contentType = "binary/octet-stream" 43 } 44 45 // Write the pipeline to the form 46 part, _ := createFormFileWithContentType(writer, "pipeline", fileName, contentType) 47 part.Write([]byte(pipeline.Data)) 48 49 // Add the replace option 50 writer.WriteField("replace", fmt.Sprintf("%t", pipeline.Replace)) 51 52 // The pipeline upload endpoint requires a way for it to uniquely 53 // identify this upload (because it's an idempotent endpoint). If a job 54 // tries to upload a pipeline that matches a previously uploaded one 55 // with a matching uuid, then it'll just return and not do anything. 56 writer.WriteField("uuid", pipeline.UUID) 57 58 // Close the writer because we don't need to add any more values to it 59 err := writer.Close() 60 if err != nil { 61 return nil, err 62 } 63 64 u := fmt.Sprintf("jobs/%s/pipelines", jobId) 65 req, err := cs.client.NewFormRequest("POST", u, body) 66 if err != nil { 67 return nil, err 68 } 69 70 req.Header.Add("Content-Type", writer.FormDataContentType()) 71 72 return cs.client.Do(req, nil) 73 }