|
7 | 7 | "io" |
8 | 8 | "net/http" |
9 | 9 | "runtime" |
| 10 | + "strconv" |
10 | 11 | "strings" |
11 | 12 | "syscall" |
12 | 13 | "time" |
@@ -59,11 +60,64 @@ var defaultRetryPredicate = func(err error) bool { |
59 | 60 | return false |
60 | 61 | } |
61 | 62 |
|
| 63 | +type progressWriter struct { |
| 64 | + written int64 |
| 65 | + total int64 |
| 66 | + fileName string |
| 67 | + downloadStatus func(string, string, string, float64) |
| 68 | +} |
| 69 | + |
| 70 | +func formatBytes(bytes int64) string { |
| 71 | + const unit = 1024 |
| 72 | + if bytes < unit { |
| 73 | + return strconv.FormatInt(bytes, 10) + " B" |
| 74 | + } |
| 75 | + div, exp := int64(unit), 0 |
| 76 | + for n := bytes / unit; n >= unit; n /= unit { |
| 77 | + div *= unit |
| 78 | + exp++ |
| 79 | + } |
| 80 | + return fmt.Sprintf("%.1f %ciB", float64(bytes)/float64(div), "KMGTPE"[exp]) |
| 81 | +} |
| 82 | + |
| 83 | +func (pw *progressWriter) Write(p []byte) (int, error) { |
| 84 | + n := len(p) |
| 85 | + pw.written += int64(n) |
| 86 | + if pw.total > 0 { |
| 87 | + percentage := float64(pw.written) / float64(pw.total) * 100 |
| 88 | + //log.Debug().Msgf("Downloading %s: %s/%s (%.2f%%)", pw.fileName, formatBytes(pw.written), formatBytes(pw.total), percentage) |
| 89 | + pw.downloadStatus(pw.fileName, formatBytes(pw.written), formatBytes(pw.total), percentage) |
| 90 | + } else { |
| 91 | + pw.downloadStatus(pw.fileName, formatBytes(pw.written), "", 0) |
| 92 | + } |
| 93 | + |
| 94 | + return n, nil |
| 95 | +} |
| 96 | + |
62 | 97 | // ExtractOCIImage will extract a given targetImage into a given targetDestination |
63 | | -func ExtractOCIImage(img v1.Image, targetDestination string) error { |
64 | | - reader := mutate.Extract(img) |
| 98 | +func ExtractOCIImage(img v1.Image, targetDestination string, downloadStatus func(string, string, string, float64)) error { |
| 99 | + var reader io.Reader |
| 100 | + reader = mutate.Extract(img) |
| 101 | + |
| 102 | + if downloadStatus != nil { |
| 103 | + var totalSize int64 |
| 104 | + layers, err := img.Layers() |
| 105 | + if err != nil { |
| 106 | + return err |
| 107 | + } |
| 108 | + for _, layer := range layers { |
| 109 | + size, err := layer.Size() |
| 110 | + if err != nil { |
| 111 | + return err |
| 112 | + } |
| 113 | + totalSize += size |
| 114 | + } |
| 115 | + reader = io.TeeReader(reader, &progressWriter{total: totalSize, downloadStatus: downloadStatus}) |
| 116 | + } |
65 | 117 |
|
66 | | - _, err := archive.Apply(context.Background(), targetDestination, reader, archive.WithNoSameOwner()) |
| 118 | + _, err := archive.Apply(context.Background(), |
| 119 | + targetDestination, reader, |
| 120 | + archive.WithNoSameOwner()) |
67 | 121 |
|
68 | 122 | return err |
69 | 123 | } |
|
0 commit comments