builder.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package docker
  2. import (
  3. "bufio"
  4. "context"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "github.com/docker/docker/api/types"
  10. "github.com/docker/docker/pkg/archive"
  11. )
  12. // BuildLocal
  13. func (a *Agent) BuildLocal(dockerfilePath, tag, buildContext string) error {
  14. tar, err := archive.TarWithOptions(buildContext, &archive.TarOptions{})
  15. if err != nil {
  16. return err
  17. }
  18. res, err := a.client.ImageBuild(context.Background(), tar, types.ImageBuildOptions{
  19. Dockerfile: dockerfilePath,
  20. Tags: []string{tag},
  21. Remove: true,
  22. })
  23. if err != nil {
  24. return err
  25. }
  26. return readBuildLogs(res.Body)
  27. }
  28. // TODO -- do something with these build logs (probably stream to Porter)
  29. type ErrorLine struct {
  30. Error string `json:"error"`
  31. ErrorDetail ErrorDetail `json:"errorDetail"`
  32. }
  33. type ErrorDetail struct {
  34. Message string `json:"message"`
  35. }
  36. func readBuildLogs(rd io.ReadCloser) error {
  37. var lastLine string
  38. scanner := bufio.NewScanner(rd)
  39. for scanner.Scan() {
  40. lastLine = scanner.Text()
  41. fmt.Println(scanner.Text())
  42. }
  43. errLine := &ErrorLine{}
  44. json.Unmarshal([]byte(lastLine), errLine)
  45. if errLine.Error != "" {
  46. return errors.New(errLine.Error)
  47. }
  48. if err := scanner.Err(); err != nil {
  49. return err
  50. }
  51. return nil
  52. }