| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
package image |
| 16 |
|
| 17 |
import ( |
| 18 |
"io" |
| 19 |
"io/ioutil" |
| 20 |
"net/http" |
| 21 |
"os" |
| 22 |
|
| 23 |
"github.com/pkg/errors" |
| 24 |
) |
| 25 |
|
| 26 |
|
| 27 |
const ( |
| 28 |
TypeImageLayout = "imageLayout" |
| 29 |
TypeImage = "image" |
| 30 |
TypeImageZip = "imageZip" |
| 31 |
TypeManifest = "manifest" |
| 32 |
TypeImageIndex = "imageIndex" |
| 33 |
TypeConfig = "config" |
| 34 |
) |
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
func Autodetect(path string) (string, error) { |
| 39 |
fi, err := os.Stat(path) |
| 40 |
if err != nil { |
| 41 |
return "", errors.Wrapf(err, "unable to access path") |
| 42 |
} |
| 43 |
|
| 44 |
if fi.IsDir() { |
| 45 |
return TypeImageLayout, nil |
| 46 |
} |
| 47 |
|
| 48 |
f, err := os.Open(path) |
| 49 |
if err != nil { |
| 50 |
return "", errors.Wrap(err, "unable to open file") |
| 51 |
} |
| 52 |
defer f.Close() |
| 53 |
|
| 54 |
buf, err := ioutil.ReadAll(io.LimitReader(f, 512)) |
| 55 |
if err != nil { |
| 56 |
return "", errors.Wrap(err, "unable to read") |
| 57 |
} |
| 58 |
|
| 59 |
mimeType := http.DetectContentType(buf) |
| 60 |
|
| 61 |
switch mimeType { |
| 62 |
case "application/x-gzip", "application/x-rar-compressed", "application/octet-stream": |
| 63 |
return TypeImage, nil |
| 64 |
case "application/zip": |
| 65 |
return TypeImageZip, nil |
| 66 |
} |
| 67 |
|
| 68 |
return "", errors.New("unknown file type") |
| 69 |
} |