Debian Codegraph @

image/autodetect.go

raw symbols SCIP
1 // Copyright 2016 The Linux Foundation
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
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 // supported autodetection types
27 const (
28 TypeImageLayout = "imageLayout"
29 TypeImage = "image"
30 TypeImageZip = "imageZip"
31 TypeManifest = "manifest"
32 TypeImageIndex = "imageIndex"
33 TypeConfig = "config"
34 )
35
36 // Autodetect detects the validation type for the given path
37 // or an error if the validation type could not be resolved.
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") // err from os.Stat includes path name
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") // os.Open includes the filename
51 }
52 defer f.Close()
53
54 buf, err := ioutil.ReadAll(io.LimitReader(f, 512)) // read some initial bytes to detect content
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 }