| 1 | |
| 2 | |
| 3 | |
| 4 | package fileutils |
| 5 | |
| 6 | import ( |
| 7 | "context" |
| 8 | "errors" |
| 9 | "fmt" |
| 10 | "path" |
| 11 | |
| 12 | "github.com/sirupsen/logrus" |
| 13 | |
| 14 | "github.com/lima-vm/lima/v2/pkg/downloader" |
| 15 | "github.com/lima-vm/lima/v2/pkg/limatype" |
| 16 | ) |
| 17 | |
| 18 | |
| 19 | var ErrSkipped = errors.New("skipped to download") |
| 20 | |
| 21 | |
| 22 | func DownloadFile(ctx context.Context, dest string, f limatype.File, decompress bool, description string, expectedArch limatype.Arch, supportedImageFormats []string) (string, error) { |
| 23 | if f.Arch != expectedArch { |
| 24 | return "", fmt.Errorf("%w: %#q: unsupported arch: %#q", ErrSkipped, f.Location, f.Arch) |
| 25 | } |
| 26 | fields := logrus.Fields{"location": f.Location, "arch": f.Arch, "digest": f.Digest} |
| 27 | logrus.WithFields(fields).Infof("Attempting to download %s", description) |
| 28 | opts := []downloader.Opt{ |
| 29 | downloader.WithCache(), |
| 30 | downloader.WithDecompress(decompress), |
| 31 | downloader.WithDescription(fmt.Sprintf("%s (%s)", description, path.Base(f.Location))), |
| 32 | downloader.WithExpectedDigest(f.Digest), |
| 33 | } |
| 34 | if len(supportedImageFormats) > 0 { |
| 35 | opts = append(opts, downloader.WithImageFormats(supportedImageFormats)) |
| 36 | } |
| 37 | |
| 38 | res, err := downloader.Download(ctx, dest, f.Location, opts...) |
| 39 | if err != nil { |
| 40 | return "", fmt.Errorf("failed to download %#q: %w", f.Location, err) |
| 41 | } |
| 42 | logrus.Debugf("res.ValidatedDigest=%v", res.ValidatedDigest) |
| 43 | switch res.Status { |
| 44 | case downloader.StatusDownloaded: |
| 45 | logrus.Infof("Downloaded %s from %#q", description, f.Location) |
| 46 | case downloader.StatusUsedCache: |
| 47 | logrus.Infof("Using cache %#q", res.CachePath) |
| 48 | default: |
| 49 | logrus.Warnf("Unexpected result from downloader.Download(): %+v", res) |
| 50 | } |
| 51 | return res.CachePath, nil |
| 52 | } |
| 53 | |
| 54 | |
| 55 | func CachedFile(f limatype.File) (string, error) { |
| 56 | res, err := downloader.Cached(f.Location, |
| 57 | downloader.WithCache(), |
| 58 | downloader.WithExpectedDigest(f.Digest)) |
| 59 | if err != nil { |
| 60 | return "", fmt.Errorf("cache did not contain %#q: %w", f.Location, err) |
| 61 | } |
| 62 | return res.CachePath, nil |
| 63 | } |
| 64 | |
| 65 | |
| 66 | |
| 67 | func Errors(errs []error) error { |
| 68 | var finalErr error |
| 69 | for _, err := range errs { |
| 70 | if errors.Is(err, ErrSkipped) { |
| 71 | logrus.Debug(err) |
| 72 | } else { |
| 73 | finalErr = errors.Join(finalErr, err) |
| 74 | } |
| 75 | } |
| 76 | if len(errs) > 0 && finalErr == nil { |
| 77 | |
| 78 | finalErr = fmt.Errorf("%v", errs) |
| 79 | } |
| 80 | return finalErr |
| 81 | } |