Debian Codegraph @

match.go

raw symbols SCIP
1 package filetype
2
3 import (
4 "io"
5 "os"
6
7 "github.com/h2non/filetype/matchers"
8 "github.com/h2non/filetype/types"
9 )
10
11 // Matchers is an alias to matchers.Matchers
12 var Matchers = matchers.Matchers
13
14 // MatcherKeys is an alias to matchers.MatcherKeys
15 var MatcherKeys = &matchers.MatcherKeys
16
17 // NewMatcher is an alias to matchers.NewMatcher
18 var NewMatcher = matchers.NewMatcher
19
20 // Match infers the file type of a given buffer inspecting its magic numbers signature
21 func Match(buf []byte) (types.Type, error) {
22 length := len(buf)
23 if length == 0 {
24 return types.Unknown, ErrEmptyBuffer
25 }
26
27 for _, kind := range *MatcherKeys {
28 checker := Matchers[kind]
29 match := checker(buf)
30 if match != types.Unknown && match.Extension != "" {
31 return match, nil
32 }
33 }
34
35 return types.Unknown, nil
36 }
37
38 // Get is an alias to Match()
39 func Get(buf []byte) (types.Type, error) {
40 return Match(buf)
41 }
42
43 // MatchFile infers a file type for a file
44 func MatchFile(filepath string) (types.Type, error) {
45 file, err := os.Open(filepath)
46 if err != nil {
47 return types.Unknown, err
48 }
49 defer file.Close()
50
51 return MatchReader(file)
52 }
53
54 // MatchReader is convenient wrapper to Match() any Reader
55 func MatchReader(reader io.Reader) (types.Type, error) {
56 buffer := make([]byte, 8192) // 8K makes msooxml tests happy and allows for expanded custom file checks
57
58 _, err := reader.Read(buffer)
59 if err != nil && err != io.EOF {
60 return types.Unknown, err
61 }
62
63 return Match(buffer)
64 }
65
66 // AddMatcher registers a new matcher type
67 func AddMatcher(fileType types.Type, matcher matchers.Matcher) matchers.TypeMatcher {
68 return matchers.NewMatcher(fileType, matcher)
69 }
70
71 // Matches checks if the given buffer matches with some supported file type
72 func Matches(buf []byte) bool {
73 kind, _ := Match(buf)
74 return kind != types.Unknown
75 }
76
77 // MatchMap performs a file matching against a map of match functions
78 func MatchMap(buf []byte, matchers matchers.Map) types.Type {
79 for kind, matcher := range matchers {
80 if matcher(buf) {
81 return kind
82 }
83 }
84 return types.Unknown
85 }
86
87 // MatchesMap is an alias to Matches() but using matching against a map of match functions
88 func MatchesMap(buf []byte, matchers matchers.Map) bool {
89 return MatchMap(buf, matchers) != types.Unknown
90 }