package docker import ( "context" "fmt" "strings" "time" ) // Images lists local images. func (s *Service) Images(ctx context.Context) ([]Image, error) { out, err := s.run(ctx, 10*time.Second, "image", "ls", "--no-trunc", "--format", "{{json .}}") if err != nil { return nil, err } rows := jsonLines(out.Stdout) images := make([]Image, 0, len(rows)) for _, row := range rows { images = append(images, Image{ ID: textField(row, "ID"), Repository: textField(row, "Repository"), Tag: textField(row, "Tag"), Size: textField(row, "Size"), CreatedAt: textField(row, "CreatedAt"), }) } return images, nil } // PullImage pulls one image reference. func (s *Service) PullImage(ctx context.Context, ref string) (string, error) { ref = strings.TrimSpace(ref) if !imageRefRe.MatchString(ref) { return "", fmt.Errorf("%w: 镜像名称不合法", ErrInvalid) } res, err := s.run(ctx, 20*time.Minute, "pull", ref) if err != nil { return "", err } return clip(strings.TrimSpace(res.Stdout+"\n"+res.Stderr), 16<<10), nil } // RemoveImage removes one image by tag or ID. func (s *Service) RemoveImage(ctx context.Context, ref string) error { ref = strings.TrimSpace(ref) if !validImageRef(ref) { return fmt.Errorf("%w: 镜像引用不合法", ErrInvalid) } _, err := s.run(ctx, 60*time.Second, "rmi", ref) return err } func validImageRef(ref string) bool { if imageRefRe.MatchString(ref) { return true } if strings.HasPrefix(ref, "sha256:") { hexPart := strings.TrimPrefix(ref, "sha256:") return len(hexPart) >= 12 && len(hexPart) <= 64 && isHex(hexPart) } return false } func isHex(s string) bool { for _, r := range s { if (r < '0' || r > '9') && (r < 'a' || r > 'f') && (r < 'A' || r > 'F') { return false } } return len(s) > 0 }