hmdeploy/docker/client.go

51 lines
962 B
Go

package docker
import (
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
)
type IClient interface {
Save(imageName, dest string) (string, error)
}
var ErrDockerClientSave = errors.New("unable to save image into tar")
type Client struct{}
var _ IClient = (*Client)(nil)
func NewClient() Client {
return Client{}
}
func (c *Client) Save(imageName, dest string) (string, error) {
destInfo, err := os.Stat(dest)
if err != nil {
return "", fmt.Errorf("unable to stat file, dir=%s, err=%v", dest, err)
}
if !destInfo.IsDir() {
return "", fmt.Errorf("dest file must be a directory, dir=%s, err=%v", dest, err)
}
tarFile := fmt.Sprintf("%s.tar", imageName)
cmd := exec.Command("docker", "save", "-o", tarFile, imageName)
cmd.Dir = dest
if _, err := cmd.Output(); err != nil {
return "", fmt.Errorf(
"%w, dir=%s, image=%s, err=%v",
ErrDockerClientSave,
dest,
imageName,
err,
)
}
return filepath.Join(dest, tarFile), nil
}